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 index 6174687..37560f0 100644 --- a/App.xaml +++ b/App.xaml @@ -2,12 +2,15 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ThreadPilot" - xmlns:helpers="clr-namespace:ThreadPilot.Helpers"> + xmlns:helpers="clr-namespace:ThreadPilot.Helpers" + xmlns:converters="clr-namespace:ThreadPilot.Converters"> + + diff --git a/App.xaml.cs b/App.xaml.cs index 40437d7..7c0ff76 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -1,42 +1,91 @@ using System.Windows; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using ThreadPilot.Services; using ThreadPilot.ViewModels; +using System; namespace ThreadPilot { - public partial class App : Application + public partial class App : System.Windows.Application { public IServiceProvider ServiceProvider { get; private set; } public App() { ServiceCollection services = new ServiceCollection(); - ConfigureServices(services); + + // Use the new centralized service configuration + services.ConfigureApplicationServices(); + ServiceProvider = services.BuildServiceProvider(); + + // Validate service configuration + ServiceConfiguration.ValidateServiceConfiguration(ServiceProvider); } - private void ConfigureServices(ServiceCollection services) - { - // Register Services - services.AddSingleton(); - services.AddSingleton(); - // Register ViewModels - services.AddTransient(); - services.AddTransient(); - - // Register Views - services.AddTransient(); - } protected override void OnStartup(StartupEventArgs e) { 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; + } + } + + // 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(); - mainWindow.Show(); + + // Handle startup behavior + if (startMinimized || isAutostart) + { + // Start minimized to tray - let MainWindow handle the minimize to tray logic + mainWindow.WindowState = WindowState.Minimized; + mainWindow.Show(); + + var logger = ServiceProvider.GetRequiredService>(); + logger.LogInformation("Application started minimized to tray (autostart: {IsAutostart})", isAutostart); + } + else + { + // Normal startup - show the window + mainWindow.Show(); + } } + + [System.Runtime.InteropServices.DllImport("kernel32.dll")] + private static extern bool AllocConsole(); } } 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/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/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/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/Data/DataAccessService.cs b/Data/DataAccessService.cs new file mode 100644 index 0000000..84b2dc7 --- /dev/null +++ b/Data/DataAccessService.cs @@ -0,0 +1,252 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Data +{ + /// + /// Implementation of data access service with JSON file repositories + /// + public class DataAccessService : IDataAccessService + { + private readonly ILogger _logger; + private readonly string _dataDirectory; + + public IRepository ProcessAssociations { get; } + public IRepository ApplicationSettings { get; } + public IRepository ProcessProfiles { get; } + + public DataAccessService(ILogger logger, string? dataDirectory = null) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _dataDirectory = dataDirectory ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ThreadPilot", "Data"); + + // Ensure data directory exists + if (!Directory.Exists(_dataDirectory)) + { + Directory.CreateDirectory(_dataDirectory); + } + + // Initialize repositories + var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); + + ProcessAssociations = new JsonRepository( + Path.Combine(_dataDirectory, "ProcessAssociations.json"), + loggerFactory.CreateLogger>()); + + ApplicationSettings = new JsonRepository( + Path.Combine(_dataDirectory, "ApplicationSettings.json"), + loggerFactory.CreateLogger>()); + + ProcessProfiles = new JsonRepository( + Path.Combine(_dataDirectory, "ProcessProfiles.json"), + loggerFactory.CreateLogger>()); + } + + public async Task InitializeAsync() + { + _logger.LogInformation("Initializing data access service with directory: {DataDirectory}", _dataDirectory); + + try + { + // Validate data directory + if (!Directory.Exists(_dataDirectory)) + { + Directory.CreateDirectory(_dataDirectory); + _logger.LogInformation("Created data directory: {DataDirectory}", _dataDirectory); + } + + // Validate data integrity + var validationResult = await ValidateDataIntegrityAsync(); + if (!validationResult.IsValid) + { + _logger.LogWarning("Data validation found {IssueCount} issues: {Issues}", + validationResult.Issues.Length, string.Join(", ", validationResult.Issues)); + } + + _logger.LogInformation("Data access service initialized successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize data access service"); + throw; + } + } + + public async Task BackupDataAsync(string backupDirectory) + { + if (string.IsNullOrEmpty(backupDirectory)) + throw new ArgumentException("Backup directory cannot be null or empty", nameof(backupDirectory)); + + try + { + if (!Directory.Exists(backupDirectory)) + { + Directory.CreateDirectory(backupDirectory); + } + + var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var backupPath = Path.Combine(backupDirectory, $"ThreadPilot_Backup_{timestamp}"); + Directory.CreateDirectory(backupPath); + + // Copy all data files + var dataFiles = Directory.GetFiles(_dataDirectory, "*.json"); + foreach (var file in dataFiles) + { + var fileName = Path.GetFileName(file); + var destPath = Path.Combine(backupPath, fileName); + File.Copy(file, destPath, true); + } + + _logger.LogInformation("Data backed up to: {BackupPath}", backupPath); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to backup data to {BackupDirectory}", backupDirectory); + throw; + } + } + + public async Task RestoreDataAsync(string backupDirectory) + { + if (string.IsNullOrEmpty(backupDirectory)) + throw new ArgumentException("Backup directory cannot be null or empty", nameof(backupDirectory)); + + if (!Directory.Exists(backupDirectory)) + throw new DirectoryNotFoundException($"Backup directory not found: {backupDirectory}"); + + try + { + // Copy backup files to data directory + var backupFiles = Directory.GetFiles(backupDirectory, "*.json"); + foreach (var file in backupFiles) + { + var fileName = Path.GetFileName(file); + var destPath = Path.Combine(_dataDirectory, fileName); + File.Copy(file, destPath, true); + } + + _logger.LogInformation("Data restored from: {BackupDirectory}", backupDirectory); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to restore data from {BackupDirectory}", backupDirectory); + throw; + } + } + + public async Task ValidateDataIntegrityAsync() + { + var issues = new List(); + var totalRecords = 0; + var validRecords = 0; + + try + { + // Validate process associations + var associations = await ProcessAssociations.GetAllAsync(); + totalRecords += associations.Count(); + + foreach (var association in associations) + { + var validation = association.Validate(); + if (validation.IsValid) + { + validRecords++; + } + else + { + issues.AddRange(validation.Errors.Select(e => $"ProcessAssociation {association.Id}: {e}")); + } + } + + // Validate application settings + var settings = await ApplicationSettings.GetAllAsync(); + totalRecords += settings.Count(); + + foreach (var setting in settings) + { + var validation = setting.Validate(); + if (validation.IsValid) + { + validRecords++; + } + else + { + issues.AddRange(validation.Errors.Select(e => $"ApplicationSettings {setting.Id}: {e}")); + } + } + + // Validate process profiles + var profiles = await ProcessProfiles.GetAllAsync(); + totalRecords += profiles.Count(); + + foreach (var profile in profiles) + { + var validation = profile.Validate(); + if (validation.IsValid) + { + validRecords++; + } + else + { + issues.AddRange(validation.Errors.Select(e => $"ProcessProfile {profile.Id}: {e}")); + } + } + + var isValid = issues.Count == 0; + return new DataValidationResult(isValid, totalRecords, validRecords, issues.ToArray()); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to validate data integrity"); + issues.Add($"Validation failed: {ex.Message}"); + return new DataValidationResult(false, totalRecords, validRecords, issues.ToArray()); + } + } + + public async Task CleanupDataAsync() + { + try + { + _logger.LogInformation("Starting data cleanup"); + + // Remove invalid associations + var associations = await ProcessAssociations.GetAllAsync(); + var invalidAssociations = associations.Where(a => !a.Validate().IsValid).ToList(); + + foreach (var invalid in invalidAssociations) + { + await ProcessAssociations.DeleteAsync(invalid.Id); + _logger.LogDebug("Removed invalid association: {AssociationId}", invalid.Id); + } + + // Remove duplicate profiles + var profiles = await ProcessProfiles.GetAllAsync(); + var duplicateProfiles = profiles + .GroupBy(p => p.Name) + .Where(g => g.Count() > 1) + .SelectMany(g => g.Skip(1)) + .ToList(); + + foreach (var duplicate in duplicateProfiles) + { + await ProcessProfiles.DeleteAsync(duplicate.Id); + _logger.LogDebug("Removed duplicate profile: {ProfileId}", duplicate.Id); + } + + _logger.LogInformation("Data cleanup completed. Removed {InvalidCount} invalid associations and {DuplicateCount} duplicate profiles", + invalidAssociations.Count, duplicateProfiles.Count); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to cleanup data"); + throw; + } + } + } +} diff --git a/Data/IDataAccessService.cs b/Data/IDataAccessService.cs new file mode 100644 index 0000000..058a4bb --- /dev/null +++ b/Data/IDataAccessService.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Data +{ + /// + /// Service for coordinating data access operations across all repositories + /// + public interface IDataAccessService + { + /// + /// Get repository for process-power plan associations + /// + IRepository ProcessAssociations { get; } + + /// + /// Get repository for application settings + /// + IRepository ApplicationSettings { get; } + + /// + /// Get repository for process profiles + /// + IRepository ProcessProfiles { get; } + + /// + /// Initialize all repositories + /// + Task InitializeAsync(); + + /// + /// Backup all data to specified directory + /// + Task BackupDataAsync(string backupDirectory); + + /// + /// Restore data from backup directory + /// + Task RestoreDataAsync(string backupDirectory); + + /// + /// Validate data integrity across all repositories + /// + Task ValidateDataIntegrityAsync(); + + /// + /// Clean up orphaned or invalid data + /// + Task CleanupDataAsync(); + } + + /// + /// Result of data validation operation + /// + public class DataValidationResult + { + public bool IsValid { get; } + public string[] Issues { get; } + public int TotalRecords { get; } + public int ValidRecords { get; } + + public DataValidationResult(bool isValid, int totalRecords, int validRecords, params string[] issues) + { + IsValid = isValid; + TotalRecords = totalRecords; + ValidRecords = validRecords; + Issues = issues ?? Array.Empty(); + } + } +} diff --git a/Data/IRepository.cs b/Data/IRepository.cs new file mode 100644 index 0000000..80902e2 --- /dev/null +++ b/Data/IRepository.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace ThreadPilot.Data +{ + /// + /// Generic repository interface for data access operations + /// + /// Entity type + /// Key type + public interface IRepository where T : class + { + /// + /// Get entity by ID + /// + Task GetByIdAsync(TKey id); + + /// + /// Get all entities + /// + Task> GetAllAsync(); + + /// + /// Find entities matching predicate + /// + Task> FindAsync(Expression> predicate); + + /// + /// Add new entity + /// + Task AddAsync(T entity); + + /// + /// Update existing entity + /// + Task UpdateAsync(T entity); + + /// + /// Delete entity by ID + /// + Task DeleteAsync(TKey id); + + /// + /// Delete entity + /// + Task DeleteAsync(T entity); + + /// + /// Check if entity exists + /// + Task ExistsAsync(TKey id); + + /// + /// Get count of entities + /// + Task CountAsync(); + + /// + /// Get count of entities matching predicate + /// + Task CountAsync(Expression> predicate); + } + + /// + /// Repository interface for entities with string keys + /// + /// Entity type + public interface IRepository : IRepository where T : class + { + } + + /// + /// Unit of work pattern for coordinating multiple repository operations + /// + public interface IUnitOfWork : IDisposable + { + /// + /// Get repository for entity type + /// + IRepository GetRepository() where T : class; + + /// + /// Save all changes + /// + Task SaveChangesAsync(); + + /// + /// Begin transaction + /// + Task BeginTransactionAsync(); + + /// + /// Commit transaction + /// + Task CommitTransactionAsync(); + + /// + /// Rollback transaction + /// + Task RollbackTransactionAsync(); + } +} diff --git a/Data/JsonRepository.cs b/Data/JsonRepository.cs new file mode 100644 index 0000000..b60efb0 --- /dev/null +++ b/Data/JsonRepository.cs @@ -0,0 +1,184 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Text.Json; +using System.Threading.Tasks; +using ThreadPilot.Models.Core; + +namespace ThreadPilot.Data +{ + /// + /// JSON file-based repository implementation + /// + /// Entity type that implements IModel + public class JsonRepository : IRepository where T : class, IModel + { + private readonly string _filePath; + private readonly ILogger> _logger; + private readonly JsonSerializerOptions _jsonOptions; + private readonly SemaphoreSlim _fileLock = new(1, 1); + + public JsonRepository(string filePath, ILogger> logger) + { + _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + _jsonOptions = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + // Ensure directory exists + var directory = Path.GetDirectoryName(_filePath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + } + + public async Task GetByIdAsync(string id) + { + var entities = await GetAllAsync(); + return entities.FirstOrDefault(e => e.Id == id); + } + + public async Task> GetAllAsync() + { + await _fileLock.WaitAsync(); + try + { + if (!File.Exists(_filePath)) + { + return new List(); + } + + var json = await File.ReadAllTextAsync(_filePath); + if (string.IsNullOrWhiteSpace(json)) + { + return new List(); + } + + var entities = JsonSerializer.Deserialize>(json, _jsonOptions); + return entities ?? new List(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to read entities from {FilePath}", _filePath); + return new List(); + } + finally + { + _fileLock.Release(); + } + } + + public async Task> FindAsync(Expression> predicate) + { + var entities = await GetAllAsync(); + var compiledPredicate = predicate.Compile(); + return entities.Where(compiledPredicate); + } + + public async Task AddAsync(T entity) + { + if (entity == null) throw new ArgumentNullException(nameof(entity)); + + var entities = (await GetAllAsync()).ToList(); + + // Check if entity already exists + if (entities.Any(e => e.Id == entity.Id)) + { + throw new InvalidOperationException($"Entity with ID {entity.Id} already exists"); + } + + entities.Add(entity); + await SaveAllAsync(entities); + + _logger.LogDebug("Added entity {EntityType} with ID {EntityId}", typeof(T).Name, entity.Id); + return entity; + } + + public async Task UpdateAsync(T entity) + { + if (entity == null) throw new ArgumentNullException(nameof(entity)); + + var entities = (await GetAllAsync()).ToList(); + var existingIndex = entities.FindIndex(e => e.Id == entity.Id); + + if (existingIndex == -1) + { + throw new InvalidOperationException($"Entity with ID {entity.Id} not found"); + } + + entities[existingIndex] = entity; + await SaveAllAsync(entities); + + _logger.LogDebug("Updated entity {EntityType} with ID {EntityId}", typeof(T).Name, entity.Id); + return entity; + } + + public async Task DeleteAsync(string id) + { + var entities = (await GetAllAsync()).ToList(); + var entityToRemove = entities.FirstOrDefault(e => e.Id == id); + + if (entityToRemove == null) + { + return false; + } + + entities.Remove(entityToRemove); + await SaveAllAsync(entities); + + _logger.LogDebug("Deleted entity {EntityType} with ID {EntityId}", typeof(T).Name, id); + return true; + } + + public async Task DeleteAsync(T entity) + { + if (entity == null) throw new ArgumentNullException(nameof(entity)); + return await DeleteAsync(entity.Id); + } + + public async Task ExistsAsync(string id) + { + var entities = await GetAllAsync(); + return entities.Any(e => e.Id == id); + } + + public async Task CountAsync() + { + var entities = await GetAllAsync(); + return entities.Count(); + } + + public async Task CountAsync(Expression> predicate) + { + var entities = await FindAsync(predicate); + return entities.Count(); + } + + private async Task SaveAllAsync(IEnumerable entities) + { + await _fileLock.WaitAsync(); + try + { + var json = JsonSerializer.Serialize(entities, _jsonOptions); + await File.WriteAllTextAsync(_filePath, json); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to save entities to {FilePath}", _filePath); + throw; + } + finally + { + _fileLock.Release(); + } + } + } +} 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 index dfcd093..5f8e539 100644 --- a/Helpers/AffinityHelper.cs +++ b/Helpers/AffinityHelper.cs @@ -6,14 +6,14 @@ namespace ThreadPilot.Helpers { public static class AffinityHelper { - public static long CalculateAffinityMask(IEnumerable cpuCheckboxes) + 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) + public static void UpdateCheckboxesFromMask(IEnumerable cpuCheckboxes, long affinityMask) { foreach (var checkbox in cpuCheckboxes) { diff --git a/MainWindow.xaml b/MainWindow.xaml index af90634..88b6da2 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -12,10 +12,6 @@ Width="1280" WindowStartupLocation="CenterScreen"> - - - - @@ -24,16 +20,38 @@ - + - + + + + + + + + + + - + + + + + + + + + + diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index 28017ba..1eb5a80 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -1,5 +1,12 @@ -using System.Windows; +using System; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; using ThreadPilot.ViewModels; +using ThreadPilot.Services; +using ThreadPilot.Views; +using ThreadPilot.Tests; +using Microsoft.Extensions.DependencyInjection; namespace ThreadPilot { @@ -7,20 +14,419 @@ namespace ThreadPilot { private readonly ProcessViewModel _processViewModel; private readonly PowerPlanViewModel _powerPlanViewModel; + private readonly ProcessPowerPlanAssociationViewModel _associationViewModel; + private readonly ISystemTrayService _systemTrayService; + private readonly IApplicationSettingsService _settingsService; + private readonly INotificationService _notificationService; + private readonly IProcessMonitorService _processMonitorService; + private readonly IProcessMonitorManagerService _processMonitorManagerService; + private readonly IGameBoostService _gameBoostService; + private readonly SettingsViewModel _settingsViewModel; + private readonly MainWindowViewModel _mainWindowViewModel; + private readonly IServiceProvider _serviceProvider; - public MainWindow(ProcessViewModel processViewModel, PowerPlanViewModel powerPlanViewModel) + public MainWindow( + ProcessViewModel processViewModel, + PowerPlanViewModel powerPlanViewModel, + ProcessPowerPlanAssociationViewModel associationViewModel, + ISystemTrayService systemTrayService, + IApplicationSettingsService settingsService, + INotificationService notificationService, + IProcessMonitorService processMonitorService, + IProcessMonitorManagerService processMonitorManagerService, + IGameBoostService gameBoostService, + SettingsViewModel settingsViewModel, + MainWindowViewModel mainWindowViewModel, + IServiceProvider serviceProvider) { InitializeComponent(); _processViewModel = processViewModel; _powerPlanViewModel = powerPlanViewModel; + _associationViewModel = associationViewModel; + _systemTrayService = systemTrayService; + _settingsService = settingsService; + _notificationService = notificationService; + _processMonitorService = processMonitorService; + _processMonitorManagerService = processMonitorManagerService; + _gameBoostService = gameBoostService; + _settingsViewModel = settingsViewModel; + _mainWindowViewModel = mainWindowViewModel; + _serviceProvider = serviceProvider; + SetDataContexts(); LoadViewModels(); + InitializeServices(); + SetupTestKeyBinding(); + } + + private void SetDataContexts() + { + // Set DataContext for the main window + DataContext = _mainWindowViewModel; + + // Set DataContext for the association view + AssociationView.DataContext = _associationViewModel; } private async void LoadViewModels() { await _processViewModel.LoadProcesses(); await _powerPlanViewModel.LoadPowerPlans(); + // The association view model loads its data automatically in its constructor + } + + private async void InitializeServices() + { + await InitializeSettingsAsync(); + InitializeSystemTray(); + InitializeNotifications(); + InitializeGameBoost(); + await InitializeMonitoringAsync(); + await StartProcessMonitoringManagerAsync(); + } + + private async Task InitializeSettingsAsync() + { + try + { + await _settingsService.LoadSettingsAsync(); + + // Apply initial settings + var settings = _settingsService.Settings; + if (settings.StartMinimized) + { + WindowState = WindowState.Minimized; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}"); + } + } + + private void InitializeSystemTray() + { + try + { + _systemTrayService.Initialize(); + _systemTrayService.Show(); + + // Subscribe to tray events + _systemTrayService.ShowMainWindowRequested += OnShowMainWindowRequested; + _systemTrayService.ExitRequested += OnExitRequested; + _systemTrayService.MonitoringToggleRequested += OnMonitoringToggleRequested; + _systemTrayService.SettingsRequested += OnSettingsRequested; + + // Update settings and tooltip + _systemTrayService.UpdateSettings(_settingsService.Settings); + _systemTrayService.UpdateTooltip("ThreadPilot - Process & Power Plan Manager"); + } + catch (Exception ex) + { + // Log error but don't fail startup + System.Diagnostics.Debug.WriteLine($"Failed to initialize system tray: {ex.Message}"); + } + } + + private void OnShowMainWindowRequested(object? sender, EventArgs e) + { + Show(); + WindowState = WindowState.Normal; + Activate(); + } + + private void OnExitRequested(object? sender, EventArgs e) + { + System.Windows.Application.Current.Shutdown(); + } + + private async void OnMonitoringToggleRequested(object? sender, MonitoringToggleEventArgs e) + { + try + { + if (e.EnableMonitoring) + { + await _processMonitorManagerService.StartAsync(); + await _notificationService.ShowSuccessNotificationAsync( + "Monitoring Enabled", + "Process monitoring and power plan management has been enabled"); + } + else + { + await _processMonitorManagerService.StopAsync(); + await _notificationService.ShowNotificationAsync( + "Monitoring Disabled", + "Process monitoring and power plan management has been disabled", + Models.NotificationType.Warning); + } + } + catch (Exception ex) + { + await _notificationService.ShowErrorNotificationAsync( + "Monitoring Error", + "Failed to toggle process monitoring", + ex); + } + } + + private void OnSettingsRequested(object? sender, EventArgs e) + { + try + { + var settingsWindow = new SettingsWindow(_settingsViewModel); + settingsWindow.Owner = this; + settingsWindow.ShowDialog(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to open settings: {ex.Message}"); + } + } + + private void InitializeNotifications() + { + try + { + // Subscribe to settings changes to update notification service + _settingsService.SettingsChanged += OnSettingsChanged; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to initialize notifications: {ex.Message}"); + } + } + + private void InitializeGameBoost() + { + try + { + // Subscribe to Game Boost events + _gameBoostService.GameBoostActivated += OnGameBoostActivated; + _gameBoostService.GameBoostDeactivated += OnGameBoostDeactivated; + + // Update initial Game Boost status in tray and main window + _systemTrayService.UpdateGameBoostStatus( + _gameBoostService.IsGameBoostActive, + _gameBoostService.CurrentGameProcess?.Name); + _mainWindowViewModel.UpdateGameBoostStatus( + _gameBoostService.IsGameBoostActive, + _gameBoostService.CurrentGameProcess?.Name); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to initialize Game Boost: {ex.Message}"); + } + } + + private async Task InitializeMonitoringAsync() + { + try + { + // Subscribe to monitoring status changes + _processMonitorService.MonitoringStatusChanged += OnMonitoringStatusChanged; + + // Update tray with initial monitoring status + _systemTrayService.UpdateMonitoringStatus( + _processMonitorService.IsMonitoring, + _processMonitorService.IsWmiAvailable); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to initialize monitoring: {ex.Message}"); + } + } + + private async Task StartProcessMonitoringManagerAsync() + { + try + { + // Subscribe to process monitor manager events + _processMonitorManagerService.ServiceStatusChanged += OnProcessMonitorManagerStatusChanged; + + // Start the process monitoring manager service + await _processMonitorManagerService.StartAsync(); + + await _notificationService.ShowSuccessNotificationAsync( + "ThreadPilot Started", + "Process monitoring and power plan management is now active"); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to start process monitoring manager: {ex.Message}"); + await _notificationService.ShowErrorNotificationAsync( + "Startup Error", + "Failed to start process monitoring manager", + ex); + } + } + + private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e) + { + // Update tray service with new settings + _systemTrayService.UpdateSettings(e.NewSettings); + } + + private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e) + { + // Update tray icon and status + _systemTrayService.UpdateMonitoringStatus(e.IsMonitoring, e.IsWmiAvailable); + + // Show notification if there's an error + if (e.Error != null && _settingsService.Settings.EnableErrorNotifications) + { + _notificationService.ShowErrorNotificationAsync( + "Monitoring Error", + e.StatusMessage ?? "An error occurred with process monitoring", + e.Error); + } + } + + private void OnProcessMonitorManagerStatusChanged(object? sender, ServiceStatusEventArgs e) + { + // Update main window status + _mainWindowViewModel.UpdateProcessMonitoringStatus(e.IsRunning, e.Status); + + // Show notification for critical status changes + if (!e.IsRunning && e.Error != null && _settingsService.Settings.EnableErrorNotifications) + { + _notificationService.ShowErrorNotificationAsync( + "Process Monitoring Error", + e.Details ?? "Process monitoring manager encountered an error", + e.Error); + } + } + + private void OnGameBoostActivated(object? sender, GameBoostActivatedEventArgs e) + { + try + { + // Update tray with Game Boost active status + _systemTrayService.UpdateGameBoostStatus(true, e.GameProcess.Name); + + // Update main window status + _mainWindowViewModel.UpdateGameBoostStatus(true, e.GameProcess.Name); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error handling Game Boost activation: {ex.Message}"); + } + } + + private void OnGameBoostDeactivated(object? sender, GameBoostDeactivatedEventArgs e) + { + try + { + // Update tray with Game Boost inactive status + _systemTrayService.UpdateGameBoostStatus(false); + + // Update main window status + _mainWindowViewModel.UpdateGameBoostStatus(false); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error handling Game Boost deactivation: {ex.Message}"); + } + } + + protected override void OnStateChanged(EventArgs e) + { + try + { + if (WindowState == WindowState.Minimized && _settingsService.Settings.MinimizeToTray) + { + Hide(); + _systemTrayService.Show(); + + // Pause process refresh when minimized to reduce resource usage + if (_processViewModel != null) + { + _processViewModel.PauseRefresh(); + } + } + else if (WindowState == WindowState.Normal) + { + // Resume process refresh when restored + if (_processViewModel != null) + { + _processViewModel.ResumeRefresh(); + } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error handling window state change: {ex.Message}"); + } + + base.OnStateChanged(e); + } + + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) + { + // Check settings for close behavior + if (_settingsService.Settings.CloseToTray) + { + // Minimize to tray instead of closing + e.Cancel = true; + WindowState = WindowState.Minimized; + } + else + { + // Actually close the application + System.Windows.Application.Current.Shutdown(); + } + } + + private void SetupTestKeyBinding() + { + // Add Ctrl+Shift+T to run Game Boost tests + var testCommand = new RoutedCommand(); + var testBinding = new KeyBinding(testCommand, Key.T, ModifierKeys.Control | ModifierKeys.Shift); + InputBindings.Add(testBinding); + CommandBindings.Add(new CommandBinding(testCommand, RunGameBoostTests)); + } + + private async void RunGameBoostTests(object sender, ExecutedRoutedEventArgs e) + { + try + { + _mainWindowViewModel.StatusMessage = "Running Game Boost integration tests..."; + + // Validate service configuration first + if (!ThreadPilot.Tests.TestRunner.ValidateServiceConfiguration(_serviceProvider)) + { + _mainWindowViewModel.StatusMessage = "Service configuration validation failed"; + await _notificationService.ShowErrorNotificationAsync( + "Test Failed", + "Service configuration validation failed"); + return; + } + + // Run integration tests + var testResult = await ThreadPilot.Tests.TestRunner.RunGameBoostTestsAsync(_serviceProvider); + + if (testResult) + { + _mainWindowViewModel.StatusMessage = "All Game Boost tests passed successfully!"; + await _notificationService.ShowSuccessNotificationAsync( + "Tests Passed", + "All Game Boost integration tests completed successfully"); + } + else + { + _mainWindowViewModel.StatusMessage = "Game Boost tests failed - check logs for details"; + await _notificationService.ShowErrorNotificationAsync( + "Tests Failed", + "One or more Game Boost tests failed - check logs for details"); + } + } + catch (Exception ex) + { + _mainWindowViewModel.StatusMessage = $"Test execution failed: {ex.Message}"; + await _notificationService.ShowErrorNotificationAsync( + "Test Error", + "Failed to execute Game Boost tests", + ex); + } } } } \ No newline at end of file diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs new file mode 100644 index 0000000..03a0595 --- /dev/null +++ b/Models/ApplicationSettingsModel.cs @@ -0,0 +1,330 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; +using ThreadPilot.Models.Core; + +namespace ThreadPilot.Models +{ + /// + /// Model for application settings including notifications and tray preferences + /// + public partial class ApplicationSettingsModel : ObservableObject, IModel + { + [ObservableProperty] + private string id = "ApplicationSettings"; // Singleton settings + + [ObservableProperty] + private DateTime createdAt = DateTime.UtcNow; + + [ObservableProperty] + private DateTime updatedAt = DateTime.UtcNow; + + [ObservableProperty] + private bool enableNotifications = true; + + [ObservableProperty] + private bool enableBalloonNotifications = true; + + [ObservableProperty] + private bool enableToastNotifications = true; + + [ObservableProperty] + private bool enablePowerPlanChangeNotifications = true; + + [ObservableProperty] + private bool enableProcessMonitoringNotifications = true; + + [ObservableProperty] + private bool enableErrorNotifications = true; + + [ObservableProperty] + private bool enableSuccessNotifications = true; + + [ObservableProperty] + private bool minimizeToTray = true; + + [ObservableProperty] + private bool closeToTray = false; + + [ObservableProperty] + private bool startMinimized = false; + + [ObservableProperty] + private bool showTrayIcon = true; + + [ObservableProperty] + private bool enableQuickApplyFromTray = true; + + [ObservableProperty] + private bool enableMonitoringControlFromTray = true; + + [ObservableProperty] + private int notificationDisplayDurationMs = 3000; + + [ObservableProperty] + private int balloonNotificationTimeoutMs = 5000; + + [ObservableProperty] + private NotificationPosition notificationPosition = NotificationPosition.BottomRight; + + [ObservableProperty] + private NotificationSound notificationSound = NotificationSound.Default; + + [ObservableProperty] + private bool enableNotificationSound = false; + + [ObservableProperty] + private string customTrayIconPath = string.Empty; + + [ObservableProperty] + private bool useCustomTrayIcon = false; + + [ObservableProperty] + private TrayIconStyle trayIconStyle = TrayIconStyle.Default; + + [ObservableProperty] + private bool showDetailedTooltips = true; + + [ObservableProperty] + private bool enableContextMenuAnimations = true; + + [ObservableProperty] + private bool autoHideNotifications = true; + + [ObservableProperty] + private bool enableNotificationHistory = true; + + [ObservableProperty] + private int maxNotificationHistoryItems = 50; + + // Autostart Settings + [ObservableProperty] + private bool autostartWithWindows = false; + + // Power Plan Settings + [ObservableProperty] + private string defaultPowerPlanId = string.Empty; + + [ObservableProperty] + private string defaultPowerPlanName = "Balanced"; + + [ObservableProperty] + private bool restoreDefaultPowerPlanOnExit = true; + + // Monitoring Settings + [ObservableProperty] + private int pollingIntervalMs = 5000; + + [ObservableProperty] + private int fallbackPollingIntervalMs = 10000; + + [ObservableProperty] + private bool enableWmiMonitoring = true; + + [ObservableProperty] + private bool enableFallbackPolling = true; + + // Game Boost Mode Settings + [ObservableProperty] + private bool enableGameBoostMode = false; + + [ObservableProperty] + private string gameBoostPowerPlanId = string.Empty; + + [ObservableProperty] + private string gameBoostPowerPlanName = "High performance"; + + [ObservableProperty] + private bool gameBoostAutoDetectGames = true; + + [ObservableProperty] + private bool gameBoostSetHighPriority = true; + + [ObservableProperty] + private bool gameBoostOptimizeCpuAffinity = true; + + [ObservableProperty] + private int gameBoostDetectionDelayMs = 2000; + + // Advanced Settings + [ObservableProperty] + private bool enableDebugLogging = false; + + [ObservableProperty] + private bool enablePerformanceCounters = false; + + [ObservableProperty] + private int maxLogFileSizeMb = 10; + + [ObservableProperty] + private int logRetentionDays = 7; + + + + /// + /// Copies settings from another instance + /// + public void CopyFrom(ApplicationSettingsModel other) + { + if (other == null) return; + + EnableNotifications = other.EnableNotifications; + EnableBalloonNotifications = other.EnableBalloonNotifications; + EnableToastNotifications = other.EnableToastNotifications; + EnablePowerPlanChangeNotifications = other.EnablePowerPlanChangeNotifications; + EnableProcessMonitoringNotifications = other.EnableProcessMonitoringNotifications; + EnableErrorNotifications = other.EnableErrorNotifications; + EnableSuccessNotifications = other.EnableSuccessNotifications; + MinimizeToTray = other.MinimizeToTray; + CloseToTray = other.CloseToTray; + StartMinimized = other.StartMinimized; + ShowTrayIcon = other.ShowTrayIcon; + EnableQuickApplyFromTray = other.EnableQuickApplyFromTray; + EnableMonitoringControlFromTray = other.EnableMonitoringControlFromTray; + NotificationDisplayDurationMs = other.NotificationDisplayDurationMs; + BalloonNotificationTimeoutMs = other.BalloonNotificationTimeoutMs; + NotificationPosition = other.NotificationPosition; + NotificationSound = other.NotificationSound; + EnableNotificationSound = other.EnableNotificationSound; + CustomTrayIconPath = other.CustomTrayIconPath; + UseCustomTrayIcon = other.UseCustomTrayIcon; + TrayIconStyle = other.TrayIconStyle; + ShowDetailedTooltips = other.ShowDetailedTooltips; + EnableContextMenuAnimations = other.EnableContextMenuAnimations; + AutoHideNotifications = other.AutoHideNotifications; + EnableNotificationHistory = other.EnableNotificationHistory; + MaxNotificationHistoryItems = other.MaxNotificationHistoryItems; + + // Autostart Settings + AutostartWithWindows = other.AutostartWithWindows; + + // Power Plan Settings + DefaultPowerPlanId = other.DefaultPowerPlanId; + DefaultPowerPlanName = other.DefaultPowerPlanName; + RestoreDefaultPowerPlanOnExit = other.RestoreDefaultPowerPlanOnExit; + + // Monitoring Settings + PollingIntervalMs = other.PollingIntervalMs; + FallbackPollingIntervalMs = other.FallbackPollingIntervalMs; + EnableWmiMonitoring = other.EnableWmiMonitoring; + EnableFallbackPolling = other.EnableFallbackPolling; + + // Game Boost Mode Settings + EnableGameBoostMode = other.EnableGameBoostMode; + GameBoostPowerPlanId = other.GameBoostPowerPlanId; + GameBoostPowerPlanName = other.GameBoostPowerPlanName; + GameBoostAutoDetectGames = other.GameBoostAutoDetectGames; + GameBoostSetHighPriority = other.GameBoostSetHighPriority; + GameBoostOptimizeCpuAffinity = other.GameBoostOptimizeCpuAffinity; + GameBoostDetectionDelayMs = other.GameBoostDetectionDelayMs; + + // Advanced Settings + EnableDebugLogging = other.EnableDebugLogging; + EnablePerformanceCounters = other.EnablePerformanceCounters; + MaxLogFileSizeMb = other.MaxLogFileSizeMb; + LogRetentionDays = other.LogRetentionDays; + } + + // IModel implementation - properties are auto-generated by ObservableProperty + public ValidationResult Validate() + { + var errors = new List(); + + if (NotificationDisplayDurationMs < 1000 || NotificationDisplayDurationMs > 30000) + errors.Add("Notification display duration must be between 1 and 30 seconds"); + + if (PollingIntervalMs < 1000 || PollingIntervalMs > 60000) + errors.Add("Process polling interval must be between 1 and 60 seconds"); + + if (FallbackPollingIntervalMs < 1000 || FallbackPollingIntervalMs > 60000) + errors.Add("Fallback polling interval must be between 1 and 60 seconds"); + + return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); + } + + public IModel Clone() + { + return new ApplicationSettingsModel + { + id = "ApplicationSettings", + EnableNotifications = this.EnableNotifications, + EnableBalloonNotifications = this.EnableBalloonNotifications, + EnableToastNotifications = this.EnableToastNotifications, + EnablePowerPlanChangeNotifications = this.EnablePowerPlanChangeNotifications, + EnableProcessMonitoringNotifications = this.EnableProcessMonitoringNotifications, + EnableErrorNotifications = this.EnableErrorNotifications, + EnableSuccessNotifications = this.EnableSuccessNotifications, + MinimizeToTray = this.MinimizeToTray, + CloseToTray = this.CloseToTray, + StartMinimized = this.StartMinimized, + ShowTrayIcon = this.ShowTrayIcon, + EnableQuickApplyFromTray = this.EnableQuickApplyFromTray, + EnableMonitoringControlFromTray = this.EnableMonitoringControlFromTray, + NotificationDisplayDurationMs = this.NotificationDisplayDurationMs, + BalloonNotificationTimeoutMs = this.BalloonNotificationTimeoutMs, + NotificationPosition = this.NotificationPosition, + NotificationSound = this.NotificationSound, + EnableNotificationSound = this.EnableNotificationSound, + TrayIconStyle = this.TrayIconStyle, + AutostartWithWindows = this.AutostartWithWindows, + DefaultPowerPlanId = this.DefaultPowerPlanId, + DefaultPowerPlanName = this.DefaultPowerPlanName, + RestoreDefaultPowerPlanOnExit = this.RestoreDefaultPowerPlanOnExit, + PollingIntervalMs = this.PollingIntervalMs, + FallbackPollingIntervalMs = this.FallbackPollingIntervalMs, + EnableWmiMonitoring = this.EnableWmiMonitoring, + EnableFallbackPolling = this.EnableFallbackPolling, + EnableGameBoostMode = this.EnableGameBoostMode, + GameBoostPowerPlanId = this.GameBoostPowerPlanId, + GameBoostPowerPlanName = this.GameBoostPowerPlanName, + GameBoostAutoDetectGames = this.GameBoostAutoDetectGames, + GameBoostSetHighPriority = this.GameBoostSetHighPriority, + GameBoostOptimizeCpuAffinity = this.GameBoostOptimizeCpuAffinity, + GameBoostDetectionDelayMs = this.GameBoostDetectionDelayMs, + EnableDebugLogging = this.EnableDebugLogging, + EnablePerformanceCounters = this.EnablePerformanceCounters, + MaxLogFileSizeMb = this.MaxLogFileSizeMb, + LogRetentionDays = this.LogRetentionDays, + CreatedAt = this.CreatedAt, + UpdatedAt = DateTime.UtcNow + }; + } + } + + /// + /// Notification position options + /// + public enum NotificationPosition + { + TopLeft, + TopRight, + BottomLeft, + BottomRight, + Center + } + + /// + /// Notification sound options + /// + public enum NotificationSound + { + None, + Default, + Information, + Warning, + Error, + Custom + } + + /// + /// Tray icon style options + /// + public enum TrayIconStyle + { + Default, + Monochrome, + Colored, + Custom + } +} diff --git a/Models/Core/IModel.cs b/Models/Core/IModel.cs new file mode 100644 index 0000000..95247b4 --- /dev/null +++ b/Models/Core/IModel.cs @@ -0,0 +1,98 @@ +using System; +using System.ComponentModel; + +namespace ThreadPilot.Models.Core +{ + /// + /// Base interface for all domain models + /// + public interface IModel : INotifyPropertyChanged + { + /// + /// Unique identifier for the model instance + /// + string Id { get; } + + /// + /// Timestamp when the model was created + /// + DateTime CreatedAt { get; } + + /// + /// Timestamp when the model was last updated + /// + DateTime UpdatedAt { get; } + + /// + /// Validate the model state + /// + ValidationResult Validate(); + + /// + /// Create a copy of the model + /// + IModel Clone(); + } + + /// + /// Validation result for model validation + /// + public class ValidationResult + { + public bool IsValid { get; } + public string[] Errors { get; } + + public ValidationResult(bool isValid, params string[] errors) + { + IsValid = isValid; + Errors = errors ?? Array.Empty(); + } + + public static ValidationResult Success() => new(true); + public static ValidationResult Failure(params string[] errors) => new(false, errors); + } + + /// + /// Base implementation for domain models + /// + public abstract class BaseModel : IModel + { + public string Id { get; protected set; } + public DateTime CreatedAt { get; protected set; } + public DateTime UpdatedAt { get; protected set; } + + public event PropertyChangedEventHandler? PropertyChanged; + + protected BaseModel() + { + Id = Guid.NewGuid().ToString(); + CreatedAt = DateTime.UtcNow; + UpdatedAt = DateTime.UtcNow; + } + + protected BaseModel(string id) + { + Id = id ?? throw new ArgumentNullException(nameof(id)); + CreatedAt = DateTime.UtcNow; + UpdatedAt = DateTime.UtcNow; + } + + protected virtual void OnPropertyChanged(string propertyName) + { + UpdatedAt = DateTime.UtcNow; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + protected bool SetProperty(ref T field, T value, string propertyName) + { + if (Equals(field, value)) return false; + + field = value; + OnPropertyChanged(propertyName); + return true; + } + + public abstract ValidationResult Validate(); + public abstract IModel Clone(); + } +} diff --git a/Models/CpuTopologyModel.cs b/Models/CpuTopologyModel.cs new file mode 100644 index 0000000..7d6b27f --- /dev/null +++ b/Models/CpuTopologyModel.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ThreadPilot.Models +{ + /// + /// Represents a logical CPU core with topology information + /// + public class CpuCoreModel + { + public int LogicalCoreId { get; set; } + public int PhysicalCoreId { get; set; } + public int SocketId { get; set; } + public int? CcdId { get; set; } // Core Complex Die (AMD) + public int? ClusterId { get; set; } // Intel Cluster + public CpuCoreType CoreType { get; set; } = CpuCoreType.Unknown; + public bool IsHyperThreaded { get; set; } + public int? HyperThreadSibling { get; set; } + public string Label { get; set; } = string.Empty; + public bool IsEnabled { get; set; } = true; + public bool IsSelected { get; set; } = false; + + /// + /// Gets the affinity mask bit for this logical core + /// + public long AffinityMask => 1L << LogicalCoreId; + } + + /// + /// Types of CPU cores + /// + public enum CpuCoreType + { + Unknown, + Standard, + PerformanceCore, // Intel P-cores + EfficiencyCore, // Intel E-cores + Zen, // AMD Zen cores + ZenPlus, // AMD Zen+ cores + Zen2, // AMD Zen2 cores + Zen3, // AMD Zen3 cores + Zen4 // AMD Zen4 cores + } + + /// + /// Represents CPU topology information + /// + public class CpuTopologyModel + { + public List LogicalCores { get; set; } = new(); + public int TotalLogicalCores => LogicalCores.Count; + public int TotalPhysicalCores => LogicalCores.GroupBy(c => c.PhysicalCoreId).Count(); + public int TotalSockets => LogicalCores.GroupBy(c => c.SocketId).Count(); + public int SocketCount => TotalSockets; // Alias for TotalSockets + public bool HasHyperThreading => LogicalCores.Any(c => c.IsHyperThreaded); + public bool HasSmt => HasHyperThreading; // SMT is AMD's term for HyperThreading + public bool HasIntelHybrid => LogicalCores.Any(c => c.CoreType == CpuCoreType.PerformanceCore || c.CoreType == CpuCoreType.EfficiencyCore); + public bool HasHybridArchitecture => HasIntelHybrid; // Alias for HasIntelHybrid + public bool HasAmdCcd => LogicalCores.Any(c => c.CcdId.HasValue); + public int CcdCount => LogicalCores.Where(c => c.CcdId.HasValue).Select(c => c.CcdId!.Value).Distinct().Count(); + public string Architecture => CpuArchitecture; // Alias for CpuArchitecture + public string CpuArchitecture { get; set; } = "Unknown"; + public string CpuBrand { get; set; } = "Unknown"; + public bool TopologyDetectionSuccessful { get; set; } = false; + + /// + /// Gets all CCDs (Core Complex Dies) available + /// + public IEnumerable AvailableCcds => LogicalCores + .Where(c => c.CcdId.HasValue) + .Select(c => c.CcdId!.Value) + .Distinct() + .OrderBy(id => id); + + /// + /// Gets all performance cores (Intel P-cores) + /// + public IEnumerable PerformanceCores => LogicalCores + .Where(c => c.CoreType == CpuCoreType.PerformanceCore); + + /// + /// Gets all efficiency cores (Intel E-cores) + /// + public IEnumerable EfficiencyCores => LogicalCores + .Where(c => c.CoreType == CpuCoreType.EfficiencyCore); + + /// + /// Gets all physical cores (one logical core per physical core, excluding HT siblings) + /// + public IEnumerable PhysicalCores => LogicalCores + .GroupBy(c => c.PhysicalCoreId) + .Select(g => g.OrderBy(c => c.LogicalCoreId).First()); + + /// + /// Gets cores by CCD ID + /// + public IEnumerable GetCoresByCcd(int ccdId) => LogicalCores + .Where(c => c.CcdId == ccdId); + + /// + /// Gets cores by socket ID + /// + public IEnumerable GetCoresBySocket(int socketId) => LogicalCores + .Where(c => c.SocketId == socketId); + + /// + /// Calculates affinity mask for selected cores + /// + public long CalculateAffinityMask(IEnumerable cores) + { + return cores.Aggregate(0L, (mask, core) => mask | core.AffinityMask); + } + + /// + /// Gets affinity mask for all physical cores (excluding HT siblings) + /// + public long GetPhysicalCoresAffinityMask() => CalculateAffinityMask(PhysicalCores); + + /// + /// Gets affinity mask for performance cores + /// + public long GetPerformanceCoresAffinityMask() => CalculateAffinityMask(PerformanceCores); + + /// + /// Gets affinity mask for efficiency cores + /// + public long GetEfficiencyCoresAffinityMask() => CalculateAffinityMask(EfficiencyCores); + + /// + /// Gets affinity mask for a specific CCD + /// + public long GetCcdAffinityMask(int ccdId) => CalculateAffinityMask(GetCoresByCcd(ccdId)); + } + + /// + /// Quick selection preset for CPU affinity + /// + public class CpuAffinityPreset + { + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public long AffinityMask { get; set; } + public bool IsAvailable { get; set; } = true; + public string UnavailableReason { get; set; } = string.Empty; + } +} diff --git a/Models/LogEventTypes.cs b/Models/LogEventTypes.cs new file mode 100644 index 0000000..1939c01 --- /dev/null +++ b/Models/LogEventTypes.cs @@ -0,0 +1,230 @@ +namespace ThreadPilot.Models +{ + /// + /// Defines structured log event types and categories for consistent logging + /// + public static class LogEventTypes + { + /// + /// Power plan related events + /// + public static class PowerPlan + { + public const string Changed = "PowerPlanChanged"; + public const string ChangeRequested = "PowerPlanChangeRequested"; + public const string ChangeFailed = "PowerPlanChangeFailed"; + public const string Restored = "PowerPlanRestored"; + public const string DefaultSet = "DefaultPowerPlanSet"; + public const string EnumerationFailed = "PowerPlanEnumerationFailed"; + } + + /// + /// Process monitoring events + /// + public static class ProcessMonitoring + { + public const string Started = "ProcessStarted"; + public const string Stopped = "ProcessStopped"; + public const string MonitoringStarted = "MonitoringStarted"; + public const string MonitoringStopped = "MonitoringStopped"; + public const string WmiEventReceived = "WmiEventReceived"; + public const string WmiConnectionFailed = "WmiConnectionFailed"; + public const string PollingFallback = "PollingFallbackActivated"; + public const string ProcessDetected = "ProcessDetected"; + public const string ProcessLost = "ProcessLost"; + public const string AssociationTriggered = "AssociationTriggered"; + } + + /// + /// Game boost related events + /// + public static class GameBoost + { + public const string Activated = "GameBoostActivated"; + public const string Deactivated = "GameBoostDeactivated"; + public const string GameDetected = "GameDetected"; + public const string GameAdded = "GameAdded"; + public const string GameRemoved = "GameRemoved"; + public const string PrioritySet = "ProcessPrioritySet"; + public const string PriorityFailed = "ProcessPriorityFailed"; + public const string AffinitySet = "CpuAffinitySet"; + public const string AffinityFailed = "CpuAffinityFailed"; + public const string ConfigurationChanged = "GameBoostConfigurationChanged"; + } + + /// + /// User action events + /// + public static class UserActions + { + public const string SettingsChanged = "SettingsChanged"; + public const string ProcessAffinityChanged = "ProcessAffinityChanged"; + public const string ProcessPriorityChanged = "ProcessPriorityChanged"; + public const string AssociationAdded = "AssociationAdded"; + public const string AssociationRemoved = "AssociationRemoved"; + public const string MonitoringToggled = "MonitoringToggled"; + public const string GameBoostToggled = "GameBoostToggled"; + public const string AutostartToggled = "AutostartToggled"; + public const string NotificationSettingsChanged = "NotificationSettingsChanged"; + public const string LogsExported = "LogsExported"; + public const string LogsCleared = "LogsCleared"; + } + + /// + /// System events + /// + public static class System + { + public const string ApplicationStarted = "ApplicationStarted"; + public const string ApplicationShutdown = "ApplicationShutdown"; + public const string ServiceInitialized = "ServiceInitialized"; + public const string ServiceStarted = "ServiceStarted"; + public const string ServiceStopped = "ServiceStopped"; + public const string ConfigurationLoaded = "ConfigurationLoaded"; + public const string ConfigurationSaved = "ConfigurationSaved"; + public const string CpuTopologyDetected = "CpuTopologyDetected"; + public const string SystemTrayInitialized = "SystemTrayInitialized"; + public const string NotificationSent = "NotificationSent"; + public const string ErrorRecovered = "ErrorRecovered"; + } + + /// + /// Error categories + /// + public static class Errors + { + public const string ServiceFailure = "ServiceFailure"; + public const string ConfigurationError = "ConfigurationError"; + public const string FileSystemError = "FileSystemError"; + public const string PermissionError = "PermissionError"; + public const string NetworkError = "NetworkError"; + public const string WmiError = "WmiError"; + public const string UnhandledException = "UnhandledException"; + public const string ValidationError = "ValidationError"; + } + + /// + /// Performance events + /// + public static class Performance + { + public const string HighMemoryUsage = "HighMemoryUsage"; + public const string HighCpuUsage = "HighCpuUsage"; + public const string SlowOperation = "SlowOperation"; + public const string LargeLogFile = "LargeLogFile"; + public const string ProcessCountHigh = "ProcessCountHigh"; + } + } + + /// + /// Log categories for organizing log entries + /// + public static class LogCategories + { + public const string PowerPlan = "PowerPlan"; + public const string ProcessMonitoring = "ProcessMonitoring"; + public const string GameBoost = "GameBoost"; + public const string UserAction = "UserAction"; + public const string System = "System"; + public const string Error = "Error"; + public const string Performance = "Performance"; + public const string Security = "Security"; + public const string Configuration = "Configuration"; + public const string Lifecycle = "Lifecycle"; + } + + /// + /// Common log properties for structured logging + /// + public static class LogProperties + { + public const string ProcessName = "ProcessName"; + public const string ProcessId = "ProcessId"; + public const string PowerPlanId = "PowerPlanId"; + public const string PowerPlanName = "PowerPlanName"; + public const string GameName = "GameName"; + public const string UserId = "UserId"; + public const string SessionId = "SessionId"; + public const string CorrelationId = "CorrelationId"; + public const string Duration = "Duration"; + public const string ErrorCode = "ErrorCode"; + public const string StackTrace = "StackTrace"; + public const string MemoryUsage = "MemoryUsage"; + public const string CpuUsage = "CpuUsage"; + public const string ThreadId = "ThreadId"; + public const string Version = "Version"; + public const string Environment = "Environment"; + } + + /// + /// Helper class for creating structured log data + /// + public static class LogDataBuilder + { + public static Dictionary CreateProcessData(string processName, int processId) + { + return new Dictionary + { + [LogProperties.ProcessName] = processName, + [LogProperties.ProcessId] = processId + }; + } + + public static Dictionary CreatePowerPlanData(string planId, string planName) + { + return new Dictionary + { + [LogProperties.PowerPlanId] = planId, + [LogProperties.PowerPlanName] = planName + }; + } + + public static Dictionary CreateGameData(string gameName) + { + return new Dictionary + { + [LogProperties.GameName] = gameName + }; + } + + public static Dictionary CreatePerformanceData(long memoryUsage, double cpuUsage) + { + return new Dictionary + { + [LogProperties.MemoryUsage] = memoryUsage, + [LogProperties.CpuUsage] = cpuUsage + }; + } + + public static Dictionary CreateErrorData(Exception exception) + { + return new Dictionary + { + [LogProperties.ErrorCode] = exception.HResult, + [LogProperties.StackTrace] = exception.StackTrace ?? "N/A", + ["ExceptionType"] = exception.GetType().Name, + ["InnerException"] = exception.InnerException?.Message ?? "N/A" + }; + } + + public static Dictionary CreateTimingData(TimeSpan duration) + { + return new Dictionary + { + [LogProperties.Duration] = duration.TotalMilliseconds + }; + } + + public static Dictionary CreateSystemData() + { + return new Dictionary + { + [LogProperties.Version] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown", + [LogProperties.Environment] = Environment.OSVersion.ToString(), + [LogProperties.ThreadId] = Thread.CurrentThread.ManagedThreadId, + ["MachineName"] = Environment.MachineName, + ["UserName"] = Environment.UserName + }; + } + } +} diff --git a/Models/NotificationModel.cs b/Models/NotificationModel.cs new file mode 100644 index 0000000..2cf8a4a --- /dev/null +++ b/Models/NotificationModel.cs @@ -0,0 +1,140 @@ +using System; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace ThreadPilot.Models +{ + /// + /// Model representing a notification + /// + public partial class NotificationModel : ObservableObject + { + [ObservableProperty] + private string id = Guid.NewGuid().ToString(); + + [ObservableProperty] + private string title = string.Empty; + + [ObservableProperty] + private string message = string.Empty; + + [ObservableProperty] + private NotificationType type = NotificationType.Information; + + [ObservableProperty] + private DateTime timestamp = DateTime.Now; + + [ObservableProperty] + private int durationMs = 3000; + + [ObservableProperty] + private bool isRead = false; + + [ObservableProperty] + private bool isPersistent = false; + + [ObservableProperty] + private string? actionText; + + [ObservableProperty] + private string? actionCommand; + + [ObservableProperty] + private string? iconPath; + + [ObservableProperty] + private NotificationPriority priority = NotificationPriority.Normal; + + [ObservableProperty] + private string? category; + + [ObservableProperty] + private string? sourceService; + + /// + /// Creates a new notification + /// + public NotificationModel() + { + } + + /// + /// Creates a new notification with basic information + /// + public NotificationModel(string title, string message, NotificationType type = NotificationType.Information) + { + Title = title; + Message = message; + Type = type; + } + + /// + /// Creates a new notification with full information + /// + public NotificationModel(string title, string message, NotificationType type, int durationMs, bool isPersistent = false) + { + Title = title; + Message = message; + Type = type; + DurationMs = durationMs; + IsPersistent = isPersistent; + } + + /// + /// Marks the notification as read + /// + public void MarkAsRead() + { + IsRead = true; + } + + /// + /// Gets the display text for the notification type + /// + public string TypeDisplayText => Type switch + { + NotificationType.Information => "Info", + NotificationType.Success => "Success", + NotificationType.Warning => "Warning", + NotificationType.Error => "Error", + NotificationType.PowerPlanChange => "Power Plan", + NotificationType.ProcessMonitoring => "Process Monitor", + NotificationType.CpuAffinity => "CPU Affinity", + _ => "Unknown" + }; + + /// + /// Gets the formatted timestamp + /// + public string FormattedTimestamp => Timestamp.ToString("HH:mm:ss"); + + /// + /// Gets the formatted date and time + /// + public string FormattedDateTime => Timestamp.ToString("yyyy-MM-dd HH:mm:ss"); + } + + /// + /// Types of notifications + /// + public enum NotificationType + { + Information, + Success, + Warning, + Error, + PowerPlanChange, + ProcessMonitoring, + CpuAffinity + } + + /// + /// Notification priority levels + /// + public enum NotificationPriority + { + Low, + Normal, + High, + Critical + } +} diff --git a/Models/ProcessModel.cs b/Models/ProcessModel.cs index f7c06f8..7f44412 100644 --- a/Models/ProcessModel.cs +++ b/Models/ProcessModel.cs @@ -22,6 +22,7 @@ namespace ThreadPilot.Models ProcessorAffinity = (long)value.ProcessorAffinity; Priority = value.PriorityClass; MemoryUsage = value.WorkingSet64; + ExecutablePath = value.MainModule?.FileName ?? string.Empty; } catch (Exception) { @@ -37,6 +38,9 @@ namespace ThreadPilot.Models [ObservableProperty] private string name = string.Empty; + [ObservableProperty] + private string executablePath = string.Empty; + [ObservableProperty] private double cpuUsage; diff --git a/Models/ProcessMonitorConfiguration.cs b/Models/ProcessMonitorConfiguration.cs new file mode 100644 index 0000000..6f1ec93 --- /dev/null +++ b/Models/ProcessMonitorConfiguration.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace ThreadPilot.Models +{ + /// + /// Configuration model for process monitoring and power plan associations + /// + public partial class ProcessMonitorConfiguration : ObservableObject + { + [ObservableProperty] + private string defaultPowerPlanGuid = string.Empty; + + [ObservableProperty] + private string defaultPowerPlanName = string.Empty; + + [ObservableProperty] + private bool isEventBasedMonitoringEnabled = true; + + [ObservableProperty] + private bool isFallbackPollingEnabled = true; + + [ObservableProperty] + private int pollingIntervalSeconds = 5; + + [ObservableProperty] + private bool preventDuplicatePowerPlanChanges = true; + + [ObservableProperty] + private int powerPlanChangeDelayMs = 1000; + + [ObservableProperty] + private bool enableLogging = true; + + [ObservableProperty] + private List associations = new(); + + [ObservableProperty] + private DateTime lastSavedDate = DateTime.Now; + + [ObservableProperty] + private string configurationVersion = "1.0"; + + public ProcessMonitorConfiguration() + { + Associations = new List(); + } + + /// + /// Gets all enabled associations sorted by priority (descending) + /// + public IEnumerable GetEnabledAssociations() + { + return Associations + .Where(a => a.IsEnabled) + .OrderByDescending(a => a.Priority) + .ThenBy(a => a.ExecutableName); + } + + /// + /// Finds the best matching association for a process + /// + public ProcessPowerPlanAssociation? FindMatchingAssociation(ProcessModel process) + { + return GetEnabledAssociations() + .FirstOrDefault(a => a.MatchesProcess(process)); + } + + /// + /// Finds association by executable name + /// + public ProcessPowerPlanAssociation? FindAssociationByExecutable(string executableName) + { + return Associations + .FirstOrDefault(a => a.MatchesExecutable(executableName)); + } + + /// + /// Adds or updates an association + /// + public void AddOrUpdateAssociation(ProcessPowerPlanAssociation association) + { + var existing = Associations.FirstOrDefault(a => a.Id == association.Id); + if (existing != null) + { + var index = Associations.IndexOf(existing); + Associations[index] = association; + } + else + { + Associations.Add(association); + } + LastSavedDate = DateTime.Now; + } + + /// + /// Removes an association + /// + public bool RemoveAssociation(string associationId) + { + var association = Associations.FirstOrDefault(a => a.Id == associationId); + if (association != null) + { + Associations.Remove(association); + LastSavedDate = DateTime.Now; + return true; + } + return false; + } + + /// + /// Validates the configuration + /// + public List Validate() + { + var errors = new List(); + + if (PollingIntervalSeconds < 1) + errors.Add("Polling interval must be at least 1 second"); + + if (PowerPlanChangeDelayMs < 0) + errors.Add("Power plan change delay cannot be negative"); + + // Check for duplicate associations + var duplicates = Associations + .GroupBy(a => new { a.ExecutableName, a.MatchByPath }) + .Where(g => g.Count() > 1) + .Select(g => g.Key.ExecutableName); + + foreach (var duplicate in duplicates) + { + errors.Add($"Duplicate association found for executable: {duplicate}"); + } + + return errors; + } + } +} diff --git a/Models/ProcessPowerPlanAssociation.cs b/Models/ProcessPowerPlanAssociation.cs new file mode 100644 index 0000000..757b9f9 --- /dev/null +++ b/Models/ProcessPowerPlanAssociation.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using ThreadPilot.Models.Core; + +namespace ThreadPilot.Models +{ + /// + /// Represents an association between an executable and a power plan + /// + public partial class ProcessPowerPlanAssociation : ObservableObject, IModel + { + [ObservableProperty] + private string id = Guid.NewGuid().ToString(); + + [ObservableProperty] + private string executableName = string.Empty; + + [ObservableProperty] + private string executablePath = string.Empty; + + [ObservableProperty] + private string powerPlanGuid = string.Empty; + + [ObservableProperty] + private string powerPlanName = string.Empty; + + [ObservableProperty] + private bool isEnabled = true; + + [ObservableProperty] + private DateTime createdAt = DateTime.UtcNow; + + [ObservableProperty] + private DateTime updatedAt = DateTime.UtcNow; + + // IModel implementation - properties are auto-generated by ObservableProperty + + [ObservableProperty] + private string description = string.Empty; + + /// + /// Whether to match by exact executable name or path + /// + [ObservableProperty] + private bool matchByPath = false; + + /// + /// Priority for this association (higher number = higher priority) + /// Used when multiple associations could match the same process + /// + [ObservableProperty] + private int priority = 0; + + public ProcessPowerPlanAssociation() + { + } + + public ProcessPowerPlanAssociation(string executableName, string powerPlanGuid, string powerPlanName) + { + ExecutableName = executableName; + PowerPlanGuid = powerPlanGuid; + PowerPlanName = powerPlanName; + } + + /// + /// Checks if this association matches the given process + /// + public bool MatchesProcess(ProcessModel process) + { + if (!IsEnabled) return false; + + if (MatchByPath && !string.IsNullOrEmpty(ExecutablePath)) + { + return string.Equals(process.ExecutablePath, ExecutablePath, StringComparison.OrdinalIgnoreCase); + } + else + { + return string.Equals(process.Name, ExecutableName, StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// Checks if this association matches the given executable name + /// + public bool MatchesExecutable(string executableName) + { + if (!IsEnabled) return false; + return string.Equals(ExecutableName, executableName, StringComparison.OrdinalIgnoreCase); + } + + + + public ValidationResult Validate() + { + var errors = new List(); + + if (string.IsNullOrWhiteSpace(ExecutableName)) + errors.Add("Executable name is required"); + + if (string.IsNullOrWhiteSpace(PowerPlanGuid)) + errors.Add("Power plan GUID is required"); + + if (string.IsNullOrWhiteSpace(PowerPlanName)) + errors.Add("Power plan name is required"); + + return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); + } + + public IModel Clone() + { + return new ProcessPowerPlanAssociation + { + id = Guid.NewGuid().ToString(), // New ID for clone + ExecutableName = this.ExecutableName, + ExecutablePath = this.ExecutablePath, + PowerPlanGuid = this.PowerPlanGuid, + PowerPlanName = this.PowerPlanName, + IsEnabled = this.IsEnabled, + Description = this.Description, + MatchByPath = this.MatchByPath, + createdAt = DateTime.UtcNow, + updatedAt = DateTime.UtcNow + }; + } + } +} diff --git a/Models/ProfileModel.cs b/Models/ProfileModel.cs index 0392b4b..9fc00a8 100644 --- a/Models/ProfileModel.cs +++ b/Models/ProfileModel.cs @@ -1,11 +1,75 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; +using CommunityToolkit.Mvvm.ComponentModel; +using ThreadPilot.Models.Core; namespace ThreadPilot.Models { - public class ProfileModel + public partial class ProfileModel : ObservableObject, IModel { - public string ProcessName { get; set; } = string.Empty; - public ProcessPriorityClass Priority { get; set; } - public long ProcessorAffinity { get; set; } + [ObservableProperty] + private string id = Guid.NewGuid().ToString(); + + [ObservableProperty] + private DateTime createdAt = DateTime.UtcNow; + + [ObservableProperty] + private DateTime updatedAt = DateTime.UtcNow; + + [ObservableProperty] + private string name = string.Empty; + + [ObservableProperty] + private string processName = string.Empty; + + [ObservableProperty] + private ProcessPriorityClass priority = ProcessPriorityClass.Normal; + + [ObservableProperty] + private long processorAffinity = -1; // All cores + + [ObservableProperty] + private string description = string.Empty; + + [ObservableProperty] + private bool isEnabled = true; + + // IModel implementation - properties are auto-generated by ObservableProperty + + public ValidationResult Validate() + { + var errors = new List(); + + if (string.IsNullOrWhiteSpace(Name)) + errors.Add("Profile name is required"); + + if (string.IsNullOrWhiteSpace(ProcessName)) + errors.Add("Process name is required"); + + return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); + } + + public IModel Clone() + { + return new ProfileModel + { + id = Guid.NewGuid().ToString(), // New ID for clone + Name = this.Name, + ProcessName = this.ProcessName, + Priority = this.Priority, + ProcessorAffinity = this.ProcessorAffinity, + Description = this.Description, + IsEnabled = this.IsEnabled, + createdAt = DateTime.UtcNow, + updatedAt = DateTime.UtcNow + }; + } + + partial void OnUpdatedAtChanged(DateTime value) + { + updatedAt = DateTime.UtcNow; + } } } \ No newline at end of file diff --git a/PROJECT_STRUCTURE.md b/PROJECT_STRUCTURE.md new file mode 100644 index 0000000..710bae0 --- /dev/null +++ b/PROJECT_STRUCTURE.md @@ -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. diff --git a/README.md b/README.md index 44c55e3..8982068 100644 --- a/README.md +++ b/README.md @@ -6,17 +6,27 @@ ThreadPilot is a Windows process and power plan management tool that gives you f - 💻 Process Management - View all running processes with real-time updates - - Set CPU affinity for individual processes + - **Advanced CPU affinity with topology detection** + - **Quick selection for P-cores, E-cores, CCDs, and physical cores** + - **Dynamic UI adapting to detected CPU architecture** - Adjust process priority levels - Search and filter processes - Save/load process configurations as profiles -- ⚡ Power Plan Management +- ⚡ Power Plan Management - View and switch between Windows power plans + - **Combined CPU affinity and power plan application** - Import custom power plan configurations - Monitor active power plan - Import custom power plan files (.pow) +- 🔧 Advanced CPU Features + - **Intel Hybrid (P-core/E-core) detection and selection** + - **AMD CCD (Core Complex Die) awareness** + - **SMT/HyperThreading detection** + - **Multi-socket system support** + - **System tray integration with quick apply** + ## Requirements 🔧 - Windows 7 or later diff --git a/Services/ApplicationSettingsService.cs b/Services/ApplicationSettingsService.cs new file mode 100644 index 0000000..2060673 --- /dev/null +++ b/Services/ApplicationSettingsService.cs @@ -0,0 +1,245 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing application settings with JSON persistence + /// + public class ApplicationSettingsService : IApplicationSettingsService + { + private readonly ILogger _logger; + private readonly string _settingsFilePath; + private ApplicationSettingsModel _settings; + + public event EventHandler? SettingsChanged; + + public ApplicationSettingsModel Settings => _settings; + + public ApplicationSettingsService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + // Set settings file path in user's AppData folder + var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + var appFolder = Path.Combine(appDataPath, "ThreadPilot"); + Directory.CreateDirectory(appFolder); + _settingsFilePath = Path.Combine(appFolder, "settings.json"); + + _settings = new ApplicationSettingsModel(); + } + + public async Task LoadSettingsAsync() + { + try + { + _logger.LogInformation("Loading application settings from {FilePath}", _settingsFilePath); + + if (!File.Exists(_settingsFilePath)) + { + _logger.LogInformation("Settings file not found, using defaults"); + _settings = new ApplicationSettingsModel(); + await SaveSettingsAsync(); + return; + } + + var json = await File.ReadAllTextAsync(_settingsFilePath); + var loadedSettings = JsonSerializer.Deserialize(json); + + if (loadedSettings != null) + { + var oldSettings = (ApplicationSettingsModel)_settings.Clone(); + _settings.CopyFrom(loadedSettings); + ValidateAndFixSettings(); + + _logger.LogInformation("Settings loaded successfully"); + OnSettingsChanged(oldSettings, _settings); + } + else + { + _logger.LogWarning("Failed to deserialize settings, using defaults"); + _settings = new ApplicationSettingsModel(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error loading settings, using defaults"); + _settings = new ApplicationSettingsModel(); + } + } + + public async Task SaveSettingsAsync() + { + try + { + _logger.LogDebug("Saving application settings to {FilePath}", _settingsFilePath); + + ValidateAndFixSettings(); + + var options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + var json = JsonSerializer.Serialize(_settings, options); + await File.WriteAllTextAsync(_settingsFilePath, json); + + _logger.LogDebug("Settings saved successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error saving settings"); + throw; + } + } + + public async Task UpdateSettingsAsync(ApplicationSettingsModel newSettings) + { + if (newSettings == null) + throw new ArgumentNullException(nameof(newSettings)); + + try + { + var oldSettings = (ApplicationSettingsModel)_settings.Clone(); + _settings.CopyFrom(newSettings); + + await SaveSettingsAsync(); + + OnSettingsChanged(oldSettings, _settings); + _logger.LogInformation("Settings updated successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error updating settings"); + throw; + } + } + + public async Task ResetToDefaultsAsync() + { + try + { + _logger.LogInformation("Resetting settings to defaults"); + + var oldSettings = (ApplicationSettingsModel)_settings.Clone(); + _settings = new ApplicationSettingsModel(); + + await SaveSettingsAsync(); + + OnSettingsChanged(oldSettings, _settings); + _logger.LogInformation("Settings reset to defaults"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error resetting settings to defaults"); + throw; + } + } + + public string GetSettingsFilePath() + { + return _settingsFilePath; + } + + public void ValidateAndFixSettings() + { + // Validate and fix notification durations + if (_settings.NotificationDisplayDurationMs < 1000) + _settings.NotificationDisplayDurationMs = 1000; + if (_settings.NotificationDisplayDurationMs > 30000) + _settings.NotificationDisplayDurationMs = 30000; + + if (_settings.BalloonNotificationTimeoutMs < 1000) + _settings.BalloonNotificationTimeoutMs = 1000; + if (_settings.BalloonNotificationTimeoutMs > 60000) + _settings.BalloonNotificationTimeoutMs = 60000; + + // Validate notification history + if (_settings.MaxNotificationHistoryItems < 10) + _settings.MaxNotificationHistoryItems = 10; + if (_settings.MaxNotificationHistoryItems > 1000) + _settings.MaxNotificationHistoryItems = 1000; + + // Validate custom icon path + if (_settings.UseCustomTrayIcon && !string.IsNullOrEmpty(_settings.CustomTrayIconPath)) + { + if (!File.Exists(_settings.CustomTrayIconPath)) + { + _logger.LogWarning("Custom tray icon file not found: {Path}", _settings.CustomTrayIconPath); + _settings.UseCustomTrayIcon = false; + } + } + } + + public async Task ExportSettingsAsync(string filePath) + { + try + { + _logger.LogInformation("Exporting settings to {FilePath}", filePath); + + var options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + var json = JsonSerializer.Serialize(_settings, options); + await File.WriteAllTextAsync(filePath, json); + + _logger.LogInformation("Settings exported successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error exporting settings"); + throw; + } + } + + public async Task ImportSettingsAsync(string filePath) + { + try + { + _logger.LogInformation("Importing settings from {FilePath}", filePath); + + if (!File.Exists(filePath)) + throw new FileNotFoundException($"Settings file not found: {filePath}"); + + var json = await File.ReadAllTextAsync(filePath); + var importedSettings = JsonSerializer.Deserialize(json); + + if (importedSettings == null) + throw new InvalidOperationException("Failed to deserialize imported settings"); + + await UpdateSettingsAsync(importedSettings); + _logger.LogInformation("Settings imported successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error importing settings"); + throw; + } + } + + private void OnSettingsChanged(ApplicationSettingsModel oldSettings, ApplicationSettingsModel newSettings) + { + try + { + // For simplicity, we'll just indicate that settings changed + // In a more sophisticated implementation, we could track specific property changes + var changedProperties = new[] { "Settings" }; + + SettingsChanged?.Invoke(this, new ApplicationSettingsChangedEventArgs( + oldSettings, newSettings, changedProperties)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error firing settings changed event"); + } + } + } +} diff --git a/Services/AutostartService.cs b/Services/AutostartService.cs new file mode 100644 index 0000000..4a9fe9d --- /dev/null +++ b/Services/AutostartService.cs @@ -0,0 +1,202 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Win32; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing Windows autostart functionality using registry + /// + public class AutostartService : IAutostartService + { + private const string REGISTRY_KEY_PATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; + private const string APPLICATION_NAME = "ThreadPilot"; + + private readonly ILogger _logger; + private bool _isAutostartEnabled; + private string? _autostartPath; + + public event EventHandler? AutostartStatusChanged; + + public bool IsAutostartEnabled => _isAutostartEnabled; + public string? AutostartPath => _autostartPath; + + public AutostartService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + // Initialize current status + _ = Task.Run(CheckAutostartStatusAsync); + } + + public async Task EnableAutostartAsync(bool startMinimized = true) + { + try + { + var executablePath = GetExecutablePath(); + if (string.IsNullOrEmpty(executablePath)) + { + _logger.LogError("Could not determine executable path for autostart"); + return false; + } + + var arguments = GetAutostartArguments(startMinimized); + var fullCommand = $"\"{executablePath}\" {arguments}"; + + using var key = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY_PATH, true); + if (key == null) + { + _logger.LogError("Could not open registry key for autostart"); + return false; + } + + key.SetValue(APPLICATION_NAME, fullCommand, RegistryValueKind.String); + + _isAutostartEnabled = true; + _autostartPath = fullCommand; + + _logger.LogInformation("Autostart enabled: {Command}", fullCommand); + + AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs( + true, startMinimized, fullCommand)); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to enable autostart"); + + AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs( + false, startMinimized, null, ex)); + + return false; + } + } + + public async Task DisableAutostartAsync() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY_PATH, true); + if (key == null) + { + _logger.LogWarning("Could not open registry key for autostart removal"); + return false; + } + + if (key.GetValue(APPLICATION_NAME) != null) + { + key.DeleteValue(APPLICATION_NAME, false); + _logger.LogInformation("Autostart disabled"); + } + + _isAutostartEnabled = false; + _autostartPath = null; + + AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(false)); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to disable autostart"); + + AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs( + false, false, null, ex)); + + return false; + } + } + + public async Task CheckAutostartStatusAsync() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY_PATH, false); + if (key == null) + { + _isAutostartEnabled = false; + _autostartPath = null; + return false; + } + + var value = key.GetValue(APPLICATION_NAME) as string; + _isAutostartEnabled = !string.IsNullOrEmpty(value); + _autostartPath = value; + + _logger.LogDebug("Autostart status checked: {IsEnabled}, Path: {Path}", + _isAutostartEnabled, _autostartPath); + + return _isAutostartEnabled; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to check autostart status"); + _isAutostartEnabled = false; + _autostartPath = null; + return false; + } + } + + public async Task UpdateAutostartAsync(bool startMinimized = true) + { + if (!_isAutostartEnabled) + { + return await EnableAutostartAsync(startMinimized); + } + + // Re-enable with new parameters + await DisableAutostartAsync(); + return await EnableAutostartAsync(startMinimized); + } + + public string GetAutostartArguments(bool startMinimized = true) + { + var args = new System.Collections.Generic.List(); + + if (startMinimized) + { + args.Add("--start-minimized"); + } + + // Add any other startup arguments as needed + args.Add("--autostart"); + + return string.Join(" ", args); + } + + private string? GetExecutablePath() + { + try + { + var assembly = System.Reflection.Assembly.GetExecutingAssembly(); + var location = assembly.Location; + + // Handle .NET Core/5+ scenarios where Location might be empty + if (string.IsNullOrEmpty(location)) + { + location = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName; + } + + // If we're running from a .dll, try to find the .exe + if (!string.IsNullOrEmpty(location) && location.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + { + var exePath = Path.ChangeExtension(location, ".exe"); + if (File.Exists(exePath)) + { + location = exePath; + } + } + + return location; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to get executable path"); + return null; + } + } + } +} diff --git a/Services/Core/BaseSystemService.cs b/Services/Core/BaseSystemService.cs new file mode 100644 index 0000000..55a7701 --- /dev/null +++ b/Services/Core/BaseSystemService.cs @@ -0,0 +1,101 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Threading.Tasks; + +namespace ThreadPilot.Services.Core +{ + /// + /// Base implementation for system services with common functionality + /// + public abstract class BaseSystemService : ISystemService, IDisposable + { + protected readonly ILogger Logger; + private bool _isAvailable; + private bool _disposed; + + public bool IsAvailable + { + get => _isAvailable; + protected set + { + if (_isAvailable != value) + { + _isAvailable = value; + OnAvailabilityChanged(value); + } + } + } + + public event EventHandler? AvailabilityChanged; + + protected BaseSystemService(ILogger logger) + { + Logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public virtual async Task InitializeAsync() + { + try + { + Logger.LogInformation("Initializing {ServiceType}", GetType().Name); + await InitializeServiceAsync(); + IsAvailable = true; + Logger.LogInformation("{ServiceType} initialized successfully", GetType().Name); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to initialize {ServiceType}", GetType().Name); + IsAvailable = false; + throw; + } + } + + public virtual async Task DisposeAsync() + { + if (_disposed) return; + + try + { + Logger.LogInformation("Disposing {ServiceType}", GetType().Name); + await DisposeServiceAsync(); + IsAvailable = false; + } + catch (Exception ex) + { + Logger.LogError(ex, "Error disposing {ServiceType}", GetType().Name); + } + finally + { + _disposed = true; + } + } + + protected abstract Task InitializeServiceAsync(); + protected abstract Task DisposeServiceAsync(); + + protected virtual void OnAvailabilityChanged(bool isAvailable, string? reason = null) + { + AvailabilityChanged?.Invoke(this, new ServiceAvailabilityChangedEventArgs(isAvailable, reason)); + } + + protected void ThrowIfDisposed() + { + if (_disposed) + throw new ObjectDisposedException(GetType().Name); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposed && disposing) + { + _ = Task.Run(async () => await DisposeAsync()); + } + } + } +} diff --git a/Services/Core/ISystemService.cs b/Services/Core/ISystemService.cs new file mode 100644 index 0000000..7e3176b --- /dev/null +++ b/Services/Core/ISystemService.cs @@ -0,0 +1,45 @@ +using System; + +namespace ThreadPilot.Services.Core +{ + /// + /// Base interface for core system services that interact directly with the operating system + /// + public interface ISystemService + { + /// + /// Gets whether the service is currently available and functional + /// + bool IsAvailable { get; } + + /// + /// Event fired when the service availability changes + /// + event EventHandler? AvailabilityChanged; + + /// + /// Initialize the service + /// + Task InitializeAsync(); + + /// + /// Cleanup and dispose of service resources + /// + Task DisposeAsync(); + } + + /// + /// Event args for service availability changes + /// + public class ServiceAvailabilityChangedEventArgs : EventArgs + { + public bool IsAvailable { get; } + public string? Reason { get; } + + public ServiceAvailabilityChangedEventArgs(bool isAvailable, string? reason = null) + { + IsAvailable = isAvailable; + Reason = reason; + } + } +} diff --git a/Services/CpuTopologyService.cs b/Services/CpuTopologyService.cs new file mode 100644 index 0000000..44e12bd --- /dev/null +++ b/Services/CpuTopologyService.cs @@ -0,0 +1,448 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for detecting CPU topology using WMI and Windows APIs + /// + public class CpuTopologyService : ICpuTopologyService + { + private readonly ILogger _logger; + private CpuTopologyModel? _currentTopology; + + public event EventHandler? TopologyDetected; + public CpuTopologyModel? CurrentTopology => _currentTopology; + + public CpuTopologyService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task DetectTopologyAsync() + { + try + { + _logger.LogInformation("Starting CPU topology detection"); + + var topology = new CpuTopologyModel(); + + // Get basic system information + await DetectBasicCpuInfoAsync(topology); + + // Detect logical cores using multiple methods + await DetectLogicalCoresAsync(topology); + + // Try to detect advanced topology (CCD, P/E cores, etc.) + await DetectAdvancedTopologyAsync(topology); + + // Validate and finalize topology + ValidateTopology(topology); + + _currentTopology = topology; + topology.TopologyDetectionSuccessful = true; + + _logger.LogInformation("CPU topology detection completed successfully. " + + "Logical cores: {LogicalCores}, Physical cores: {PhysicalCores}, " + + "Sockets: {Sockets}, HT: {HasHT}, Hybrid: {HasHybrid}, CCD: {HasCcd}", + topology.TotalLogicalCores, topology.TotalPhysicalCores, topology.TotalSockets, + topology.HasHyperThreading, topology.HasIntelHybrid, topology.HasAmdCcd); + + TopologyDetected?.Invoke(this, new CpuTopologyDetectedEventArgs(topology, true)); + return topology; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to detect CPU topology"); + + // Create fallback topology + var fallbackTopology = CreateFallbackTopology(); + _currentTopology = fallbackTopology; + + TopologyDetected?.Invoke(this, new CpuTopologyDetectedEventArgs(fallbackTopology, false, ex.Message)); + return fallbackTopology; + } + } + + private async Task DetectBasicCpuInfoAsync(CpuTopologyModel topology) + { + try + { + using var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); + using var collection = searcher.Get(); + + foreach (ManagementObject processor in collection) + { + topology.CpuBrand = processor["Name"]?.ToString() ?? "Unknown"; + topology.CpuArchitecture = processor["Architecture"]?.ToString() ?? "Unknown"; + break; // Take first processor for basic info + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to detect basic CPU info via WMI"); + } + } + + private async Task DetectLogicalCoresAsync(CpuTopologyModel topology) + { + try + { + // Method 1: Use Environment.ProcessorCount as baseline + int logicalCoreCount = Environment.ProcessorCount; + + // Method 2: Try WMI for more detailed information + await DetectCoresViaWmiAsync(topology); + + // If WMI failed, create basic topology + if (topology.LogicalCores.Count == 0) + { + CreateBasicTopology(topology, logicalCoreCount); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to detect logical cores, using fallback"); + CreateBasicTopology(topology, Environment.ProcessorCount); + } + } + + private async Task DetectCoresViaWmiAsync(CpuTopologyModel topology) + { + try + { + // First, get physical processor information + var physicalCoreCount = 0; + var logicalCoreCount = 0; + + using (var processorSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor")) + using (var processorCollection = processorSearcher.Get()) + { + foreach (ManagementObject processor in processorCollection) + { + var numberOfCores = Convert.ToInt32(processor["NumberOfCores"] ?? 0); + var numberOfLogicalProcessors = Convert.ToInt32(processor["NumberOfLogicalProcessors"] ?? 0); + + physicalCoreCount += numberOfCores; + logicalCoreCount += numberOfLogicalProcessors; + + _logger.LogInformation("Detected CPU: {Cores} physical cores, {LogicalProcessors} logical processors", + numberOfCores, numberOfLogicalProcessors); + } + } + + // If WMI didn't provide the info, fall back to Environment.ProcessorCount + if (logicalCoreCount == 0) + { + logicalCoreCount = Environment.ProcessorCount; + physicalCoreCount = logicalCoreCount; // Assume no HT if we can't detect + } + + // Create logical cores with proper physical core mapping + var hasHyperThreading = logicalCoreCount > physicalCoreCount; + var threadsPerCore = hasHyperThreading ? logicalCoreCount / physicalCoreCount : 1; + + for (int logicalId = 0; logicalId < logicalCoreCount; logicalId++) + { + var physicalId = logicalId / threadsPerCore; + var isHyperThreaded = hasHyperThreading && (logicalId % threadsPerCore != 0); + var htSibling = hasHyperThreading ? (logicalId % threadsPerCore == 0 ? logicalId + 1 : logicalId - 1) : (int?)null; + + var core = new CpuCoreModel + { + LogicalCoreId = logicalId, + PhysicalCoreId = physicalId, + SocketId = 0, // Will be refined later + Label = $"Core {logicalId}", + IsEnabled = true, + IsHyperThreaded = isHyperThreaded, + HyperThreadSibling = htSibling + }; + + topology.LogicalCores.Add(core); + } + + _logger.LogInformation("Created topology: {LogicalCores} logical cores, {PhysicalCores} physical cores, HT: {HasHT}", + logicalCoreCount, physicalCoreCount, hasHyperThreading); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "WMI logical processor detection failed"); + } + } + + private void CreateBasicTopology(CpuTopologyModel topology, int logicalCoreCount) + { + topology.LogicalCores.Clear(); + + for (int i = 0; i < logicalCoreCount; i++) + { + var core = new CpuCoreModel + { + LogicalCoreId = i, + PhysicalCoreId = i, // Assume no HT for basic topology + SocketId = 0, + CoreType = CpuCoreType.Standard, + Label = $"Core {i}", + IsEnabled = true + }; + + topology.LogicalCores.Add(core); + } + } + + private async Task DetectAdvancedTopologyAsync(CpuTopologyModel topology) + { + // Try to detect Intel Hybrid (P/E cores) + await DetectIntelHybridAsync(topology); + + // Try to detect AMD CCD information + await DetectAmdCcdAsync(topology); + + // Try to detect HyperThreading + DetectHyperThreading(topology); + } + + private async Task DetectIntelHybridAsync(CpuTopologyModel topology) + { + try + { + // Intel Hybrid detection is complex and requires specific APIs + // For now, we'll use heuristics based on CPU brand and core count patterns + if (topology.CpuBrand.Contains("Intel", StringComparison.OrdinalIgnoreCase)) + { + // Check for 12th gen or later Intel processors (Alder Lake+) + if (topology.CpuBrand.Contains("12th") || topology.CpuBrand.Contains("13th") || + topology.CpuBrand.Contains("14th") || topology.CpuBrand.Contains("15th")) + { + // Heuristic: Assume first cores are P-cores, later ones are E-cores + // This is a simplified approach - real detection would require CPUID + var totalCores = topology.LogicalCores.Count; + var estimatedPCores = Math.Min(8, totalCores / 2); // Rough estimate + + for (int i = 0; i < topology.LogicalCores.Count; i++) + { + if (i < estimatedPCores * 2) // P-cores with HT + { + topology.LogicalCores[i].CoreType = CpuCoreType.PerformanceCore; + } + else + { + topology.LogicalCores[i].CoreType = CpuCoreType.EfficiencyCore; + } + } + } + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to detect Intel Hybrid topology"); + } + } + + private async Task DetectAmdCcdAsync(CpuTopologyModel topology) + { + try + { + if (topology.CpuBrand.Contains("AMD", StringComparison.OrdinalIgnoreCase)) + { + // AMD CCD detection - improved heuristic + // Only assign CCD if we actually have multiple CCDs + var totalPhysicalCores = topology.TotalPhysicalCores; + var coresPerCcd = 8; // Typical for Zen 2/3/4 + + // Only assign CCD IDs if we have more than 8 physical cores (indicating multiple CCDs) + if (totalPhysicalCores > coresPerCcd) + { + for (int i = 0; i < topology.LogicalCores.Count; i++) + { + var physicalCoreId = topology.LogicalCores[i].PhysicalCoreId; + topology.LogicalCores[i].CcdId = physicalCoreId / coresPerCcd; + topology.LogicalCores[i].CoreType = CpuCoreType.Zen3; // Default assumption + } + + _logger.LogInformation("Detected AMD multi-CCD configuration: {PhysicalCores} physical cores, estimated {CcdCount} CCDs", + totalPhysicalCores, (totalPhysicalCores + coresPerCcd - 1) / coresPerCcd); + } + else + { + // Single CCD or small core count - don't assign CCD IDs + foreach (var core in topology.LogicalCores) + { + core.CoreType = CpuCoreType.Zen3; // Default assumption + } + + _logger.LogInformation("Detected AMD single-CCD configuration: {PhysicalCores} physical cores", totalPhysicalCores); + } + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to detect AMD CCD topology"); + } + } + + private void DetectHyperThreading(CpuTopologyModel topology) + { + try + { + // Simple HT detection: if we have more logical than physical cores + var logicalCount = topology.LogicalCores.Count; + var physicalCount = topology.TotalPhysicalCores; + + if (logicalCount > physicalCount) + { + // Mark cores as HT siblings + for (int i = 0; i < topology.LogicalCores.Count; i += 2) + { + if (i + 1 < topology.LogicalCores.Count) + { + topology.LogicalCores[i].IsHyperThreaded = true; + topology.LogicalCores[i].HyperThreadSibling = i + 1; + topology.LogicalCores[i + 1].IsHyperThreaded = true; + topology.LogicalCores[i + 1].HyperThreadSibling = i; + } + } + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to detect HyperThreading"); + } + } + + private void ValidateTopology(CpuTopologyModel topology) + { + // Ensure we have at least one core + if (topology.LogicalCores.Count == 0) + { + CreateBasicTopology(topology, Environment.ProcessorCount); + } + + // Ensure logical core IDs are sequential + for (int i = 0; i < topology.LogicalCores.Count; i++) + { + topology.LogicalCores[i].LogicalCoreId = i; + } + + // Update labels - simplified without CCD clutter + foreach (var core in topology.LogicalCores) + { + var typeLabel = core.CoreType switch + { + CpuCoreType.PerformanceCore => "P", + CpuCoreType.EfficiencyCore => "E", + _ => "" + }; + + var htLabel = core.IsHyperThreaded ? " (HT)" : ""; + + core.Label = $"{typeLabel}Core {core.LogicalCoreId}{htLabel}"; + } + } + + private CpuTopologyModel CreateFallbackTopology() + { + var topology = new CpuTopologyModel(); + CreateBasicTopology(topology, Environment.ProcessorCount); + topology.TopologyDetectionSuccessful = false; + return topology; + } + + public IEnumerable GetAffinityPresets() + { + if (_currentTopology == null) + return Enumerable.Empty(); + + var presets = new List(); + + // All cores preset + presets.Add(new CpuAffinityPreset + { + Name = "All Cores", + Description = $"All {_currentTopology.TotalLogicalCores} logical cores", + AffinityMask = (1L << _currentTopology.TotalLogicalCores) - 1, + IsAvailable = true + }); + + // Physical cores only (if HT is available) + if (_currentTopology.HasHyperThreading) + { + presets.Add(new CpuAffinityPreset + { + Name = "Physical Cores Only", + Description = $"All {_currentTopology.TotalPhysicalCores} physical cores (no HyperThreading)", + AffinityMask = _currentTopology.GetPhysicalCoresAffinityMask(), + IsAvailable = true + }); + } + + // Performance cores (Intel Hybrid) + if (_currentTopology.HasIntelHybrid && _currentTopology.PerformanceCores.Any()) + { + presets.Add(new CpuAffinityPreset + { + Name = "Performance Cores", + Description = $"Intel P-cores ({_currentTopology.PerformanceCores.Count()} cores)", + AffinityMask = _currentTopology.GetPerformanceCoresAffinityMask(), + IsAvailable = true + }); + } + + // Efficiency cores (Intel Hybrid) + if (_currentTopology.HasIntelHybrid && _currentTopology.EfficiencyCores.Any()) + { + presets.Add(new CpuAffinityPreset + { + Name = "Efficiency Cores", + Description = $"Intel E-cores ({_currentTopology.EfficiencyCores.Count()} cores)", + AffinityMask = _currentTopology.GetEfficiencyCoresAffinityMask(), + IsAvailable = true + }); + } + + // CCD presets (AMD) + if (_currentTopology.HasAmdCcd) + { + foreach (var ccdId in _currentTopology.AvailableCcds) + { + var ccdCores = _currentTopology.GetCoresByCcd(ccdId); + presets.Add(new CpuAffinityPreset + { + Name = $"CCD {ccdId}", + Description = $"AMD CCD {ccdId} ({ccdCores.Count()} cores)", + AffinityMask = _currentTopology.GetCcdAffinityMask(ccdId), + IsAvailable = true + }); + } + } + + return presets; + } + + public bool IsAffinityMaskValid(long affinityMask) + { + if (_currentTopology == null) return false; + + var maxMask = (1L << _currentTopology.TotalLogicalCores) - 1; + return affinityMask > 0 && affinityMask <= maxMask; + } + + public int GetMaxLogicalCores() + { + return _currentTopology?.TotalLogicalCores ?? Environment.ProcessorCount; + } + + public async Task RefreshTopologyAsync() + { + await DetectTopologyAsync(); + } + } +} diff --git a/Services/EnhancedLoggingService.cs b/Services/EnhancedLoggingService.cs new file mode 100644 index 0000000..4d7e6e6 --- /dev/null +++ b/Services/EnhancedLoggingService.cs @@ -0,0 +1,481 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace ThreadPilot.Services +{ + /// + /// Enhanced logging service with file persistence and structured logging + /// + public class EnhancedLoggingService : IEnhancedLoggingService, IDisposable + { + private readonly ILogger _logger; + private readonly IApplicationSettingsService _settingsService; + private readonly SemaphoreSlim _fileLock = new(1, 1); + private readonly ConcurrentQueue _logQueue = new(); + private readonly System.Threading.Timer _flushTimer; + private readonly string _logDirectory; + private string _currentLogFilePath; + private bool _isInitialized; + private bool _disposed; + + public string CurrentLogFilePath => _currentLogFilePath; + public string LogDirectoryPath => _logDirectory; + public bool IsDebugLoggingEnabled => _settingsService.Settings.EnableDebugLogging; + + public event EventHandler? CriticalErrorOccurred; + + public EnhancedLoggingService(ILogger logger, IApplicationSettingsService settingsService) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + + // Set up log directory + _logDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ThreadPilot", "Logs"); + _currentLogFilePath = GetCurrentLogFilePath(); + + // Create flush timer (flush every 5 seconds) + _flushTimer = new System.Threading.Timer(FlushLogs, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); + } + + public async Task InitializeAsync() + { + if (_isInitialized) return; + + try + { + // Ensure log directory exists + Directory.CreateDirectory(_logDirectory); + + // Create initial log file if it doesn't exist + if (!File.Exists(_currentLogFilePath)) + { + await CreateNewLogFileAsync(); + } + + // Log initialization + await LogSystemEventAsync("LoggingService", "Enhanced logging service initialized", LogLevel.Information); + + // Clean up old logs + await CleanupOldLogsAsync(); + + _isInitialized = true; + _logger.LogInformation("Enhanced logging service initialized. Log directory: {LogDirectory}", _logDirectory); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize enhanced logging service"); + throw; + } + } + + public async Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason, string? processName = null) + { + var properties = new Dictionary + { + ["FromPlan"] = fromPlan, + ["ToPlan"] = toPlan, + ["Reason"] = reason, + ["ProcessName"] = processName ?? "N/A" + }; + + var message = processName != null + ? $"Power plan changed from '{fromPlan}' to '{toPlan}' due to process '{processName}' ({reason})" + : $"Power plan changed from '{fromPlan}' to '{toPlan}' ({reason})"; + + await LogStructuredEventAsync("PowerPlan", message, LogLevel.Information, properties); + } + + public async Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details) + { + var properties = new Dictionary + { + ["EventType"] = eventType, + ["ProcessName"] = processName, + ["ProcessId"] = processId, + ["Details"] = details + }; + + var message = $"Process monitoring event: {eventType} - {processName} (PID: {processId}) - {details}"; + await LogStructuredEventAsync("ProcessMonitoring", message, LogLevel.Information, properties); + } + + public async Task LogGameBoostEventAsync(string eventType, string gameName, string details) + { + var properties = new Dictionary + { + ["EventType"] = eventType, + ["GameName"] = gameName, + ["Details"] = details + }; + + var message = $"Game Boost {eventType}: {gameName} - {details}"; + await LogStructuredEventAsync("GameBoost", message, LogLevel.Information, properties); + } + + public async Task LogUserActionAsync(string action, string details, string? context = null) + { + var properties = new Dictionary + { + ["Action"] = action, + ["Details"] = details, + ["Context"] = context ?? "N/A" + }; + + var message = $"User action: {action} - {details}"; + if (!string.IsNullOrEmpty(context)) + { + message += $" (Context: {context})"; + } + + await LogStructuredEventAsync("UserAction", message, LogLevel.Information, properties); + } + + public async Task LogSystemEventAsync(string eventType, string message, LogLevel level = LogLevel.Information) + { + var properties = new Dictionary + { + ["EventType"] = eventType + }; + + await LogStructuredEventAsync("System", message, level, properties); + } + + public async Task LogErrorAsync(Exception exception, string context, Dictionary? additionalData = null) + { + var properties = new Dictionary + { + ["Context"] = context, + ["ExceptionType"] = exception.GetType().Name, + ["StackTrace"] = exception.StackTrace ?? "N/A" + }; + + if (additionalData != null) + { + foreach (var kvp in additionalData) + { + properties[kvp.Key] = kvp.Value; + } + } + + var message = $"Error in {context}: {exception.Message}"; + await LogStructuredEventAsync("Error", message, LogLevel.Error, properties, exception); + + // Raise critical error event for severe exceptions + if (exception is OutOfMemoryException or StackOverflowException or AccessViolationException) + { + CriticalErrorOccurred?.Invoke(this, new CriticalErrorEventArgs(exception, context, additionalData)); + } + } + + public async Task LogApplicationLifecycleEventAsync(string eventType, string details) + { + var properties = new Dictionary + { + ["EventType"] = eventType, + ["Details"] = details, + ["Version"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown" + }; + + var message = $"Application {eventType}: {details}"; + await LogStructuredEventAsync("Lifecycle", message, LogLevel.Information, properties); + } + + private async Task LogStructuredEventAsync(string category, string message, LogLevel level, Dictionary properties, Exception? exception = null) + { + if (!_isInitialized && category != "System") return; + + // Skip debug messages if debug logging is disabled + if (level == LogLevel.Debug && !IsDebugLoggingEnabled) return; + + var logEntry = new LogEntry + { + Timestamp = DateTime.UtcNow, + Level = level, + Category = category, + Message = message, + Exception = exception?.ToString(), + Properties = properties, + CorrelationId = Thread.CurrentThread.ManagedThreadId.ToString() + }; + + _logQueue.Enqueue(logEntry); + + // Force immediate flush for errors and critical events + if (level >= LogLevel.Error) + { + await FlushLogsAsync(); + } + } + + private async void FlushLogs(object? state) + { + await FlushLogsAsync(); + } + + private async Task FlushLogsAsync() + { + if (_logQueue.IsEmpty) return; + + await _fileLock.WaitAsync(); + try + { + // Check if we need to rotate the log file + await CheckLogRotationAsync(); + + var logEntries = new List(); + while (_logQueue.TryDequeue(out var entry)) + { + logEntries.Add(entry); + } + + if (logEntries.Count == 0) return; + + // Write entries to file + await WriteLogEntriesToFileAsync(logEntries); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to flush logs to file"); + } + finally + { + _fileLock.Release(); + } + } + + private async Task WriteLogEntriesToFileAsync(List entries) + { + var logLines = entries.Select(FormatLogEntry); + await File.AppendAllLinesAsync(_currentLogFilePath, logLines); + } + + private string FormatLogEntry(LogEntry entry) + { + var logData = new + { + timestamp = entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"), + level = entry.Level.ToString(), + category = entry.Category, + message = entry.Message, + exception = entry.Exception, + properties = entry.Properties, + correlationId = entry.CorrelationId + }; + + return JsonSerializer.Serialize(logData, new JsonSerializerOptions { WriteIndented = false }); + } + + private async Task CheckLogRotationAsync() + { + var fileInfo = new FileInfo(_currentLogFilePath); + var maxSizeBytes = _settingsService.Settings.MaxLogFileSizeMb * 1024 * 1024; + + if (fileInfo.Exists && fileInfo.Length > maxSizeBytes) + { + // Rotate log file + var rotatedPath = Path.Combine(_logDirectory, $"ThreadPilot_{DateTime.UtcNow:yyyyMMdd_HHmmss}.log"); + File.Move(_currentLogFilePath, rotatedPath); + await CreateNewLogFileAsync(); + } + } + + private async Task CreateNewLogFileAsync() + { + _currentLogFilePath = GetCurrentLogFilePath(); + await File.WriteAllTextAsync(_currentLogFilePath, $"# ThreadPilot Log File - Created {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC{Environment.NewLine}"); + } + + private string GetCurrentLogFilePath() + { + return Path.Combine(_logDirectory, "ThreadPilot.log"); + } + + public async Task> GetRecentLogEntriesAsync(int count = 100) + { + return await GetLogEntriesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow); + } + + public async Task> GetLogEntriesAsync(DateTime fromDate, DateTime toDate) + { + var entries = new List(); + + await _fileLock.WaitAsync(); + try + { + var logFiles = Directory.GetFiles(_logDirectory, "*.log") + .OrderByDescending(f => new FileInfo(f).CreationTime); + + foreach (var logFile in logFiles) + { + var fileEntries = await ReadLogEntriesFromFileAsync(logFile, fromDate, toDate); + entries.AddRange(fileEntries); + } + + return entries.OrderByDescending(e => e.Timestamp).Take(1000).ToList(); + } + finally + { + _fileLock.Release(); + } + } + + private async Task> ReadLogEntriesFromFileAsync(string filePath, DateTime fromDate, DateTime toDate) + { + var entries = new List(); + + try + { + var lines = await File.ReadAllLinesAsync(filePath); + foreach (var line in lines) + { + if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line)) continue; + + try + { + var logData = JsonSerializer.Deserialize(line); + var timestamp = DateTime.Parse(logData.GetProperty("timestamp").GetString()!); + + if (timestamp >= fromDate && timestamp <= toDate) + { + var entry = new LogEntry + { + Timestamp = timestamp, + Level = Enum.Parse(logData.GetProperty("level").GetString()!), + Category = logData.GetProperty("category").GetString()!, + Message = logData.GetProperty("message").GetString()!, + Exception = logData.TryGetProperty("exception", out var ex) ? ex.GetString() : null, + CorrelationId = logData.TryGetProperty("correlationId", out var cid) ? cid.GetString() : null + }; + + if (logData.TryGetProperty("properties", out var props)) + { + entry.Properties = JsonSerializer.Deserialize>(props.GetRawText()) ?? new(); + } + + entries.Add(entry); + } + } + catch + { + // Skip malformed log entries + } + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to read log entries from file: {FilePath}", filePath); + } + + return entries; + } + + public async Task CleanupOldLogsAsync() + { + await _fileLock.WaitAsync(); + try + { + var retentionDate = DateTime.UtcNow.AddDays(-_settingsService.Settings.LogRetentionDays); + var logFiles = Directory.GetFiles(_logDirectory, "*.log"); + + foreach (var logFile in logFiles) + { + var fileInfo = new FileInfo(logFile); + if (fileInfo.CreationTime < retentionDate && Path.GetFileName(logFile) != "ThreadPilot.log") + { + try + { + File.Delete(logFile); + _logger.LogDebug("Deleted old log file: {LogFile}", logFile); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to delete old log file: {LogFile}", logFile); + } + } + } + } + finally + { + _fileLock.Release(); + } + } + + public async Task GetLogStatisticsAsync() + { + await _fileLock.WaitAsync(); + try + { + var stats = new LogFileStatistics(); + var logFiles = Directory.GetFiles(_logDirectory, "*.log"); + + stats.TotalLogFiles = logFiles.Length; + + foreach (var logFile in logFiles) + { + var fileInfo = new FileInfo(logFile); + stats.TotalLogSizeBytes += fileInfo.Length; + + if (Path.GetFileName(logFile) == "ThreadPilot.log") + { + stats.CurrentFileSizeBytes = fileInfo.Length; + } + + if (stats.OldestLogDate == default || fileInfo.CreationTime < stats.OldestLogDate) + { + stats.OldestLogDate = fileInfo.CreationTime; + } + + if (fileInfo.CreationTime > stats.NewestLogDate) + { + stats.NewestLogDate = fileInfo.CreationTime; + } + } + + return stats; + } + finally + { + _fileLock.Release(); + } + } + + public async Task ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null) + { + exportPath ??= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + $"ThreadPilot_Logs_{DateTime.Now:yyyyMMdd_HHmmss}.txt"); + + var entries = await GetLogEntriesAsync(fromDate, toDate); + var exportLines = entries.Select(e => $"{e.Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{e.Level}] {e.Category}: {e.Message}"); + + await File.WriteAllLinesAsync(exportPath, exportLines); + return exportPath; + } + + public async Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays) + { + _settingsService.Settings.EnableDebugLogging = enableDebugLogging; + _settingsService.Settings.MaxLogFileSizeMb = maxFileSizeMb; + _settingsService.Settings.LogRetentionDays = retentionDays; + + await _settingsService.SaveSettingsAsync(); + await LogSystemEventAsync("Configuration", $"Logging configuration updated: Debug={enableDebugLogging}, MaxSize={maxFileSizeMb}MB, Retention={retentionDays}days"); + } + + public void Dispose() + { + if (_disposed) return; + + _flushTimer?.Dispose(); + FlushLogsAsync().Wait(TimeSpan.FromSeconds(5)); + _fileLock?.Dispose(); + _disposed = true; + } + } +} diff --git a/Services/GameBoostService.cs b/Services/GameBoostService.cs new file mode 100644 index 0000000..098d4b8 --- /dev/null +++ b/Services/GameBoostService.cs @@ -0,0 +1,629 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing Game Boost mode functionality + /// + public class GameBoostService : IGameBoostService + { + private readonly ILogger _logger; + private readonly IPowerPlanService _powerPlanService; + private readonly IProcessService _processService; + private readonly INotificationService _notificationService; + private readonly IApplicationSettingsService _settingsService; + + private ApplicationSettingsModel _settings; + private bool _isGameBoostActive; + private ProcessModel? _currentGameProcess; + private string? _previousPowerPlanId; + private DateTime? _gameBoostStartTime; + private readonly List _knownGameExecutables; + + public event EventHandler? GameBoostActivated; + public event EventHandler? GameBoostDeactivated; + public event EventHandler? GameDetected; + + public bool IsGameBoostActive => _isGameBoostActive; + public ProcessModel? CurrentGameProcess => _currentGameProcess; + public IReadOnlyList KnownGameExecutables => _knownGameExecutables.AsReadOnly(); + + public GameBoostService( + ILogger logger, + IPowerPlanService powerPlanService, + IProcessService processService, + INotificationService notificationService, + IApplicationSettingsService settingsService) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _processService = processService ?? throw new ArgumentNullException(nameof(processService)); + _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + + _settings = _settingsService.Settings; + _knownGameExecutables = InitializeKnownGames(); + + // Subscribe to settings changes + _settingsService.SettingsChanged += OnSettingsChanged; + + _logger.LogInformation("Game Boost service initialized with {Count} known games", _knownGameExecutables.Count); + } + + public async Task EnableGameBoostAsync() + { + try + { + if (!_settings.EnableGameBoostMode) + { + _logger.LogWarning("Game Boost mode is disabled in settings"); + return false; + } + + _logger.LogInformation("Game Boost mode enabled"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to enable Game Boost mode"); + return false; + } + } + + public async Task DisableGameBoostAsync() + { + try + { + if (_isGameBoostActive) + { + await DeactivateGameBoostAsync(); + } + + _logger.LogInformation("Game Boost mode disabled"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to disable Game Boost mode"); + return false; + } + } + + public async Task ActivateGameBoostAsync(ProcessModel process) + { + try + { + if (_isGameBoostActive && _currentGameProcess?.ProcessId == process.ProcessId) + { + _logger.LogDebug("Game Boost already active for process {ProcessName}", process.Name); + return true; + } + + // Deactivate current boost if active + if (_isGameBoostActive) + { + await DeactivateGameBoostAsync(); + } + + // Store current power plan + var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); + _previousPowerPlanId = currentPowerPlan?.Guid; + + // Apply Game Boost power plan + var gameBoostPowerPlanId = !string.IsNullOrEmpty(_settings.GameBoostPowerPlanId) + ? _settings.GameBoostPowerPlanId + : await GetHighPerformancePowerPlanIdAsync(); + + if (!string.IsNullOrEmpty(gameBoostPowerPlanId)) + { + await _powerPlanService.SetActivePowerPlanByGuidAsync(gameBoostPowerPlanId); + } + + // Set high priority if enabled + if (_settings.GameBoostSetHighPriority) + { + await SetProcessPriorityAsync(process, ProcessPriorityClass.High); + } + + // Optimize CPU affinity if enabled + if (_settings.GameBoostOptimizeCpuAffinity) + { + await OptimizeCpuAffinityAsync(process); + } + + _isGameBoostActive = true; + _currentGameProcess = process; + _gameBoostStartTime = DateTime.Now; + + _logger.LogInformation("Game Boost activated for {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + + // Fire events + GameDetected?.Invoke(this, new GameDetectedEventArgs(process, _knownGameExecutables.Contains(process.Name.ToLowerInvariant()))); + GameBoostActivated?.Invoke(this, new GameBoostActivatedEventArgs(process, gameBoostPowerPlanId ?? "")); + + await _notificationService.ShowSuccessNotificationAsync( + "Game Boost Activated", + $"Game Boost mode activated for {process.Name}"); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to activate Game Boost for process {ProcessName}", process.Name); + return false; + } + } + + public async Task DeactivateGameBoostAsync() + { + try + { + if (!_isGameBoostActive) + { + return true; + } + + var duration = _gameBoostStartTime.HasValue + ? DateTime.Now - _gameBoostStartTime.Value + : TimeSpan.Zero; + + // Restore previous power plan + if (!string.IsNullOrEmpty(_previousPowerPlanId)) + { + await _powerPlanService.SetActivePowerPlanByGuidAsync(_previousPowerPlanId); + } + else if (!string.IsNullOrEmpty(_settings.DefaultPowerPlanId)) + { + await _powerPlanService.SetActivePowerPlanByGuidAsync(_settings.DefaultPowerPlanId); + } + + var gameProcess = _currentGameProcess; + var restoredPowerPlanId = _previousPowerPlanId ?? _settings.DefaultPowerPlanId; + + _isGameBoostActive = false; + _currentGameProcess = null; + _previousPowerPlanId = null; + _gameBoostStartTime = null; + + _logger.LogInformation("Game Boost deactivated after {Duration}", duration); + + GameBoostDeactivated?.Invoke(this, new GameBoostDeactivatedEventArgs( + gameProcess, restoredPowerPlanId, duration)); + + await _notificationService.ShowNotificationAsync( + "Game Boost Deactivated", + $"Game Boost mode deactivated after {duration:hh\\:mm\\:ss}", + NotificationType.Information); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to deactivate Game Boost"); + return false; + } + } + + public async Task AddKnownGameAsync(string executableName) + { + if (string.IsNullOrWhiteSpace(executableName)) + return false; + + var normalizedName = executableName.ToLowerInvariant(); + if (!_knownGameExecutables.Contains(normalizedName)) + { + _knownGameExecutables.Add(normalizedName); + _logger.LogInformation("Added known game: {ExecutableName}", executableName); + return true; + } + + return false; + } + + public async Task RemoveKnownGameAsync(string executableName) + { + if (string.IsNullOrWhiteSpace(executableName)) + return false; + + var normalizedName = executableName.ToLowerInvariant(); + var removed = _knownGameExecutables.Remove(normalizedName); + + if (removed) + { + _logger.LogInformation("Removed known game: {ExecutableName}", executableName); + } + + return removed; + } + + public IReadOnlyList GetKnownGameExecutables() + { + return _knownGameExecutables.ToList().AsReadOnly(); + } + + public bool IsGameProcess(ProcessModel process) + { + if (process == null || string.IsNullOrEmpty(process.Name)) + return false; + + var processName = process.Name.ToLowerInvariant(); + + // Check against known games list + if (_knownGameExecutables.Contains(processName)) + return true; + + // Auto-detection heuristics (if enabled) + if (_settings.GameBoostAutoDetectGames) + { + return IsLikelyGameProcess(process); + } + + return false; + } + + private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e) + { + try + { + _settings = e.NewSettings; + _logger.LogDebug("Game Boost settings updated"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error updating Game Boost settings"); + } + } + + private List InitializeKnownGames() + { + return new List + { + // Game Launchers + "steam.exe", + "steamwebhelper.exe", + "origin.exe", + "epicgameslauncher.exe", + "uplay.exe", + "ubisoft connect.exe", + "battlenet.exe", + "battle.net.exe", + "gog.exe", + "gog galaxy.exe", + "rockstarlauncher.exe", + "bethesdanetlauncher.exe", + "ea desktop.exe", + "xbox.exe", + "xboxapp.exe", + "gamepass.exe", + + // Popular Games - FPS/Shooters + "csgo.exe", + "cs2.exe", + "valorant.exe", + "valorant-win64-shipping.exe", + "fortniteclient-win64-shipping.exe", + "fortnite.exe", + "apex_legends.exe", + "r5apex.exe", + "overwatch.exe", + "overwatch2.exe", + "cod.exe", + "modernwarfare.exe", + "warzone.exe", + "blackops.exe", + "rainbow6.exe", + "rainbowsix.exe", + "pubg.exe", + "tslgame.exe", + "bf1.exe", + "bfv.exe", + "bf2042.exe", + "titanfall2.exe", + "doom.exe", + "doomslayers.exe", + "doom eternal.exe", + "halo.exe", + "haloinfinite.exe", + "destiny2.exe", + + // Popular Games - MOBA/Strategy + "dota2.exe", + "league of legends.exe", + "lol.exe", + "riotclientservices.exe", + "teamfighttactics.exe", + "starcraft2.exe", + "sc2.exe", + "warcraft3.exe", + "aoe2de.exe", + "aoe4.exe", + "civilization6.exe", + "civ6.exe", + "totalwar.exe", + + // Popular Games - RPG/Adventure + "witcher3.exe", + "cyberpunk2077.exe", + "skyrim.exe", + "skyrimse.exe", + "fallout4.exe", + "fallout76.exe", + "elderscrollsonline.exe", + "wow.exe", + "worldofwarcraft.exe", + "ffxiv.exe", + "ffxiv_dx11.exe", + "guildwars2.exe", + "newworld.exe", + "lostark.exe", + "diablo3.exe", + "diablo4.exe", + "pathofexile.exe", + "borderlands3.exe", + "masseffect.exe", + "dragonage.exe", + "assassinscreed.exe", + "farcry.exe", + "watchdogs.exe", + + // Popular Games - Open World/Action + "gta5.exe", + "gtav.exe", + "rdr2.exe", + "reddeadredemption2.exe", + "minecraft.exe", + "minecraftlauncher.exe", + "javaw.exe", // Minecraft Java + "terraria.exe", + "stardewvalley.exe", + "subnautica.exe", + "nomanssky.exe", + "spiderman.exe", + "godofwar.exe", + "horizonzerodawn.exe", + "deathstranding.exe", + + // Popular Games - Racing/Sports + "forza.exe", + "forzahorizon.exe", + "granturismo.exe", + "f1.exe", + "dirt.exe", + "wreckfest.exe", + "fifa.exe", + "nba2k.exe", + "madden.exe", + "rocketleague.exe", + + // Popular Games - Simulation/Building + "citiesskylines.exe", + "simcity.exe", + "planetcoaster.exe", + "twopointcampus.exe", + "kerbalspaceprogram.exe", + "factorio.exe", + "satisfactory.exe", + "valheim.exe", + "rust.exe", + "ark.exe", + "7daystodie.exe", + "greenhell.exe", + "theforest.exe", + + // VR Games + "vrchat.exe", + "beatsaber.exe", + "halflife alyx.exe", + "pavlov.exe", + "boneworks.exe", + + // Indie/Popular Smaller Games + "amongus.exe", + "fallguys.exe", + "cuphead.exe", + "hollowknight.exe", + "celeste.exe", + "ori.exe", + "hades.exe", + "deadcells.exe", + "riskofrain2.exe", + "deeprockgalactic.exe", + "seaofthieves.exe", + "phasmophobia.exe", + "genshinimpact.exe", + "honkaiimpact.exe" + }; + } + + private bool IsLikelyGameProcess(ProcessModel process) + { + try + { + var processName = process.Name.ToLowerInvariant(); + var processPath = process.ExecutablePath?.ToLowerInvariant() ?? ""; + + // Skip system processes and common applications + if (IsSystemOrCommonProcess(processName)) + return false; + + // Check for game-related keywords in process name + if (HasGameKeywords(processName)) + return true; + + // Check for game-related paths + if (HasGamePath(processPath)) + return true; + + // Check for game engines + if (HasGameEngineIndicators(processName, processPath)) + return true; + + // Check for executable patterns common in games + if (HasGameExecutablePatterns(processName)) + return true; + + return false; + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Error in game detection heuristics for process {ProcessName}", process.Name); + return false; + } + } + + private bool IsSystemOrCommonProcess(string processName) + { + var systemProcesses = new[] + { + "explorer.exe", "dwm.exe", "winlogon.exe", "csrss.exe", "smss.exe", "wininit.exe", + "services.exe", "lsass.exe", "svchost.exe", "taskhost.exe", "taskhostw.exe", + "conhost.exe", "audiodg.exe", "spoolsv.exe", "winlogon.exe", "userinit.exe", + "chrome.exe", "firefox.exe", "msedge.exe", "iexplore.exe", "opera.exe", + "notepad.exe", "calc.exe", "mspaint.exe", "wordpad.exe", "cmd.exe", "powershell.exe", + "winword.exe", "excel.exe", "powerpoint.exe", "outlook.exe", "onenote.exe", + "photoshop.exe", "illustrator.exe", "premiere.exe", "aftereffects.exe", + "code.exe", "devenv.exe", "rider.exe", "intellij.exe", "eclipse.exe", + "discord.exe", "slack.exe", "teams.exe", "zoom.exe", "skype.exe", + "spotify.exe", "vlc.exe", "wmplayer.exe", "itunes.exe", "winamp.exe", + "7z.exe", "winrar.exe", "winzip.exe", "filezilla.exe", "putty.exe" + }; + + return systemProcesses.Contains(processName); + } + + private bool HasGameKeywords(string processName) + { + var gameKeywords = new[] + { + "game", "launcher", "client", "engine", "unity", "unreal", "godot", "cryengine", + "steam", "epic", "origin", "uplay", "battlenet", "gog", "rockstar", + "minecraft", "roblox", "fortnite", "valorant", "csgo", "dota", "lol", + "wow", "overwatch", "apex", "pubg", "cod", "battlefield", "destiny", + "cyberpunk", "witcher", "skyrim", "fallout", "gta", "rdr", "assassin", + "farcry", "watchdog", "borderlands", "diablo", "starcraft", "warcraft", + "civilization", "totalwar", "aoe", "fifa", "nba", "madden", "forza", + "racing", "simulator", "tycoon", "builder", "strategy", "rpg", "mmo", + "shooter", "adventure", "action", "puzzle", "platformer", "indie" + }; + + return gameKeywords.Any(keyword => processName.Contains(keyword)); + } + + private bool HasGamePath(string processPath) + { + if (string.IsNullOrEmpty(processPath)) + return false; + + var gamePaths = new[] + { + @"\steam\steamapps\", @"\steamapps\common\", @"\steam games\", + @"\epic games\", @"\epicgames\", @"\epic\", + @"\origin games\", @"\origin\", @"\ea games\", + @"\ubisoft\", @"\uplay\", @"\ubisoft game launcher\", + @"\gog galaxy\", @"\gog games\", @"\gog.com\", + @"\battle.net\", @"\battlenet\", @"\blizzard\", + @"\rockstar games\", @"\rockstar\", + @"\xbox games\", @"\microsoft games\", @"\windowsapps\", + @"\games\", @"\gaming\", @"\my games\", + @"\program files\games\", @"\program files (x86)\games\", + @"\minecraft\", @"\roblox\", @"\riot games\", + @"\square enix\", @"\activision\", @"\electronic arts\", + @"\2k games\", @"\bethesda\", @"\cd projekt red\", + @"\valve\", @"\id software\", @"\bungie\" + }; + + return gamePaths.Any(path => processPath.Contains(path)); + } + + private bool HasGameEngineIndicators(string processName, string processPath) + { + var engineIndicators = new[] + { + "unity", "unreal", "ue4", "ue5", "godot", "cryengine", "frostbite", + "source", "idtech", "creation", "anvil", "dunia", "snowdrop", + "decima", "fox", "mt framework", "luminous", "crystal tools", + "gamebryo", "havok", "physx", "directx", "opengl", "vulkan" + }; + + return engineIndicators.Any(indicator => + processName.Contains(indicator) || processPath.Contains(indicator)); + } + + private bool HasGameExecutablePatterns(string processName) + { + // Common patterns in game executables + var patterns = new[] + { + // Shipping builds (Unreal Engine) + "shipping.exe", "-shipping.exe", "_shipping.exe", + // Win64 builds + "win64.exe", "-win64.exe", "_win64.exe", + // Game suffixes + "game.exe", "_game.exe", "-game.exe", + // Client executables + "client.exe", "_client.exe", "-client.exe", + // Launcher patterns + "launcher.exe", "_launcher.exe", "-launcher.exe", + // Engine patterns + "engine.exe", "_engine.exe", "-engine.exe", + // Common game number patterns (sequels) + "2.exe", "3.exe", "4.exe", "5.exe", "2077.exe", "2042.exe" + }; + + return patterns.Any(pattern => processName.EndsWith(pattern)); + } + + private async Task GetHighPerformancePowerPlanIdAsync() + { + try + { + var powerPlans = await _powerPlanService.GetPowerPlansAsync(); + var highPerformancePlan = powerPlans.FirstOrDefault(p => + p.Name.Contains("High performance", StringComparison.OrdinalIgnoreCase) || + p.Name.Contains("Ultimate Performance", StringComparison.OrdinalIgnoreCase)); + + return highPerformancePlan?.Guid; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to get high performance power plan"); + return null; + } + } + + private async Task SetProcessPriorityAsync(ProcessModel processModel, ProcessPriorityClass priority) + { + try + { + var process = Process.GetProcessById(processModel.ProcessId); + process.PriorityClass = priority; + _logger.LogDebug("Set process {ProcessName} priority to {Priority}", processModel.Name, priority); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to set process priority for {ProcessName}", processModel.Name); + } + } + + private async Task OptimizeCpuAffinityAsync(ProcessModel processModel) + { + try + { + // This would integrate with the CPU topology service + // For now, just log the intent + _logger.LogDebug("CPU affinity optimization requested for {ProcessName}", processModel.Name); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to optimize CPU affinity for {ProcessName}", processModel.Name); + } + } + } +} diff --git a/Services/IApplicationSettingsService.cs b/Services/IApplicationSettingsService.cs new file mode 100644 index 0000000..0e38da4 --- /dev/null +++ b/Services/IApplicationSettingsService.cs @@ -0,0 +1,82 @@ +using System; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing application settings + /// + public interface IApplicationSettingsService + { + /// + /// Event fired when settings are changed + /// + event EventHandler? SettingsChanged; + + /// + /// Gets the current application settings + /// + ApplicationSettingsModel Settings { get; } + + /// + /// Loads settings from storage + /// + Task LoadSettingsAsync(); + + /// + /// Saves current settings to storage + /// + Task SaveSettingsAsync(); + + /// + /// Updates settings and saves them + /// + Task UpdateSettingsAsync(ApplicationSettingsModel newSettings); + + /// + /// Resets settings to default values + /// + Task ResetToDefaultsAsync(); + + /// + /// Gets the settings file path + /// + string GetSettingsFilePath(); + + /// + /// Validates settings and fixes any invalid values + /// + void ValidateAndFixSettings(); + + /// + /// Exports settings to a file + /// + Task ExportSettingsAsync(string filePath); + + /// + /// Imports settings from a file + /// + Task ImportSettingsAsync(string filePath); + } + + /// + /// Event args for settings changed event + /// + public class ApplicationSettingsChangedEventArgs : EventArgs + { + public ApplicationSettingsModel OldSettings { get; } + public ApplicationSettingsModel NewSettings { get; } + public string[] ChangedProperties { get; } + + public ApplicationSettingsChangedEventArgs( + ApplicationSettingsModel oldSettings, + ApplicationSettingsModel newSettings, + string[] changedProperties) + { + OldSettings = oldSettings; + NewSettings = newSettings; + ChangedProperties = changedProperties; + } + } +} diff --git a/Services/IAutostartService.cs b/Services/IAutostartService.cs new file mode 100644 index 0000000..2a91a75 --- /dev/null +++ b/Services/IAutostartService.cs @@ -0,0 +1,78 @@ +using System; +using System.Threading.Tasks; + +namespace ThreadPilot.Services +{ + /// + /// Interface for managing Windows autostart functionality + /// + public interface IAutostartService + { + /// + /// Event fired when autostart status changes + /// + event EventHandler? AutostartStatusChanged; + + /// + /// Gets whether the application is currently set to autostart with Windows + /// + bool IsAutostartEnabled { get; } + + /// + /// Gets the current autostart registry entry path + /// + string? AutostartPath { get; } + + /// + /// Enables autostart with Windows + /// + /// Whether to start the application minimized + /// True if successful, false otherwise + Task EnableAutostartAsync(bool startMinimized = true); + + /// + /// Disables autostart with Windows + /// + /// True if successful, false otherwise + Task DisableAutostartAsync(); + + /// + /// Checks if autostart is currently enabled + /// + /// True if autostart is enabled, false otherwise + Task CheckAutostartStatusAsync(); + + /// + /// Updates the autostart entry with new parameters + /// + /// Whether to start minimized + /// True if successful, false otherwise + Task UpdateAutostartAsync(bool startMinimized = true); + + /// + /// Gets the command line arguments for autostart + /// + /// Whether to include start minimized flag + /// Command line arguments string + string GetAutostartArguments(bool startMinimized = true); + } + + /// + /// Event arguments for autostart status changes + /// + public class AutostartStatusChangedEventArgs : EventArgs + { + public bool IsEnabled { get; } + public bool StartMinimized { get; } + public string? RegistryPath { get; } + public Exception? Error { get; } + + public AutostartStatusChangedEventArgs(bool isEnabled, bool startMinimized = false, string? registryPath = null, Exception? error = null) + { + IsEnabled = isEnabled; + StartMinimized = startMinimized; + RegistryPath = registryPath; + Error = error; + } + } +} diff --git a/Services/ICpuTopologyService.cs b/Services/ICpuTopologyService.cs new file mode 100644 index 0000000..f55c205 --- /dev/null +++ b/Services/ICpuTopologyService.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for detecting and managing CPU topology information + /// + public interface ICpuTopologyService + { + /// + /// Event fired when CPU topology is detected or updated + /// + event EventHandler? TopologyDetected; + + /// + /// Gets the current CPU topology information + /// + CpuTopologyModel? CurrentTopology { get; } + + /// + /// Detects CPU topology information + /// + Task DetectTopologyAsync(); + + /// + /// Gets available affinity presets based on current topology + /// + IEnumerable GetAffinityPresets(); + + /// + /// Validates if an affinity mask is valid for the current system + /// + bool IsAffinityMaskValid(long affinityMask); + + /// + /// Gets the maximum number of logical cores supported + /// + int GetMaxLogicalCores(); + + /// + /// Refreshes topology information (useful for hot-plug scenarios) + /// + Task RefreshTopologyAsync(); + } + + /// + /// Event arguments for CPU topology detection + /// + public class CpuTopologyDetectedEventArgs : EventArgs + { + public CpuTopologyModel Topology { get; } + public bool DetectionSuccessful { get; } + public string? ErrorMessage { get; } + public DateTime DetectionTime { get; } + + public CpuTopologyDetectedEventArgs(CpuTopologyModel topology, bool successful, string? errorMessage = null) + { + Topology = topology; + DetectionSuccessful = successful; + ErrorMessage = errorMessage; + DetectionTime = DateTime.Now; + } + } +} diff --git a/Services/IEnhancedLoggingService.cs b/Services/IEnhancedLoggingService.cs new file mode 100644 index 0000000..08c0699 --- /dev/null +++ b/Services/IEnhancedLoggingService.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace ThreadPilot.Services +{ + /// + /// Enhanced logging service interface for persistent, structured logging + /// + public interface IEnhancedLoggingService + { + /// + /// Gets the current log file path + /// + string CurrentLogFilePath { get; } + + /// + /// Gets the log directory path + /// + string LogDirectoryPath { get; } + + /// + /// Gets whether debug logging is enabled + /// + bool IsDebugLoggingEnabled { get; } + + /// + /// Event raised when a critical error occurs + /// + event EventHandler? CriticalErrorOccurred; + + /// + /// Initialize the logging service + /// + Task InitializeAsync(); + + /// + /// Log a power plan change event + /// + Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason, string? processName = null); + + /// + /// Log a process monitoring event + /// + Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details); + + /// + /// Log a game boost event + /// + Task LogGameBoostEventAsync(string eventType, string gameName, string details); + + /// + /// Log a user action + /// + Task LogUserActionAsync(string action, string details, string? context = null); + + /// + /// Log a system event + /// + Task LogSystemEventAsync(string eventType, string message, LogLevel level = LogLevel.Information); + + /// + /// Log an error with structured data + /// + Task LogErrorAsync(Exception exception, string context, Dictionary? additionalData = null); + + /// + /// Log application startup/shutdown events + /// + Task LogApplicationLifecycleEventAsync(string eventType, string details); + + /// + /// Get recent log entries + /// + Task> GetRecentLogEntriesAsync(int count = 100); + + /// + /// Get log entries for a specific date range + /// + Task> GetLogEntriesAsync(DateTime fromDate, DateTime toDate); + + /// + /// Clean up old log files based on retention policy + /// + Task CleanupOldLogsAsync(); + + /// + /// Get log file statistics + /// + Task GetLogStatisticsAsync(); + + /// + /// Export logs to a file + /// + Task ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null); + + /// + /// Update logging configuration + /// + Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays); + } + + /// + /// Event args for critical errors + /// + public class CriticalErrorEventArgs : EventArgs + { + public Exception Exception { get; } + public string Context { get; } + public DateTime Timestamp { get; } + public Dictionary AdditionalData { get; } + + public CriticalErrorEventArgs(Exception exception, string context, Dictionary? additionalData = null) + { + Exception = exception; + Context = context; + Timestamp = DateTime.UtcNow; + AdditionalData = additionalData ?? new Dictionary(); + } + } + + /// + /// Represents a log entry + /// + public class LogEntry + { + public DateTime Timestamp { get; set; } + public LogLevel Level { get; set; } + public string Category { get; set; } = string.Empty; + public string Message { get; set; } = string.Empty; + public string? Exception { get; set; } + public Dictionary Properties { get; set; } = new(); + public string? CorrelationId { get; set; } + } + + /// + /// Log file statistics + /// + public class LogFileStatistics + { + public long CurrentFileSizeBytes { get; set; } + public int TotalLogFiles { get; set; } + public long TotalLogSizeBytes { get; set; } + public DateTime OldestLogDate { get; set; } + public DateTime NewestLogDate { get; set; } + public int ErrorCount { get; set; } + public int WarningCount { get; set; } + public int InfoCount { get; set; } + } +} diff --git a/Services/IGameBoostService.cs b/Services/IGameBoostService.cs new file mode 100644 index 0000000..eee9eda --- /dev/null +++ b/Services/IGameBoostService.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Interface for Game Boost mode functionality + /// + public interface IGameBoostService + { + /// + /// Event fired when Game Boost mode is activated + /// + event EventHandler? GameBoostActivated; + + /// + /// Event fired when Game Boost mode is deactivated + /// + event EventHandler? GameBoostDeactivated; + + /// + /// Event fired when a game is detected + /// + event EventHandler? GameDetected; + + /// + /// Gets whether Game Boost mode is currently active + /// + bool IsGameBoostActive { get; } + + /// + /// Gets the currently detected game process + /// + ProcessModel? CurrentGameProcess { get; } + + /// + /// Gets the list of known game executables + /// + IReadOnlyList KnownGameExecutables { get; } + + /// + /// Gets the list of known game executables as a collection + /// + IReadOnlyList GetKnownGameExecutables(); + + /// + /// Enables Game Boost mode + /// + Task EnableGameBoostAsync(); + + /// + /// Disables Game Boost mode + /// + Task DisableGameBoostAsync(); + + /// + /// Manually activates Game Boost for a specific process + /// + /// The process to boost + Task ActivateGameBoostAsync(ProcessModel process); + + /// + /// Manually deactivates Game Boost + /// + Task DeactivateGameBoostAsync(); + + /// + /// Adds a game executable to the known games list + /// + /// Name of the executable (e.g., "game.exe") + Task AddKnownGameAsync(string executableName); + + /// + /// Removes a game executable from the known games list + /// + /// Name of the executable to remove + Task RemoveKnownGameAsync(string executableName); + + /// + /// Checks if a process is considered a game + /// + /// The process to check + bool IsGameProcess(ProcessModel process); + } + + /// + /// Event arguments for Game Boost activation + /// + public class GameBoostActivatedEventArgs : EventArgs + { + public ProcessModel GameProcess { get; } + public string PowerPlanId { get; } + public DateTime ActivatedAt { get; } + + public GameBoostActivatedEventArgs(ProcessModel gameProcess, string powerPlanId) + { + GameProcess = gameProcess; + PowerPlanId = powerPlanId; + ActivatedAt = DateTime.Now; + } + } + + /// + /// Event arguments for Game Boost deactivation + /// + public class GameBoostDeactivatedEventArgs : EventArgs + { + public ProcessModel? GameProcess { get; } + public string? RestoredPowerPlanId { get; } + public DateTime DeactivatedAt { get; } + public TimeSpan Duration { get; } + + public GameBoostDeactivatedEventArgs(ProcessModel? gameProcess, string? restoredPowerPlanId, TimeSpan duration) + { + GameProcess = gameProcess; + RestoredPowerPlanId = restoredPowerPlanId; + DeactivatedAt = DateTime.Now; + Duration = duration; + } + } + + /// + /// Event arguments for game detection + /// + public class GameDetectedEventArgs : EventArgs + { + public ProcessModel GameProcess { get; } + public bool IsKnownGame { get; } + public DateTime DetectedAt { get; } + + public GameDetectedEventArgs(ProcessModel gameProcess, bool isKnownGame) + { + GameProcess = gameProcess; + IsKnownGame = isKnownGame; + DetectedAt = DateTime.Now; + } + } +} diff --git a/Services/INotificationService.cs b/Services/INotificationService.cs new file mode 100644 index 0000000..64b94f0 --- /dev/null +++ b/Services/INotificationService.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing notifications (balloon tips and toast notifications) + /// + public interface INotificationService + { + /// + /// Event fired when a notification is shown + /// + event EventHandler? NotificationShown; + + /// + /// Event fired when a notification is dismissed + /// + event EventHandler? NotificationDismissed; + + /// + /// Event fired when a notification action is clicked + /// + event EventHandler? NotificationActionClicked; + + /// + /// Gets the notification history + /// + IReadOnlyList NotificationHistory { get; } + + /// + /// Shows a simple notification + /// + Task ShowNotificationAsync(string title, string message, NotificationType type = NotificationType.Information); + + /// + /// Shows a notification with custom settings + /// + Task ShowNotificationAsync(NotificationModel notification); + + /// + /// Shows a balloon tip notification + /// + Task ShowBalloonTipAsync(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000); + + /// + /// Shows a Windows toast notification (if available) + /// + Task ShowToastNotificationAsync(string title, string message, NotificationType type = NotificationType.Information); + + /// + /// Shows a notification for power plan changes + /// + Task ShowPowerPlanChangeNotificationAsync(string oldPlan, string newPlan, string processName = ""); + + /// + /// Shows a notification for process monitoring events + /// + Task ShowProcessMonitoringNotificationAsync(string message, bool isEnabled); + + /// + /// Shows a notification for CPU affinity changes + /// + Task ShowCpuAffinityNotificationAsync(string processName, string affinityInfo); + + /// + /// Shows an error notification + /// + Task ShowErrorNotificationAsync(string title, string message, Exception? exception = null); + + /// + /// Shows a success notification + /// + Task ShowSuccessNotificationAsync(string title, string message); + + /// + /// Dismisses a specific notification + /// + Task DismissNotificationAsync(string notificationId); + + /// + /// Dismisses all notifications + /// + Task DismissAllNotificationsAsync(); + + /// + /// Clears notification history + /// + Task ClearNotificationHistoryAsync(); + + /// + /// Gets unread notification count + /// + int GetUnreadNotificationCount(); + + /// + /// Marks all notifications as read + /// + Task MarkAllNotificationsAsReadAsync(); + + /// + /// Checks if notifications are enabled for the given type + /// + bool AreNotificationsEnabled(NotificationType type); + + /// + /// Updates notification settings + /// + void UpdateSettings(ApplicationSettingsModel settings); + + /// + /// Initializes the notification service + /// + Task InitializeAsync(); + + /// + /// Disposes the notification service + /// + void Dispose(); + } + + /// + /// Event args for notification events + /// + public class NotificationEventArgs : EventArgs + { + public NotificationModel Notification { get; } + + public NotificationEventArgs(NotificationModel notification) + { + Notification = notification; + } + } + + /// + /// Event args for notification action events + /// + public class NotificationActionEventArgs : EventArgs + { + public NotificationModel Notification { get; } + public string ActionCommand { get; } + + public NotificationActionEventArgs(NotificationModel notification, string actionCommand) + { + Notification = notification; + ActionCommand = actionCommand; + } + } +} diff --git a/Services/IPowerPlanService.cs b/Services/IPowerPlanService.cs index 4ddc90b..164e321 100644 --- a/Services/IPowerPlanService.cs +++ b/Services/IPowerPlanService.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using ThreadPilot.Models; @@ -6,10 +7,59 @@ namespace ThreadPilot.Services { public interface IPowerPlanService { + /// + /// Event fired when the active power plan changes + /// + event EventHandler? PowerPlanChanged; + Task> GetPowerPlansAsync(); Task> GetCustomPowerPlansAsync(); Task SetActivePowerPlan(PowerPlanModel powerPlan); Task GetActivePowerPlan(); Task ImportCustomPowerPlan(string filePath); + + /// + /// Sets the active power plan by GUID with duplicate change prevention + /// + Task SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true); + + /// + /// Gets the currently active power plan GUID + /// + Task GetActivePowerPlanGuidAsync(); + + /// + /// Checks if a power plan with the given GUID exists + /// + Task PowerPlanExistsAsync(string powerPlanGuid); + + /// + /// Gets a power plan by GUID + /// + Task GetPowerPlanByGuidAsync(string powerPlanGuid); + + /// + /// Validates that a power plan change is necessary + /// + Task IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid); + } + + /// + /// Event arguments for power plan changes + /// + public class PowerPlanChangedEventArgs : EventArgs + { + public PowerPlanModel? PreviousPowerPlan { get; } + public PowerPlanModel? NewPowerPlan { get; } + public DateTime Timestamp { get; } + public string? Reason { get; } + + public PowerPlanChangedEventArgs(PowerPlanModel? previousPowerPlan, PowerPlanModel? newPowerPlan, string? reason = null) + { + PreviousPowerPlan = previousPowerPlan; + NewPowerPlan = newPowerPlan; + Timestamp = DateTime.Now; + Reason = reason; + } } } \ No newline at end of file diff --git a/Services/IProcessMonitorManagerService.cs b/Services/IProcessMonitorManagerService.cs new file mode 100644 index 0000000..215567d --- /dev/null +++ b/Services/IProcessMonitorManagerService.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Main orchestration service for process monitoring and power plan management + /// + public interface IProcessMonitorManagerService : IDisposable + { + /// + /// Event fired when a process-triggered power plan change occurs + /// + event EventHandler? ProcessPowerPlanChanged; + + /// + /// Event fired when the service status changes + /// + event EventHandler? ServiceStatusChanged; + + /// + /// Gets whether the service is currently running + /// + bool IsRunning { get; } + + /// + /// Gets the current service status + /// + string Status { get; } + + /// + /// Gets currently running associated processes + /// + IEnumerable RunningAssociatedProcesses { get; } + + /// + /// Starts the process monitoring and power plan management service + /// + Task StartAsync(); + + /// + /// Stops the service + /// + Task StopAsync(); + + /// + /// Manually triggers a power plan evaluation for all running processes + /// + Task EvaluateCurrentProcessesAsync(); + + /// + /// Forces a return to the default power plan + /// + Task ForceDefaultPowerPlanAsync(); + + /// + /// Gets the current active power plan information + /// + Task GetCurrentActivePowerPlanAsync(); + + /// + /// Refreshes the configuration from the association service + /// + Task RefreshConfigurationAsync(); + + /// + /// Updates the service settings (polling intervals, etc.) + /// + void UpdateSettings(); + } + + /// + /// Event arguments for process-triggered power plan changes + /// + public class ProcessPowerPlanChangeEventArgs : EventArgs + { + public ProcessModel Process { get; } + public ProcessPowerPlanAssociation Association { get; } + public PowerPlanModel? PreviousPowerPlan { get; } + public PowerPlanModel? NewPowerPlan { get; } + public string Action { get; } // "ProcessStarted", "ProcessStopped", "DefaultRestored" + public DateTime Timestamp { get; } + + public ProcessPowerPlanChangeEventArgs( + ProcessModel process, + ProcessPowerPlanAssociation association, + PowerPlanModel? previousPowerPlan, + PowerPlanModel? newPowerPlan, + string action) + { + Process = process; + Association = association; + PreviousPowerPlan = previousPowerPlan; + NewPowerPlan = newPowerPlan; + Action = action; + Timestamp = DateTime.Now; + } + } + + /// + /// Event arguments for service status changes + /// + public class ServiceStatusEventArgs : EventArgs + { + public bool IsRunning { get; } + public string Status { get; } + public string? Details { get; } + public Exception? Error { get; } + public DateTime Timestamp { get; } + + public ServiceStatusEventArgs(bool isRunning, string status, string? details = null, Exception? error = null) + { + IsRunning = isRunning; + Status = status; + Details = details; + Error = error; + Timestamp = DateTime.Now; + } + } +} diff --git a/Services/IProcessMonitorService.cs b/Services/IProcessMonitorService.cs new file mode 100644 index 0000000..0582ac4 --- /dev/null +++ b/Services/IProcessMonitorService.cs @@ -0,0 +1,103 @@ +using System; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Interface for process monitoring service that uses WMI events with fallback polling + /// + public interface IProcessMonitorService : IDisposable + { + /// + /// Event fired when a process starts + /// + event EventHandler? ProcessStarted; + + /// + /// Event fired when a process stops + /// + event EventHandler? ProcessStopped; + + /// + /// Event fired when monitoring status changes + /// + event EventHandler? MonitoringStatusChanged; + + /// + /// Gets whether the service is currently monitoring + /// + bool IsMonitoring { get; } + + /// + /// Gets whether WMI monitoring is available and working + /// + bool IsWmiAvailable { get; } + + /// + /// Gets whether fallback polling is currently active + /// + bool IsFallbackPollingActive { get; } + + /// + /// Starts monitoring processes + /// + Task StartMonitoringAsync(); + + /// + /// Stops monitoring processes + /// + Task StopMonitoringAsync(); + + /// + /// Gets all currently running processes + /// + Task> GetRunningProcessesAsync(); + + /// + /// Checks if a specific process is currently running + /// + Task IsProcessRunningAsync(string executableName); + + /// + /// Updates the service settings (polling intervals, etc.) + /// + void UpdateSettings(); + } + + /// + /// Event arguments for process events + /// + public class ProcessEventArgs : EventArgs + { + public ProcessModel Process { get; } + public DateTime Timestamp { get; } + + public ProcessEventArgs(ProcessModel process) + { + Process = process; + Timestamp = DateTime.Now; + } + } + + /// + /// Event arguments for monitoring status changes + /// + public class MonitoringStatusEventArgs : EventArgs + { + public bool IsMonitoring { get; } + public bool IsWmiAvailable { get; } + public bool IsFallbackPollingActive { get; } + public string? StatusMessage { get; } + public Exception? Error { get; } + + public MonitoringStatusEventArgs(bool isMonitoring, bool isWmiAvailable, bool isFallbackPollingActive, string? statusMessage = null, Exception? error = null) + { + IsMonitoring = isMonitoring; + IsWmiAvailable = isWmiAvailable; + IsFallbackPollingActive = isFallbackPollingActive; + StatusMessage = statusMessage; + Error = error; + } + } +} diff --git a/Services/IProcessPowerPlanAssociationService.cs b/Services/IProcessPowerPlanAssociationService.cs new file mode 100644 index 0000000..eae126e --- /dev/null +++ b/Services/IProcessPowerPlanAssociationService.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Interface for managing process-power plan associations + /// + public interface IProcessPowerPlanAssociationService + { + /// + /// Event fired when configuration changes + /// + event EventHandler? ConfigurationChanged; + + /// + /// Gets the current configuration + /// + ProcessMonitorConfiguration Configuration { get; } + + /// + /// Loads configuration from persistent storage + /// + Task LoadConfigurationAsync(); + + /// + /// Saves configuration to persistent storage + /// + Task SaveConfigurationAsync(); + + /// + /// Gets all associations + /// + Task> GetAssociationsAsync(); + + /// + /// Gets enabled associations only + /// + Task> GetEnabledAssociationsAsync(); + + /// + /// Adds a new association + /// + Task AddAssociationAsync(ProcessPowerPlanAssociation association); + + /// + /// Updates an existing association + /// + Task UpdateAssociationAsync(ProcessPowerPlanAssociation association); + + /// + /// Removes an association + /// + Task RemoveAssociationAsync(string associationId); + + /// + /// Finds the best matching association for a process + /// + Task FindMatchingAssociationAsync(ProcessModel process); + + /// + /// Finds association by executable name + /// + Task FindAssociationByExecutableAsync(string executableName); + + /// + /// Sets the default power plan + /// + Task SetDefaultPowerPlanAsync(string powerPlanGuid, string powerPlanName); + + /// + /// Gets the default power plan + /// + Task<(string Guid, string Name)> GetDefaultPowerPlanAsync(); + + /// + /// Validates the current configuration + /// + Task> ValidateConfigurationAsync(); + + /// + /// Resets configuration to defaults + /// + Task ResetConfigurationAsync(); + + /// + /// Exports configuration to a file + /// + Task ExportConfigurationAsync(string filePath); + + /// + /// Imports configuration from a file + /// + Task ImportConfigurationAsync(string filePath); + } + + /// + /// Event arguments for configuration changes + /// + public class ConfigurationChangedEventArgs : EventArgs + { + public string ChangeType { get; } + public ProcessPowerPlanAssociation? Association { get; } + public string? Details { get; } + + public ConfigurationChangedEventArgs(string changeType, ProcessPowerPlanAssociation? association = null, string? details = null) + { + ChangeType = changeType; + Association = association; + Details = details; + } + } +} diff --git a/Services/IProcessService.cs b/Services/IProcessService.cs index 28277cb..4e6cc68 100644 --- a/Services/IProcessService.cs +++ b/Services/IProcessService.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Threading.Tasks; @@ -13,5 +14,30 @@ namespace ThreadPilot.Services Task SaveProcessProfile(string profileName, ProcessModel process); Task LoadProcessProfile(string profileName, ProcessModel process); Task RefreshProcessInfo(ProcessModel process); + + /// + /// Gets a process by its ID + /// + Task GetProcessByIdAsync(int processId); + + /// + /// Gets processes by executable name + /// + Task> GetProcessesByNameAsync(string executableName); + + /// + /// Checks if a process with the given name is currently running + /// + Task IsProcessRunningAsync(string executableName); + + /// + /// Gets all running processes with their executable paths + /// + Task> GetProcessesWithPathsAsync(); + + /// + /// Creates a ProcessModel from a System.Diagnostics.Process + /// + ProcessModel CreateProcessModel(Process process); } } \ No newline at end of file diff --git a/Services/ISystemTrayService.cs b/Services/ISystemTrayService.cs new file mode 100644 index 0000000..e7015da --- /dev/null +++ b/Services/ISystemTrayService.cs @@ -0,0 +1,117 @@ +using System; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing system tray functionality + /// + public interface ISystemTrayService : IDisposable + { + /// + /// Event fired when quick apply is requested from tray + /// + event EventHandler? QuickApplyRequested; + + /// + /// Event fired when show main window is requested from tray + /// + event EventHandler? ShowMainWindowRequested; + + /// + /// Event fired when exit is requested from tray + /// + event EventHandler? ExitRequested; + + /// + /// Event fired when monitoring enable/disable is requested from tray + /// + event EventHandler? MonitoringToggleRequested; + + /// + /// Event fired when settings are requested from tray + /// + event EventHandler? SettingsRequested; + + /// + /// Initializes the system tray icon + /// + void Initialize(); + + /// + /// Shows the system tray icon + /// + void Show(); + + /// + /// Hides the system tray icon + /// + void Hide(); + + /// + /// Updates the tray icon tooltip + /// + void UpdateTooltip(string tooltip); + + /// + /// Shows a balloon tip notification + /// + void ShowBalloonTip(string title, string text, int timeoutMs = 3000); + + /// + /// Updates the context menu with current process information + /// + void UpdateContextMenu(string? selectedProcessName = null, bool hasSelection = false); + + /// + /// Updates the monitoring status in the context menu + /// + void UpdateMonitoringStatus(bool isMonitoring, bool isWmiAvailable = true); + + /// + /// Updates the tray icon based on application state + /// + void UpdateTrayIcon(TrayIconState state); + + /// + /// Shows a notification through the tray icon + /// + void ShowTrayNotification(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000); + + /// + /// Updates settings for the tray service + /// + void UpdateSettings(ApplicationSettingsModel settings); + + /// + /// Updates the Game Boost status in the tray + /// + void UpdateGameBoostStatus(bool isGameBoostActive, string? currentGameName = null); + } + + /// + /// Event args for monitoring toggle events + /// + public class MonitoringToggleEventArgs : EventArgs + { + public bool EnableMonitoring { get; } + + public MonitoringToggleEventArgs(bool enableMonitoring) + { + EnableMonitoring = enableMonitoring; + } + } + + /// + /// Tray icon states + /// + public enum TrayIconState + { + Normal, + Monitoring, + Error, + Disabled, + GameBoost + } +} diff --git a/Services/LogFileManager.cs b/Services/LogFileManager.cs new file mode 100644 index 0000000..18234b2 --- /dev/null +++ b/Services/LogFileManager.cs @@ -0,0 +1,425 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace ThreadPilot.Services +{ + /// + /// Manages log file operations including rotation, cleanup, and concurrent access + /// + public class LogFileManager : IDisposable + { + private readonly ILogger _logger; + private readonly string _logDirectory; + private readonly SemaphoreSlim _fileLock = new(1, 1); + private readonly ReaderWriterLockSlim _configLock = new(); + private bool _disposed; + + // Configuration + private int _maxFileSizeMb = 10; + private int _retentionDays = 7; + private int _maxLogFiles = 50; + + public string LogDirectory => _logDirectory; + public string CurrentLogFilePath { get; private set; } + + public LogFileManager(ILogger logger, string? logDirectory = null) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + _logDirectory = logDirectory ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "ThreadPilot", + "Logs"); + + CurrentLogFilePath = Path.Combine(_logDirectory, "ThreadPilot.log"); + } + + /// + /// Initialize the log file manager + /// + public async Task InitializeAsync() + { + await _fileLock.WaitAsync(); + try + { + // Ensure log directory exists + Directory.CreateDirectory(_logDirectory); + + // Create current log file if it doesn't exist + if (!File.Exists(CurrentLogFilePath)) + { + await CreateNewLogFileAsync(); + } + + _logger.LogInformation("Log file manager initialized. Directory: {LogDirectory}", _logDirectory); + } + finally + { + _fileLock.Release(); + } + } + + /// + /// Write log entries to the current log file with automatic rotation + /// + public async Task WriteLogEntriesAsync(IEnumerable logLines) + { + await _fileLock.WaitAsync(); + try + { + // Check if rotation is needed + await CheckAndRotateLogFileAsync(); + + // Write entries + await File.AppendAllLinesAsync(CurrentLogFilePath, logLines); + } + finally + { + _fileLock.Release(); + } + } + + /// + /// Write a single log entry + /// + public async Task WriteLogEntryAsync(string logLine) + { + await WriteLogEntriesAsync(new[] { logLine }); + } + + /// + /// Read log entries from all log files within date range + /// + public async Task> ReadLogEntriesAsync(DateTime fromDate, DateTime toDate, int maxEntries = 1000) + { + await _fileLock.WaitAsync(); + try + { + var allEntries = new List<(DateTime timestamp, string line)>(); + var logFiles = GetLogFiles(); + + foreach (var logFile in logFiles) + { + var entries = await ReadLogEntriesFromFileAsync(logFile, fromDate, toDate); + allEntries.AddRange(entries); + } + + return allEntries + .OrderByDescending(e => e.timestamp) + .Take(maxEntries) + .Select(e => e.line) + .ToList(); + } + finally + { + _fileLock.Release(); + } + } + + /// + /// Get log file statistics + /// + public async Task GetStatisticsAsync() + { + await _fileLock.WaitAsync(); + try + { + var stats = new LogFileStatistics(); + var logFiles = GetLogFiles(); + + stats.TotalLogFiles = logFiles.Count; + + foreach (var logFile in logFiles) + { + var fileInfo = new FileInfo(logFile); + stats.TotalLogSizeBytes += fileInfo.Length; + + if (Path.GetFileName(logFile) == "ThreadPilot.log") + { + stats.CurrentFileSizeBytes = fileInfo.Length; + } + + if (stats.OldestLogDate == default || fileInfo.CreationTime < stats.OldestLogDate) + { + stats.OldestLogDate = fileInfo.CreationTime; + } + + if (fileInfo.CreationTime > stats.NewestLogDate) + { + stats.NewestLogDate = fileInfo.CreationTime; + } + } + + // Count log levels by reading recent entries + await CountLogLevelsAsync(stats); + + return stats; + } + finally + { + _fileLock.Release(); + } + } + + /// + /// Clean up old log files based on retention policy + /// + public async Task CleanupOldLogsAsync() + { + await _fileLock.WaitAsync(); + try + { + _configLock.EnterReadLock(); + var retentionDate = DateTime.UtcNow.AddDays(-_retentionDays); + var maxFiles = _maxLogFiles; + _configLock.ExitReadLock(); + + var logFiles = GetLogFiles() + .Where(f => Path.GetFileName(f) != "ThreadPilot.log") // Don't delete current log + .OrderBy(f => new FileInfo(f).CreationTime) + .ToList(); + + var deletedCount = 0; + + // Delete files older than retention period + foreach (var logFile in logFiles.ToList()) + { + var fileInfo = new FileInfo(logFile); + if (fileInfo.CreationTime < retentionDate) + { + try + { + File.Delete(logFile); + logFiles.Remove(logFile); + deletedCount++; + _logger.LogDebug("Deleted old log file: {LogFile}", logFile); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to delete old log file: {LogFile}", logFile); + } + } + } + + // Delete excess files if we have too many + if (logFiles.Count > maxFiles) + { + var excessFiles = logFiles.Take(logFiles.Count - maxFiles); + foreach (var logFile in excessFiles) + { + try + { + File.Delete(logFile); + deletedCount++; + _logger.LogDebug("Deleted excess log file: {LogFile}", logFile); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to delete excess log file: {LogFile}", logFile); + } + } + } + + if (deletedCount > 0) + { + _logger.LogInformation("Cleaned up {DeletedCount} old log files", deletedCount); + } + } + finally + { + _fileLock.Release(); + } + } + + /// + /// Export logs to a specified file + /// + public async Task ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null) + { + exportPath ??= Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + $"ThreadPilot_Logs_{DateTime.Now:yyyyMMdd_HHmmss}.txt"); + + var logEntries = await ReadLogEntriesAsync(fromDate, toDate, int.MaxValue); + + var exportContent = new List + { + $"# ThreadPilot Log Export", + $"# Export Date: {DateTime.Now:yyyy-MM-dd HH:mm:ss}", + $"# Date Range: {fromDate:yyyy-MM-dd} to {toDate:yyyy-MM-dd}", + $"# Total Entries: {logEntries.Count}", + "" + }; + + exportContent.AddRange(logEntries); + + await File.WriteAllLinesAsync(exportPath, exportContent); + return exportPath; + } + + /// + /// Update configuration + /// + public void UpdateConfiguration(int maxFileSizeMb, int retentionDays, int maxLogFiles = 50) + { + _configLock.EnterWriteLock(); + try + { + _maxFileSizeMb = maxFileSizeMb; + _retentionDays = retentionDays; + _maxLogFiles = maxLogFiles; + } + finally + { + _configLock.ExitWriteLock(); + } + } + + private async Task CheckAndRotateLogFileAsync() + { + var fileInfo = new FileInfo(CurrentLogFilePath); + + _configLock.EnterReadLock(); + var maxSizeBytes = _maxFileSizeMb * 1024 * 1024; + _configLock.ExitReadLock(); + + if (fileInfo.Exists && fileInfo.Length > maxSizeBytes) + { + await RotateLogFileAsync(); + } + } + + private async Task RotateLogFileAsync() + { + var timestamp = DateTime.UtcNow.ToString("yyyyMMdd_HHmmss"); + var rotatedPath = Path.Combine(_logDirectory, $"ThreadPilot_{timestamp}.log"); + + try + { + // Move current log to rotated name + File.Move(CurrentLogFilePath, rotatedPath); + + // Create new current log file + await CreateNewLogFileAsync(); + + _logger.LogInformation("Log file rotated: {RotatedPath}", rotatedPath); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to rotate log file"); + throw; + } + } + + private async Task CreateNewLogFileAsync() + { + var header = new[] + { + $"# ThreadPilot Log File", + $"# Created: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC", + $"# Version: {System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}", + $"# Machine: {Environment.MachineName}", + "" + }; + + await File.WriteAllLinesAsync(CurrentLogFilePath, header); + } + + private List GetLogFiles() + { + return Directory.GetFiles(_logDirectory, "*.log") + .OrderByDescending(f => new FileInfo(f).CreationTime) + .ToList(); + } + + private async Task> ReadLogEntriesFromFileAsync(string filePath, DateTime fromDate, DateTime toDate) + { + var entries = new List<(DateTime timestamp, string line)>(); + + try + { + var lines = await File.ReadAllLinesAsync(filePath); + foreach (var line in lines) + { + if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line)) continue; + + // Try to extract timestamp from JSON log entry + if (TryExtractTimestamp(line, out var timestamp)) + { + if (timestamp >= fromDate && timestamp <= toDate) + { + entries.Add((timestamp, line)); + } + } + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to read log entries from file: {FilePath}", filePath); + } + + return entries; + } + + private bool TryExtractTimestamp(string logLine, out DateTime timestamp) + { + timestamp = default; + + try + { + // Look for timestamp in JSON format: "timestamp":"2024-01-01 12:00:00.000" + var timestampStart = logLine.IndexOf("\"timestamp\":\""); + if (timestampStart >= 0) + { + timestampStart += 13; // Length of "timestamp":"" + var timestampEnd = logLine.IndexOf("\"", timestampStart); + if (timestampEnd > timestampStart) + { + var timestampStr = logLine.Substring(timestampStart, timestampEnd - timestampStart); + return DateTime.TryParse(timestampStr, out timestamp); + } + } + } + catch + { + // Ignore parsing errors + } + + return false; + } + + private async Task CountLogLevelsAsync(LogFileStatistics stats) + { + try + { + // Read recent entries to count log levels + var recentEntries = await ReadLogEntriesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, 1000); + + foreach (var entry in recentEntries) + { + if (entry.Contains("\"level\":\"Error\"")) stats.ErrorCount++; + else if (entry.Contains("\"level\":\"Warning\"")) stats.WarningCount++; + else if (entry.Contains("\"level\":\"Information\"")) stats.InfoCount++; + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to count log levels"); + } + } + + public void Dispose() + { + if (_disposed) return; + + _fileLock?.Dispose(); + _configLock?.Dispose(); + _disposed = true; + } + } +} diff --git a/Services/NotificationService.cs b/Services/NotificationService.cs new file mode 100644 index 0000000..b353800 --- /dev/null +++ b/Services/NotificationService.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing notifications with balloon tips and toast support + /// + public class NotificationService : INotificationService, IDisposable + { + private readonly ILogger _logger; + private readonly IApplicationSettingsService _settingsService; + private readonly ISystemTrayService _systemTrayService; + private readonly List _notificationHistory; + private ApplicationSettingsModel _settings; + private bool _disposed = false; + + public event EventHandler? NotificationShown; + public event EventHandler? NotificationDismissed; + public event EventHandler? NotificationActionClicked; + + public IReadOnlyList NotificationHistory => _notificationHistory.AsReadOnly(); + + public NotificationService( + ILogger logger, + IApplicationSettingsService settingsService, + ISystemTrayService systemTrayService) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _systemTrayService = systemTrayService ?? throw new ArgumentNullException(nameof(systemTrayService)); + + _notificationHistory = new List(); + _settings = _settingsService.Settings; + + // Subscribe to settings changes + _settingsService.SettingsChanged += OnSettingsChanged; + } + + public async Task InitializeAsync() + { + try + { + _logger.LogInformation("Initializing notification service"); + + // Load settings + _settings = _settingsService.Settings; + + _logger.LogInformation("Notification service initialized successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize notification service"); + throw; + } + } + + public async Task ShowNotificationAsync(string title, string message, NotificationType type = NotificationType.Information) + { + var notification = new NotificationModel(title, message, type) + { + DurationMs = _settings.NotificationDisplayDurationMs, + Category = "General", + SourceService = "NotificationService" + }; + + await ShowNotificationAsync(notification); + } + + public async Task ShowNotificationAsync(NotificationModel notification) + { + if (notification == null) return; + + try + { + // Check if notifications are enabled + if (!AreNotificationsEnabled(notification.Type)) + { + _logger.LogDebug("Notifications disabled for type {Type}", notification.Type); + return; + } + + // Add to history + AddToHistory(notification); + + // Show balloon tip if enabled + if (_settings.EnableBalloonNotifications) + { + await ShowBalloonTipInternalAsync(notification); + } + + // Show toast notification if enabled and available + if (_settings.EnableToastNotifications) + { + await ShowToastNotificationInternalAsync(notification); + } + + // Fire event + NotificationShown?.Invoke(this, new NotificationEventArgs(notification)); + + _logger.LogDebug("Notification shown: {Title}", notification.Title); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error showing notification: {Title}", notification.Title); + } + } + + public async Task ShowBalloonTipAsync(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000) + { + var notification = new NotificationModel(title, message, type) + { + DurationMs = timeoutMs, + Category = "BalloonTip", + SourceService = "NotificationService" + }; + + if (_settings.EnableBalloonNotifications && AreNotificationsEnabled(type)) + { + AddToHistory(notification); + await ShowBalloonTipInternalAsync(notification); + NotificationShown?.Invoke(this, new NotificationEventArgs(notification)); + } + } + + public async Task ShowToastNotificationAsync(string title, string message, NotificationType type = NotificationType.Information) + { + var notification = new NotificationModel(title, message, type) + { + Category = "Toast", + SourceService = "NotificationService" + }; + + if (_settings.EnableToastNotifications && AreNotificationsEnabled(type)) + { + AddToHistory(notification); + await ShowToastNotificationInternalAsync(notification); + NotificationShown?.Invoke(this, new NotificationEventArgs(notification)); + } + } + + public async Task ShowPowerPlanChangeNotificationAsync(string oldPlan, string newPlan, string processName = "") + { + if (!_settings.EnablePowerPlanChangeNotifications) return; + + var message = string.IsNullOrEmpty(processName) + ? $"Power plan changed from '{oldPlan}' to '{newPlan}'" + : $"Power plan changed to '{newPlan}' for process '{processName}'"; + + var notification = new NotificationModel("Power Plan Changed", message, NotificationType.PowerPlanChange) + { + Category = "PowerPlan", + SourceService = "PowerPlanService", + Priority = NotificationPriority.Normal + }; + + await ShowNotificationAsync(notification); + } + + public async Task ShowProcessMonitoringNotificationAsync(string message, bool isEnabled) + { + if (!_settings.EnableProcessMonitoringNotifications) return; + + var title = isEnabled ? "Process Monitoring Enabled" : "Process Monitoring Disabled"; + var type = isEnabled ? NotificationType.Success : NotificationType.Warning; + + var notification = new NotificationModel(title, message, type) + { + Category = "ProcessMonitoring", + SourceService = "ProcessMonitorService", + Priority = NotificationPriority.Normal + }; + + await ShowNotificationAsync(notification); + } + + public async Task ShowCpuAffinityNotificationAsync(string processName, string affinityInfo) + { + var notification = new NotificationModel( + "CPU Affinity Applied", + $"CPU affinity set for '{processName}': {affinityInfo}", + NotificationType.CpuAffinity) + { + Category = "CpuAffinity", + SourceService = "ProcessService", + Priority = NotificationPriority.Normal + }; + + await ShowNotificationAsync(notification); + } + + public async Task ShowErrorNotificationAsync(string title, string message, Exception? exception = null) + { + if (!_settings.EnableErrorNotifications) return; + + var fullMessage = exception != null ? $"{message}\n\nError: {exception.Message}" : message; + + var notification = new NotificationModel(title, fullMessage, NotificationType.Error) + { + Category = "Error", + SourceService = "System", + Priority = NotificationPriority.High, + IsPersistent = true + }; + + await ShowNotificationAsync(notification); + } + + public async Task ShowSuccessNotificationAsync(string title, string message) + { + if (!_settings.EnableSuccessNotifications) return; + + var notification = new NotificationModel(title, message, NotificationType.Success) + { + Category = "Success", + SourceService = "System", + Priority = NotificationPriority.Normal + }; + + await ShowNotificationAsync(notification); + } + + public async Task DismissNotificationAsync(string notificationId) + { + var notification = _notificationHistory.FirstOrDefault(n => n.Id == notificationId); + if (notification != null) + { + NotificationDismissed?.Invoke(this, new NotificationEventArgs(notification)); + _logger.LogDebug("Notification dismissed: {Id}", notificationId); + } + await Task.CompletedTask; + } + + public async Task DismissAllNotificationsAsync() + { + foreach (var notification in _notificationHistory.ToList()) + { + NotificationDismissed?.Invoke(this, new NotificationEventArgs(notification)); + } + _logger.LogDebug("All notifications dismissed"); + await Task.CompletedTask; + } + + public async Task ClearNotificationHistoryAsync() + { + _notificationHistory.Clear(); + _logger.LogInformation("Notification history cleared"); + await Task.CompletedTask; + } + + public int GetUnreadNotificationCount() + { + return _notificationHistory.Count(n => !n.IsRead); + } + + public async Task MarkAllNotificationsAsReadAsync() + { + foreach (var notification in _notificationHistory) + { + notification.MarkAsRead(); + } + _logger.LogDebug("All notifications marked as read"); + await Task.CompletedTask; + } + + public bool AreNotificationsEnabled(NotificationType type) + { + if (!_settings.EnableNotifications) return false; + + return type switch + { + NotificationType.PowerPlanChange => _settings.EnablePowerPlanChangeNotifications, + NotificationType.ProcessMonitoring => _settings.EnableProcessMonitoringNotifications, + NotificationType.Error => _settings.EnableErrorNotifications, + NotificationType.Success => _settings.EnableSuccessNotifications, + _ => true + }; + } + + public void UpdateSettings(ApplicationSettingsModel settings) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _logger.LogDebug("Notification settings updated"); + } + + private void AddToHistory(NotificationModel notification) + { + if (!_settings.EnableNotificationHistory) return; + + _notificationHistory.Insert(0, notification); + + // Trim history if it exceeds max items + while (_notificationHistory.Count > _settings.MaxNotificationHistoryItems) + { + _notificationHistory.RemoveAt(_notificationHistory.Count - 1); + } + } + + private async Task ShowBalloonTipInternalAsync(NotificationModel notification) + { + try + { + // Use the system tray service to show the actual balloon tip + _systemTrayService.ShowTrayNotification( + notification.Title, + notification.Message, + notification.Type, + notification.DurationMs); + + _logger.LogDebug("Balloon tip shown via system tray: {Title} - {Message}", notification.Title, notification.Message); + await Task.CompletedTask; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error showing balloon tip"); + } + } + + private async Task ShowToastNotificationInternalAsync(NotificationModel notification) + { + try + { + // Toast notifications would require Windows 10+ and additional setup + // For now, we'll just log it + _logger.LogDebug("Toast notification: {Title} - {Message}", notification.Title, notification.Message); + await Task.CompletedTask; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error showing toast notification"); + } + } + + private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e) + { + UpdateSettings(e.NewSettings); + } + + public void Dispose() + { + if (_disposed) return; + + try + { + _settingsService.SettingsChanged -= OnSettingsChanged; + _disposed = true; + _logger.LogInformation("Notification service disposed"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error disposing notification service"); + } + } + } +} diff --git a/Services/PowerPlanService.cs b/Services/PowerPlanService.cs index ae7c40b..61bea6a 100644 --- a/Services/PowerPlanService.cs +++ b/Services/PowerPlanService.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using ThreadPilot.Models; namespace ThreadPilot.Services @@ -12,6 +13,18 @@ namespace ThreadPilot.Services public class PowerPlanService : IPowerPlanService { private const string PowerPlansPath = @"C:\Users\Administrator\Desktop\Project\ThreadPilot_1\Powerplans"; + private readonly object _lockObject = new(); + private readonly ILogger _logger; + private readonly IEnhancedLoggingService _enhancedLogger; + private string? _lastActivePowerPlanGuid; + + public event EventHandler? PowerPlanChanged; + + public PowerPlanService(ILogger logger, IEnhancedLoggingService enhancedLogger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger)); + } public async Task> GetPowerPlansAsync() { @@ -83,16 +96,43 @@ namespace ThreadPilot.Services public async Task SetActivePowerPlan(PowerPlanModel powerPlan) { - return await Task.Run(() => + return await SetActivePowerPlanByGuidAsync(powerPlan.Guid, false); + } + + public async Task SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true) + { + return await Task.Run(async () => { try { + // Check if change is needed when duplicate prevention is enabled + if (preventDuplicateChanges) + { + var isChangeNeeded = await IsPowerPlanChangeNeededAsync(powerPlanGuid); + if (!isChangeNeeded) + { + _logger.LogDebug("Power plan change skipped - already active: {PowerPlanGuid}", powerPlanGuid); + return true; // No change needed, consider it successful + } + } + + var previousPowerPlan = await GetActivePowerPlan(); + var targetPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid); + + _logger.LogInformation("Attempting to change power plan from '{FromPlan}' to '{ToPlan}'", + previousPowerPlan?.Name ?? "Unknown", targetPowerPlan?.Name ?? "Unknown"); + + await _enhancedLogger.LogPowerPlanChangeAsync( + previousPowerPlan?.Name ?? "Unknown", + targetPowerPlan?.Name ?? "Unknown", + "Manual power plan change requested"); + var process = new Process { StartInfo = new ProcessStartInfo { FileName = "powercfg", - Arguments = $"/setactive {powerPlan.Guid}", + Arguments = $"/setactive {powerPlanGuid}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, @@ -103,10 +143,50 @@ namespace ThreadPilot.Services process.Start(); process.WaitForExit(); - return process.ExitCode == 0; + var success = process.ExitCode == 0; + + if (success) + { + lock (_lockObject) + { + _lastActivePowerPlanGuid = powerPlanGuid; + } + + var newPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid); + + _logger.LogInformation("Power plan successfully changed to '{PowerPlan}'", newPowerPlan?.Name ?? "Unknown"); + + await _enhancedLogger.LogPowerPlanChangeAsync( + previousPowerPlan?.Name ?? "Unknown", + newPowerPlan?.Name ?? "Unknown", + "Manual power plan change completed"); + + PowerPlanChanged?.Invoke(this, new PowerPlanChangedEventArgs( + previousPowerPlan, newPowerPlan, "Manual power plan change")); + } + else + { + _logger.LogWarning("Failed to change power plan to '{PowerPlanGuid}' - powercfg exit code: {ExitCode}", + powerPlanGuid, process.ExitCode); + + await _enhancedLogger.LogSystemEventAsync(LogEventTypes.PowerPlan.ChangeFailed, + $"Failed to change power plan to '{targetPowerPlan?.Name ?? powerPlanGuid}' - Exit code: {process.ExitCode}", + Microsoft.Extensions.Logging.LogLevel.Warning); + } + + return success; } - catch (Exception) + catch (Exception ex) { + _logger.LogError(ex, "Exception occurred while changing power plan to '{PowerPlanGuid}'", powerPlanGuid); + + await _enhancedLogger.LogErrorAsync(ex, "PowerPlanService.SetActivePowerPlanByGuidAsync", + new Dictionary + { + ["PowerPlanGuid"] = powerPlanGuid, + ["PreventDuplicateChanges"] = preventDuplicateChanges + }); + return false; } }); @@ -186,5 +266,52 @@ namespace ThreadPilot.Services } }); } + + public async Task GetActivePowerPlanGuidAsync() + { + var activePlan = await GetActivePowerPlan(); + return activePlan?.Guid; + } + + public async Task PowerPlanExistsAsync(string powerPlanGuid) + { + var powerPlans = await GetPowerPlansAsync(); + return powerPlans.Any(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase)); + } + + public async Task GetPowerPlanByGuidAsync(string powerPlanGuid) + { + var powerPlans = await GetPowerPlansAsync(); + return powerPlans.FirstOrDefault(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase)); + } + + public async Task IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid) + { + try + { + var currentGuid = await GetActivePowerPlanGuidAsync(); + + // Check if the target power plan is already active + if (string.Equals(currentGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase)) + { + return false; // No change needed + } + + // Check if we recently set this power plan (to prevent rapid switching) + lock (_lockObject) + { + if (string.Equals(_lastActivePowerPlanGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase)) + { + return false; // We recently set this plan + } + } + + return true; // Change is needed + } + catch + { + return true; // If we can't determine, assume change is needed + } + } } } \ No newline at end of file diff --git a/Services/ProcessManagement/IProcessManagementService.cs b/Services/ProcessManagement/IProcessManagementService.cs new file mode 100644 index 0000000..294b7b1 --- /dev/null +++ b/Services/ProcessManagement/IProcessManagementService.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services.ProcessManagement +{ + /// + /// Unified interface for process management operations + /// + public interface IProcessManagementService + { + /// + /// Event fired when a process starts + /// + event EventHandler? ProcessStarted; + + /// + /// Event fired when a process stops + /// + event EventHandler? ProcessStopped; + + /// + /// Event fired when process monitoring status changes + /// + event EventHandler? MonitoringStatusChanged; + + /// + /// Gets whether process monitoring is currently active + /// + bool IsMonitoringActive { get; } + + /// + /// Gets all currently running processes + /// + Task> GetRunningProcessesAsync(); + + /// + /// Gets a specific process by ID + /// + Task GetProcessByIdAsync(int processId); + + /// + /// Gets processes by executable name + /// + Task> GetProcessesByNameAsync(string executableName); + + /// + /// Start monitoring for process events + /// + Task StartMonitoringAsync(); + + /// + /// Stop monitoring for process events + /// + Task StopMonitoringAsync(); + + /// + /// Set processor affinity for a process + /// + Task SetProcessorAffinityAsync(ProcessModel process, long affinityMask); + + /// + /// Set priority for a process + /// + Task SetProcessPriorityAsync(ProcessModel process, ProcessPriorityClass priority); + + /// + /// Refresh process information + /// + Task RefreshProcessInfoAsync(ProcessModel process); + } + + /// + /// Event args for process events + /// + public class ProcessEventArgs : EventArgs + { + public ProcessModel Process { get; } + public DateTime Timestamp { get; } + + public ProcessEventArgs(ProcessModel process) + { + Process = process ?? throw new ArgumentNullException(nameof(process)); + Timestamp = DateTime.Now; + } + } + + /// + /// Event args for monitoring status changes + /// + public class MonitoringStatusChangedEventArgs : EventArgs + { + public bool IsActive { get; } + public string? Reason { get; } + + public MonitoringStatusChangedEventArgs(bool isActive, string? reason = null) + { + IsActive = isActive; + Reason = reason; + } + } +} diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs new file mode 100644 index 0000000..e434714 --- /dev/null +++ b/Services/ProcessMonitorManagerService.cs @@ -0,0 +1,495 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Main orchestration service that coordinates process monitoring and power plan management + /// + public class ProcessMonitorManagerService : IProcessMonitorManagerService + { + private readonly IProcessMonitorService _processMonitorService; + private readonly IProcessPowerPlanAssociationService _associationService; + private readonly IPowerPlanService _powerPlanService; + private readonly IGameBoostService _gameBoostService; + private readonly INotificationService _notificationService; + private readonly IApplicationSettingsService _settingsService; + private readonly ILogger _logger; + private readonly IEnhancedLoggingService _enhancedLogger; + private readonly object _lockObject = new(); + + private readonly ConcurrentDictionary _runningAssociatedProcesses = new(); + private readonly System.Threading.Timer _delayTimer; + private readonly SemaphoreSlim _powerPlanChangeSemaphore = new(1, 1); + + private bool _isRunning; + private string _status = "Stopped"; + private bool _disposed; + private ProcessMonitorConfiguration? _configuration; + + public event EventHandler? ProcessPowerPlanChanged; + public event EventHandler? ServiceStatusChanged; + + public bool IsRunning => _isRunning; + public string Status => _status; + public IEnumerable RunningAssociatedProcesses => _runningAssociatedProcesses.Values.ToList(); + + public ProcessMonitorManagerService( + IProcessMonitorService processMonitorService, + IProcessPowerPlanAssociationService associationService, + IPowerPlanService powerPlanService, + IGameBoostService gameBoostService, + INotificationService notificationService, + IApplicationSettingsService settingsService, + ILogger logger, + IEnhancedLoggingService enhancedLogger) + { + _processMonitorService = processMonitorService ?? throw new ArgumentNullException(nameof(processMonitorService)); + _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); + _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _gameBoostService = gameBoostService ?? throw new ArgumentNullException(nameof(gameBoostService)); + _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger)); + + // Initialize delay timer (used for delayed power plan changes) + _delayTimer = new System.Threading.Timer(DelayedPowerPlanChangeCallback, null, Timeout.Infinite, Timeout.Infinite); + + // Subscribe to events + _processMonitorService.ProcessStarted += OnProcessStarted; + _processMonitorService.ProcessStopped += OnProcessStopped; + _processMonitorService.MonitoringStatusChanged += OnMonitoringStatusChanged; + _associationService.ConfigurationChanged += OnConfigurationChanged; + } + + public async Task StartAsync() + { + if (_disposed) throw new ObjectDisposedException(nameof(ProcessMonitorManagerService)); + + if (_isRunning) return; + + try + { + _logger.LogInformation("Starting Process Monitor Manager Service"); + await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, + "Process Monitor Manager Service starting"); + SetStatus(true, "Starting..."); + + // Load configuration + await _associationService.LoadConfigurationAsync(); + _configuration = _associationService.Configuration; + _logger.LogInformation("Configuration loaded with {AssociationCount} associations", + _configuration.Associations.Count); + + await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ConfigurationLoaded, + $"Process monitoring configuration loaded with {_configuration.Associations.Count} associations"); + + // Start process monitoring + await _processMonitorService.StartMonitoringAsync(); + _logger.LogInformation("Process monitoring started"); + + await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.MonitoringStarted, + "ProcessMonitorService", 0, "WMI-based process monitoring started"); + + // Evaluate current processes + await EvaluateCurrentProcessesAsync(); + + _isRunning = true; + SetStatus(true, "Running"); + _logger.LogInformation("Process Monitor Manager Service started successfully"); + + await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, + "Process Monitor Manager Service started successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to start Process Monitor Manager Service"); + await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.StartAsync", + new Dictionary { ["ServiceName"] = "ProcessMonitorManagerService" }); + _isRunning = false; + SetStatus(false, "Failed to start", $"Error: {ex.Message}", ex); + throw; + } + } + + public async Task StopAsync() + { + if (!_isRunning) return; + + try + { + SetStatus(false, "Stopping..."); + + // Stop process monitoring + await _processMonitorService.StopMonitoringAsync(); + + // Clear running processes + _runningAssociatedProcesses.Clear(); + + // Restore default power plan if configured + if (_configuration?.DefaultPowerPlanGuid != null) + { + await ForceDefaultPowerPlanAsync(); + } + + _isRunning = false; + SetStatus(false, "Stopped"); + } + catch (Exception ex) + { + SetStatus(false, "Error stopping", $"Error: {ex.Message}", ex); + throw; + } + } + + public async Task EvaluateCurrentProcessesAsync() + { + if (!_isRunning || _configuration == null) return; + + try + { + var currentProcesses = await _processMonitorService.GetRunningProcessesAsync(); + var associatedProcesses = new List(); + + // Find all currently running processes that have associations + foreach (var process in currentProcesses) + { + var association = _configuration.FindMatchingAssociation(process); + if (association != null) + { + associatedProcesses.Add(process); + _runningAssociatedProcesses.TryAdd(process.ProcessId, process); + } + } + + // Determine which power plan should be active + await DeterminePowerPlanAsync(associatedProcesses); + } + catch (Exception ex) + { + SetStatus(_isRunning, "Error evaluating processes", $"Error: {ex.Message}", ex); + } + } + + public async Task ForceDefaultPowerPlanAsync() + { + if (_configuration?.DefaultPowerPlanGuid == null) return; + + try + { + await _powerPlanChangeSemaphore.WaitAsync(); + + var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); + var success = await _powerPlanService.SetActivePowerPlanByGuidAsync( + _configuration.DefaultPowerPlanGuid, + _configuration.PreventDuplicatePowerPlanChanges); + + if (success) + { + var newPowerPlan = await _powerPlanService.GetPowerPlanByGuidAsync(_configuration.DefaultPowerPlanGuid); + // Note: We don't have a specific process for this event, so we'll use a dummy one + var dummyProcess = new ProcessModel { Name = "System", ProcessId = -1 }; + var dummyAssociation = new ProcessPowerPlanAssociation("System", _configuration.DefaultPowerPlanGuid, _configuration.DefaultPowerPlanName); + + ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( + dummyProcess, dummyAssociation, currentPowerPlan, newPowerPlan, "DefaultRestored")); + + // Show notification for default power plan restoration + await _notificationService.ShowPowerPlanChangeNotificationAsync( + currentPowerPlan?.Name ?? "Unknown", + newPowerPlan?.Name ?? _configuration.DefaultPowerPlanName, + ""); + } + } + catch (Exception ex) + { + SetStatus(_isRunning, "Error setting default power plan", $"Error: {ex.Message}", ex); + } + finally + { + _powerPlanChangeSemaphore.Release(); + } + } + + public async Task GetCurrentActivePowerPlanAsync() + { + return await _powerPlanService.GetActivePowerPlan(); + } + + public async Task RefreshConfigurationAsync() + { + await _associationService.LoadConfigurationAsync(); + _configuration = _associationService.Configuration; + + if (_isRunning) + { + await EvaluateCurrentProcessesAsync(); + } + } + + private async void OnProcessStarted(object? sender, ProcessEventArgs e) + { + if (!_isRunning || _configuration == null) return; + + try + { + await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.Started, + e.Process.Name, e.Process.ProcessId, "Process started and detected by monitoring"); + + // Check for Game Boost first + await CheckForGameBoostAsync(e.Process); + + var association = _configuration.FindMatchingAssociation(e.Process); + if (association != null) + { + _runningAssociatedProcesses.TryAdd(e.Process.ProcessId, e.Process); + + await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.AssociationTriggered, + e.Process.Name, e.Process.ProcessId, + $"Process matched association for power plan: {association.PowerPlanName}"); + + // Schedule power plan change with delay if configured + if (_configuration.PowerPlanChangeDelayMs > 0) + { + _delayTimer.Change(_configuration.PowerPlanChangeDelayMs, Timeout.Infinite); + + await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ConfigurationLoaded, + $"Power plan change scheduled with {_configuration.PowerPlanChangeDelayMs}ms delay for process {e.Process.Name}"); + } + else + { + await ChangePowerPlanForProcess(e.Process, association, "ProcessStarted"); + } + } + } + catch (Exception ex) + { + await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.OnProcessStarted", + new Dictionary + { + ["ProcessName"] = e.Process.Name, + ["ProcessId"] = e.Process.ProcessId + }); + SetStatus(_isRunning, "Error handling process start", $"Error: {ex.Message}", ex); + } + } + + private async void OnProcessStopped(object? sender, ProcessEventArgs e) + { + if (!_isRunning || _configuration == null) return; + + try + { + // Check if this was a game process and deactivate Game Boost if needed + await CheckForGameBoostDeactivationAsync(e.Process); + + if (_runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out var removedProcess)) + { + // Check if there are any other associated processes still running + var remainingProcesses = _runningAssociatedProcesses.Values.ToList(); + await DeterminePowerPlanAsync(remainingProcesses); + } + } + catch (Exception ex) + { + SetStatus(_isRunning, "Error handling process stop", $"Error: {ex.Message}", ex); + } + } + + private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e) + { + var details = e.StatusMessage ?? (e.IsMonitoring ? "Monitoring active" : "Monitoring inactive"); + SetStatus(_isRunning, $"Monitor: {details}", e.StatusMessage, e.Error); + } + + private void OnConfigurationChanged(object? sender, ConfigurationChangedEventArgs e) + { + _configuration = _associationService.Configuration; + + if (_isRunning) + { + Task.Run(async () => await EvaluateCurrentProcessesAsync()); + } + } + + private async void DelayedPowerPlanChangeCallback(object? state) + { + if (!_isRunning) return; + + var runningProcesses = _runningAssociatedProcesses.Values.ToList(); + await DeterminePowerPlanAsync(runningProcesses); + } + + private async Task DeterminePowerPlanAsync(IList associatedProcesses) + { + if (_configuration == null) return; + + try + { + if (associatedProcesses.Any()) + { + // Find the highest priority association among running processes + var associations = associatedProcesses + .Select(p => _configuration.FindMatchingAssociation(p)) + .Where(a => a != null) + .OrderByDescending(a => a!.Priority) + .ToList(); + + if (associations.Any()) + { + var topAssociation = associations.First()!; + var matchingProcess = associatedProcesses.First(p => topAssociation.MatchesProcess(p)); + await ChangePowerPlanForProcess(matchingProcess, topAssociation, "ProcessStarted"); + } + } + else + { + // No associated processes running, revert to default + if (!string.IsNullOrEmpty(_configuration.DefaultPowerPlanGuid)) + { + await ForceDefaultPowerPlanAsync(); + } + } + } + catch (Exception ex) + { + SetStatus(_isRunning, "Error determining power plan", $"Error: {ex.Message}", ex); + } + } + + private async Task ChangePowerPlanForProcess(ProcessModel process, ProcessPowerPlanAssociation association, string action) + { + try + { + await _powerPlanChangeSemaphore.WaitAsync(); + + var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); + var success = await _powerPlanService.SetActivePowerPlanByGuidAsync( + association.PowerPlanGuid, + _configuration?.PreventDuplicatePowerPlanChanges ?? true); + + if (success) + { + var newPowerPlan = await _powerPlanService.GetPowerPlanByGuidAsync(association.PowerPlanGuid); + ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( + process, association, currentPowerPlan, newPowerPlan, action)); + + // Show notification for power plan change + await _notificationService.ShowPowerPlanChangeNotificationAsync( + currentPowerPlan?.Name ?? "Unknown", + newPowerPlan?.Name ?? association.PowerPlanName, + process.Name); + } + } + catch (Exception ex) + { + SetStatus(_isRunning, "Error changing power plan", $"Error: {ex.Message}", ex); + } + finally + { + _powerPlanChangeSemaphore.Release(); + } + } + + private void SetStatus(bool isRunning, string status, string? details = null, Exception? error = null) + { + lock (_lockObject) + { + _status = status; + } + + ServiceStatusChanged?.Invoke(this, new ServiceStatusEventArgs(isRunning, status, details, error)); + + // Show error notification if there's an error + if (error != null) + { + Task.Run(async () => + { + try + { + await _notificationService.ShowErrorNotificationAsync( + "Process Monitor Error", + details ?? status, + error); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to show error notification"); + } + }); + } + } + + /// + /// Checks if a process is a game and activates Game Boost if enabled + /// + private async Task CheckForGameBoostAsync(ProcessModel process) + { + try + { + if (_gameBoostService.IsGameProcess(process)) + { + _logger.LogInformation("Game detected: {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); + + // Activate Game Boost if enabled and not already active for this process + if (!_gameBoostService.IsGameBoostActive || _gameBoostService.CurrentGameProcess?.ProcessId != process.ProcessId) + { + await _gameBoostService.ActivateGameBoostAsync(process); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error checking for Game Boost activation for process {ProcessName}", process.Name); + } + } + + /// + /// Checks if a stopped process was the current game and deactivates Game Boost if needed + /// + private async Task CheckForGameBoostDeactivationAsync(ProcessModel process) + { + try + { + if (_gameBoostService.IsGameBoostActive && + _gameBoostService.CurrentGameProcess?.ProcessId == process.ProcessId) + { + _logger.LogInformation("Game process stopped: {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); + await _gameBoostService.DeactivateGameBoostAsync(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error checking for Game Boost deactivation for process {ProcessName}", process.Name); + } + } + + public void UpdateSettings() + { + // Update the process monitor service with new settings + _processMonitorService.UpdateSettings(); + + _logger.LogDebug("ProcessMonitorManagerService settings updated"); + } + + public void Dispose() + { + if (_disposed) return; + + StopAsync().Wait(5000); // Wait up to 5 seconds for clean shutdown + + _delayTimer?.Dispose(); + _powerPlanChangeSemaphore?.Dispose(); + _processMonitorService?.Dispose(); + + _disposed = true; + } + } +} diff --git a/Services/ProcessMonitorService.cs b/Services/ProcessMonitorService.cs new file mode 100644 index 0000000..59b0962 --- /dev/null +++ b/Services/ProcessMonitorService.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Management; +using System.Threading; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Process monitoring service using WMI events with fallback polling + /// + public class ProcessMonitorService : IProcessMonitorService + { + private readonly IProcessService _processService; + private readonly IApplicationSettingsService _settingsService; + private readonly object _lockObject = new(); + private readonly ConcurrentDictionary _runningProcesses = new(); + + private ManagementEventWatcher? _processStartWatcher; + private ManagementEventWatcher? _processStopWatcher; + private System.Threading.Timer? _fallbackTimer; + private CancellationTokenSource? _cancellationTokenSource; + + private bool _isMonitoring; + private bool _isWmiAvailable; + private bool _isFallbackPollingActive; + private bool _disposed; + + // Configuration - will be updated from settings + private int _fallbackPollingIntervalMs = 5000; // Default 5 seconds + private readonly int _wmiRetryDelayMs = 10000; // 10 seconds + + public event EventHandler? ProcessStarted; + public event EventHandler? ProcessStopped; + public event EventHandler? MonitoringStatusChanged; + + public bool IsMonitoring => _isMonitoring; + public bool IsWmiAvailable => _isWmiAvailable; + public bool IsFallbackPollingActive => _isFallbackPollingActive; + + public ProcessMonitorService(IProcessService processService, IApplicationSettingsService settingsService) + { + _processService = processService ?? throw new ArgumentNullException(nameof(processService)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + + // Initialize polling interval from settings + UpdatePollingInterval(); + } + + public async Task StartMonitoringAsync() + { + if (_disposed) throw new ObjectDisposedException(nameof(ProcessMonitorService)); + + lock (_lockObject) + { + if (_isMonitoring) return; + _isMonitoring = true; + } + + _cancellationTokenSource = new CancellationTokenSource(); + + // Initialize current process list + await InitializeProcessListAsync(); + + // Try to start WMI monitoring first + var wmiStarted = await TryStartWmiMonitoringAsync(); + + if (!wmiStarted) + { + // Fall back to polling if WMI is not available + StartFallbackPolling(); + } + + OnMonitoringStatusChanged(); + } + + public async Task StopMonitoringAsync() + { + if (_disposed) return; + + lock (_lockObject) + { + if (!_isMonitoring) return; + _isMonitoring = false; + } + + // Stop WMI watchers + StopWmiWatchers(); + + // Stop fallback polling + StopFallbackPolling(); + + // Cancel any ongoing operations + _cancellationTokenSource?.Cancel(); + _cancellationTokenSource?.Dispose(); + _cancellationTokenSource = null; + + _runningProcesses.Clear(); + OnMonitoringStatusChanged(); + + await Task.CompletedTask; + } + + public async Task> GetRunningProcessesAsync() + { + try + { + var processes = await _processService.GetProcessesAsync(); + return processes; + } + catch (Exception) + { + return Enumerable.Empty(); + } + } + + public async Task IsProcessRunningAsync(string executableName) + { + try + { + var processes = await GetRunningProcessesAsync(); + return processes.Any(p => string.Equals(p.Name, executableName, StringComparison.OrdinalIgnoreCase)); + } + catch + { + return false; + } + } + + private async Task InitializeProcessListAsync() + { + try + { + var processes = await GetRunningProcessesAsync(); + _runningProcesses.Clear(); + + foreach (var process in processes) + { + _runningProcesses.TryAdd(process.ProcessId, process); + } + } + catch (Exception ex) + { + OnMonitoringStatusChanged($"Failed to initialize process list: {ex.Message}", ex); + } + } + + private async Task TryStartWmiMonitoringAsync() + { + try + { + await Task.Run(() => + { + // Create WMI event watchers for process start and stop + var startQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"); + var stopQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"); + + _processStartWatcher = new ManagementEventWatcher(startQuery); + _processStopWatcher = new ManagementEventWatcher(stopQuery); + + _processStartWatcher.EventArrived += OnProcessStarted; + _processStopWatcher.EventArrived += OnProcessStopped; + + _processStartWatcher.Start(); + _processStopWatcher.Start(); + }); + + _isWmiAvailable = true; + OnMonitoringStatusChanged("WMI monitoring started successfully"); + return true; + } + catch (Exception ex) + { + _isWmiAvailable = false; + OnMonitoringStatusChanged($"WMI monitoring failed: {ex.Message}", ex); + + // Clean up any partially created watchers + StopWmiWatchers(); + + return false; + } + } + + private void StartFallbackPolling() + { + // Update polling interval from current settings + UpdatePollingInterval(); + + _isFallbackPollingActive = true; + _fallbackTimer = new System.Threading.Timer(FallbackPollingCallback, null, 0, _fallbackPollingIntervalMs); + OnMonitoringStatusChanged($"Fallback polling started (interval: {_fallbackPollingIntervalMs}ms)"); + } + + private void StopWmiWatchers() + { + try + { + _processStartWatcher?.Stop(); + _processStartWatcher?.Dispose(); + _processStartWatcher = null; + + _processStopWatcher?.Stop(); + _processStopWatcher?.Dispose(); + _processStopWatcher = null; + + _isWmiAvailable = false; + } + catch (Exception ex) + { + OnMonitoringStatusChanged($"Error stopping WMI watchers: {ex.Message}", ex); + } + } + + private void StopFallbackPolling() + { + _fallbackTimer?.Dispose(); + _fallbackTimer = null; + _isFallbackPollingActive = false; + } + + private async void OnProcessStarted(object sender, EventArrivedEventArgs e) + { + try + { + var processId = Convert.ToInt32(e.NewEvent["ProcessID"]); + var processName = e.NewEvent["ProcessName"]?.ToString() ?? string.Empty; + + // Get detailed process information + var process = await CreateProcessModelFromId(processId, processName); + if (process != null) + { + _runningProcesses.TryAdd(processId, process); + ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); + } + } + catch (Exception ex) + { + OnMonitoringStatusChanged($"Error handling process start event: {ex.Message}", ex); + } + } + + private void OnProcessStopped(object sender, EventArrivedEventArgs e) + { + try + { + var processId = Convert.ToInt32(e.NewEvent["ProcessID"]); + + if (_runningProcesses.TryRemove(processId, out var process)) + { + ProcessStopped?.Invoke(this, new ProcessEventArgs(process)); + } + } + catch (Exception ex) + { + OnMonitoringStatusChanged($"Error handling process stop event: {ex.Message}", ex); + } + } + + private async void FallbackPollingCallback(object? state) + { + if (!_isMonitoring || _cancellationTokenSource?.Token.IsCancellationRequested == true) + return; + + try + { + var currentProcesses = await GetRunningProcessesAsync(); + var currentProcessDict = currentProcesses.ToDictionary(p => p.ProcessId, p => p); + + // Check for new processes + foreach (var process in currentProcesses) + { + if (!_runningProcesses.ContainsKey(process.ProcessId)) + { + _runningProcesses.TryAdd(process.ProcessId, process); + ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); + } + } + + // Check for stopped processes + var stoppedProcesses = _runningProcesses.Keys + .Where(pid => !currentProcessDict.ContainsKey(pid)) + .ToList(); + + foreach (var pid in stoppedProcesses) + { + if (_runningProcesses.TryRemove(pid, out var stoppedProcess)) + { + ProcessStopped?.Invoke(this, new ProcessEventArgs(stoppedProcess)); + } + } + } + catch (Exception ex) + { + OnMonitoringStatusChanged($"Error in fallback polling: {ex.Message}", ex); + } + } + + private async Task CreateProcessModelFromId(int processId, string processName) + { + try + { + var process = Process.GetProcessById(processId); + var model = new ProcessModel { Process = process }; + return model; + } + catch + { + // Process may have already terminated + return null; + } + } + + private void OnMonitoringStatusChanged(string? message = null, Exception? error = null) + { + MonitoringStatusChanged?.Invoke(this, new MonitoringStatusEventArgs( + _isMonitoring, _isWmiAvailable, _isFallbackPollingActive, message, error)); + } + + private void UpdatePollingInterval() + { + var settings = _settingsService.Settings; + _fallbackPollingIntervalMs = settings.FallbackPollingIntervalMs; + } + + public void UpdateSettings() + { + UpdatePollingInterval(); + + // If fallback polling is active, restart it with new interval + if (_isFallbackPollingActive && _fallbackTimer != null) + { + _fallbackTimer.Change(0, _fallbackPollingIntervalMs); + OnMonitoringStatusChanged($"Polling interval updated to {_fallbackPollingIntervalMs}ms"); + } + } + + public void Dispose() + { + if (_disposed) return; + + StopMonitoringAsync().Wait(5000); // Wait up to 5 seconds for clean shutdown + + _disposed = true; + } + } +} diff --git a/Services/ProcessPowerPlanAssociationService.cs b/Services/ProcessPowerPlanAssociationService.cs new file mode 100644 index 0000000..8863d22 --- /dev/null +++ b/Services/ProcessPowerPlanAssociationService.cs @@ -0,0 +1,340 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing process-power plan associations with persistence + /// + public class ProcessPowerPlanAssociationService : IProcessPowerPlanAssociationService + { + private readonly string _configurationDirectory; + private readonly string _configurationFilePath; + private readonly object _lockObject = new(); + + private ProcessMonitorConfiguration _configuration; + + public event EventHandler? ConfigurationChanged; + + public ProcessMonitorConfiguration Configuration => _configuration; + + public ProcessPowerPlanAssociationService() + { + _configurationDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration"); + _configurationFilePath = Path.Combine(_configurationDirectory, "ProcessPowerPlanAssociations.json"); + _configuration = new ProcessMonitorConfiguration(); + + EnsureConfigurationDirectoryExists(); + } + + public async Task LoadConfigurationAsync() + { + try + { + if (!File.Exists(_configurationFilePath)) + { + // Create default configuration + _configuration = new ProcessMonitorConfiguration(); + await SaveConfigurationAsync(); + return true; + } + + var json = await File.ReadAllTextAsync(_configurationFilePath); + var loadedConfig = JsonSerializer.Deserialize(json); + + if (loadedConfig != null) + { + lock (_lockObject) + { + _configuration = loadedConfig; + } + + OnConfigurationChanged("Loaded", null, "Configuration loaded from file"); + return true; + } + + return false; + } + catch (Exception ex) + { + OnConfigurationChanged("LoadError", null, $"Failed to load configuration: {ex.Message}"); + return false; + } + } + + public async Task SaveConfigurationAsync() + { + try + { + ProcessMonitorConfiguration configToSave; + lock (_lockObject) + { + configToSave = _configuration; + configToSave.LastSavedDate = DateTime.Now; + } + + var options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + var json = JsonSerializer.Serialize(configToSave, options); + await File.WriteAllTextAsync(_configurationFilePath, json); + + OnConfigurationChanged("Saved", null, "Configuration saved to file"); + return true; + } + catch (Exception ex) + { + OnConfigurationChanged("SaveError", null, $"Failed to save configuration: {ex.Message}"); + return false; + } + } + + public async Task> GetAssociationsAsync() + { + await Task.CompletedTask; + lock (_lockObject) + { + return _configuration.Associations.ToList(); + } + } + + public async Task> GetEnabledAssociationsAsync() + { + await Task.CompletedTask; + lock (_lockObject) + { + return _configuration.GetEnabledAssociations().ToList(); + } + } + + public async Task AddAssociationAsync(ProcessPowerPlanAssociation association) + { + try + { + if (association == null) return false; + + lock (_lockObject) + { + // Check for duplicates + var existing = _configuration.Associations + .FirstOrDefault(a => a.ExecutableName.Equals(association.ExecutableName, StringComparison.OrdinalIgnoreCase)); + + if (existing != null) + { + return false; // Duplicate found + } + + _configuration.AddOrUpdateAssociation(association); + } + + await SaveConfigurationAsync(); + OnConfigurationChanged("Added", association, $"Association added for {association.ExecutableName}"); + return true; + } + catch (Exception ex) + { + OnConfigurationChanged("AddError", association, $"Failed to add association: {ex.Message}"); + return false; + } + } + + public async Task UpdateAssociationAsync(ProcessPowerPlanAssociation association) + { + try + { + if (association == null) return false; + + lock (_lockObject) + { + _configuration.AddOrUpdateAssociation(association); + } + + await SaveConfigurationAsync(); + OnConfigurationChanged("Updated", association, $"Association updated for {association.ExecutableName}"); + return true; + } + catch (Exception ex) + { + OnConfigurationChanged("UpdateError", association, $"Failed to update association: {ex.Message}"); + return false; + } + } + + public async Task RemoveAssociationAsync(string associationId) + { + try + { + ProcessPowerPlanAssociation? removedAssociation = null; + bool removed; + + lock (_lockObject) + { + removedAssociation = _configuration.Associations.FirstOrDefault(a => a.Id == associationId); + removed = _configuration.RemoveAssociation(associationId); + } + + if (removed) + { + await SaveConfigurationAsync(); + OnConfigurationChanged("Removed", removedAssociation, + $"Association removed for {removedAssociation?.ExecutableName}"); + } + + return removed; + } + catch (Exception ex) + { + OnConfigurationChanged("RemoveError", null, $"Failed to remove association: {ex.Message}"); + return false; + } + } + + public async Task FindMatchingAssociationAsync(ProcessModel process) + { + await Task.CompletedTask; + lock (_lockObject) + { + return _configuration.FindMatchingAssociation(process); + } + } + + public async Task FindAssociationByExecutableAsync(string executableName) + { + await Task.CompletedTask; + lock (_lockObject) + { + return _configuration.FindAssociationByExecutable(executableName); + } + } + + public async Task SetDefaultPowerPlanAsync(string powerPlanGuid, string powerPlanName) + { + try + { + lock (_lockObject) + { + _configuration.DefaultPowerPlanGuid = powerPlanGuid; + _configuration.DefaultPowerPlanName = powerPlanName; + } + + await SaveConfigurationAsync(); + OnConfigurationChanged("DefaultPowerPlanChanged", null, $"Default power plan set to {powerPlanName}"); + return true; + } + catch (Exception ex) + { + OnConfigurationChanged("DefaultPowerPlanError", null, $"Failed to set default power plan: {ex.Message}"); + return false; + } + } + + public async Task<(string Guid, string Name)> GetDefaultPowerPlanAsync() + { + await Task.CompletedTask; + lock (_lockObject) + { + return (_configuration.DefaultPowerPlanGuid, _configuration.DefaultPowerPlanName); + } + } + + public async Task> ValidateConfigurationAsync() + { + await Task.CompletedTask; + lock (_lockObject) + { + return _configuration.Validate(); + } + } + + public async Task ResetConfigurationAsync() + { + lock (_lockObject) + { + _configuration = new ProcessMonitorConfiguration(); + } + + await SaveConfigurationAsync(); + OnConfigurationChanged("Reset", null, "Configuration reset to defaults"); + } + + public async Task ExportConfigurationAsync(string filePath) + { + try + { + ProcessMonitorConfiguration configToExport; + lock (_lockObject) + { + configToExport = _configuration; + } + + var options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + var json = JsonSerializer.Serialize(configToExport, options); + await File.WriteAllTextAsync(filePath, json); + + OnConfigurationChanged("Exported", null, $"Configuration exported to {filePath}"); + return true; + } + catch (Exception ex) + { + OnConfigurationChanged("ExportError", null, $"Failed to export configuration: {ex.Message}"); + return false; + } + } + + public async Task ImportConfigurationAsync(string filePath) + { + try + { + if (!File.Exists(filePath)) return false; + + var json = await File.ReadAllTextAsync(filePath); + var importedConfig = JsonSerializer.Deserialize(json); + + if (importedConfig != null) + { + lock (_lockObject) + { + _configuration = importedConfig; + } + + await SaveConfigurationAsync(); + OnConfigurationChanged("Imported", null, $"Configuration imported from {filePath}"); + return true; + } + + return false; + } + catch (Exception ex) + { + OnConfigurationChanged("ImportError", null, $"Failed to import configuration: {ex.Message}"); + return false; + } + } + + private void EnsureConfigurationDirectoryExists() + { + if (!Directory.Exists(_configurationDirectory)) + { + Directory.CreateDirectory(_configurationDirectory); + } + } + + private void OnConfigurationChanged(string changeType, ProcessPowerPlanAssociation? association = null, string? details = null) + { + ConfigurationChanged?.Invoke(this, new ConfigurationChangedEventArgs(changeType, association, details)); + } + } +} diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 4ac2c63..54621ae 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -26,21 +26,47 @@ namespace ThreadPilot.Services return await Task.Run(() => { var processes = Process.GetProcesses() - .Select(p => new ProcessModel - { - Process = p, - ProcessId = p.Id, - Name = p.ProcessName, - MemoryUsage = p.WorkingSet64, - Priority = p.PriorityClass, - ProcessorAffinity = (long)p.ProcessorAffinity - }) + .Select(CreateProcessModel) + .Where(p => p != null) .OrderBy(p => p.Name); return new ObservableCollection(processes); }); } + public ProcessModel CreateProcessModel(Process process) + { + var model = new ProcessModel(); + try + { + model.Process = process; + model.ProcessId = process.Id; + model.Name = process.ProcessName; + model.MemoryUsage = process.WorkingSet64; + model.Priority = process.PriorityClass; + model.ProcessorAffinity = (long)process.ProcessorAffinity; + + // Try to get executable path + try + { + model.ExecutablePath = process.MainModule?.FileName ?? string.Empty; + } + catch + { + model.ExecutablePath = string.Empty; + } + } + catch + { + // Process may have terminated or access denied + // Return a minimal model + model.ProcessId = process.Id; + model.Name = process.ProcessName; + } + + return model; + } + public async Task SetProcessorAffinity(ProcessModel process, long affinityMask) { await Task.Run(() => @@ -129,5 +155,59 @@ namespace ThreadPilot.Services } }); } + + public async Task GetProcessByIdAsync(int processId) + { + return await Task.Run(() => + { + try + { + var process = Process.GetProcessById(processId); + return CreateProcessModel(process); + } + catch + { + return null; + } + }); + } + + public async Task> GetProcessesByNameAsync(string executableName) + { + return await Task.Run(() => + { + try + { + var processes = Process.GetProcessesByName(executableName) + .Select(CreateProcessModel) + .Where(p => p != null); + + return processes; + } + catch + { + return Enumerable.Empty(); + } + }); + } + + public async Task IsProcessRunningAsync(string executableName) + { + var processes = await GetProcessesByNameAsync(executableName); + return processes.Any(); + } + + public async Task> GetProcessesWithPathsAsync() + { + return await Task.Run(() => + { + var processes = Process.GetProcesses() + .Select(CreateProcessModel) + .Where(p => p != null && !string.IsNullOrEmpty(p.ExecutablePath)) + .OrderBy(p => p.Name); + + return processes; + }); + } } } \ No newline at end of file diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs new file mode 100644 index 0000000..8f3f12f --- /dev/null +++ b/Services/ServiceConfiguration.cs @@ -0,0 +1,166 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using ThreadPilot.ViewModels; + +namespace ThreadPilot.Services +{ + /// + /// Centralized service configuration for dependency injection + /// + public static class ServiceConfiguration + { + /// + /// Configure all application services + /// + public static IServiceCollection ConfigureApplicationServices(this IServiceCollection services) + { + // Configure service infrastructure + services.ConfigureServiceInfrastructure(); + + // Configure core system services + services.ConfigureCoreSystemServices(); + + // Configure process management services + services.ConfigureProcessManagementServices(); + + // Configure application services + services.ConfigureApplicationLevelServices(); + + // Configure presentation layer + services.ConfigurePresentationLayer(); + + return services; + } + + /// + /// Configure service infrastructure (logging, factories, etc.) + /// + private static IServiceCollection ConfigureServiceInfrastructure(this IServiceCollection services) + { + // Logging infrastructure + services.AddLogging(builder => + { + builder.AddConsole(); + builder.SetMinimumLevel(LogLevel.Information); + }); + + // Enhanced logging service + services.AddSingleton(); + + // Service factory for advanced service management + services.AddSingleton(); + + // Data access services + services.AddSingleton(); + + return services; + } + + /// + /// Configure core system services that interact directly with the OS + /// + private static IServiceCollection ConfigureCoreSystemServices(this IServiceCollection services) + { + // Core system interaction services + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + return services; + } + + /// + /// Configure process monitoring and management services + /// + private static IServiceCollection ConfigureProcessManagementServices(this IServiceCollection services) + { + // Process monitoring services + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // Game boost and optimization services + services.AddSingleton(); + + return services; + } + + /// + /// Configure application-level services (settings, notifications, etc.) + /// + private static IServiceCollection ConfigureApplicationLevelServices(this IServiceCollection services) + { + // Application configuration and settings + services.AddSingleton(); + + // User interface services + services.AddSingleton(); + services.AddSingleton(); + + // System integration services + services.AddSingleton(); + + return services; + } + + /// + /// Configure presentation layer (ViewModels and Views) + /// + private static IServiceCollection ConfigurePresentationLayer(this IServiceCollection services) + { + // ViewModel factory for centralized ViewModel management + services.AddViewModelFactory(); + + // ViewModels - Transient for proper lifecycle management + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + // Views - Transient for proper lifecycle management + services.AddTransient(); + + return services; + } + + /// + /// Validate service configuration + /// + public static void ValidateServiceConfiguration(IServiceProvider serviceProvider) + { + var loggerFactory = serviceProvider.GetRequiredService(); + var logger = loggerFactory.CreateLogger("ServiceConfiguration"); + + try + { + // Validate core services can be resolved + var coreServices = new[] + { + typeof(IProcessService), + typeof(IPowerPlanService), + typeof(ICpuTopologyService), + typeof(IEnhancedLoggingService), + typeof(IApplicationSettingsService) + }; + + foreach (var serviceType in coreServices) + { + var service = serviceProvider.GetRequiredService(serviceType); + if (service == null) + { + throw new InvalidOperationException($"Failed to resolve required service: {serviceType.Name}"); + } + } + + logger.LogInformation("Service configuration validation completed successfully"); + } + catch (Exception ex) + { + logger.LogError(ex, "Service configuration validation failed"); + throw; + } + } + } +} diff --git a/Services/ServiceFactory.cs b/Services/ServiceFactory.cs new file mode 100644 index 0000000..9ac91d8 --- /dev/null +++ b/Services/ServiceFactory.cs @@ -0,0 +1,166 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using ThreadPilot.Services.Core; + +namespace ThreadPilot.Services +{ + /// + /// Factory for creating and managing service instances with proper dependency resolution + /// + public interface IServiceFactory + { + /// + /// Create a service instance of the specified type + /// + T CreateService() where T : class; + + /// + /// Create a service instance with additional parameters + /// + T CreateService(params object[] parameters) where T : class; + + /// + /// Get or create a singleton service instance + /// + T GetSingletonService() where T : class; + + /// + /// Initialize all core services + /// + Task InitializeAllServicesAsync(); + + /// + /// Dispose all managed services + /// + Task DisposeAllServicesAsync(); + } + + /// + /// Implementation of service factory with dependency injection support + /// + public class ServiceFactory : IServiceFactory, IDisposable + { + private readonly IServiceProvider _serviceProvider; + private readonly ILogger _logger; + private readonly Dictionary _singletonInstances = new(); + private readonly List _managedServices = new(); + private bool _disposed; + + public ServiceFactory(IServiceProvider serviceProvider, ILogger logger) + { + _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public T CreateService() where T : class + { + try + { + var service = _serviceProvider.GetRequiredService(); + + // Track system services for lifecycle management + if (service is ISystemService systemService) + { + _managedServices.Add(systemService); + } + + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create service of type {ServiceType}", typeof(T).Name); + throw; + } + } + + public T CreateService(params object[] parameters) where T : class + { + try + { + // For services with additional parameters, use ActivatorUtilities + var service = ActivatorUtilities.CreateInstance(_serviceProvider, parameters); + + if (service is ISystemService systemService) + { + _managedServices.Add(systemService); + } + + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create service of type {ServiceType} with parameters", typeof(T).Name); + throw; + } + } + + public T GetSingletonService() where T : class + { + var serviceType = typeof(T); + + if (_singletonInstances.TryGetValue(serviceType, out var existingInstance)) + { + return (T)existingInstance; + } + + var newInstance = CreateService(); + _singletonInstances[serviceType] = newInstance; + + return newInstance; + } + + public async Task InitializeAllServicesAsync() + { + _logger.LogInformation("Initializing all managed services"); + + var initializationTasks = _managedServices.Select(async service => + { + try + { + await service.InitializeAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize service {ServiceType}", service.GetType().Name); + throw; + } + }); + + await Task.WhenAll(initializationTasks); + _logger.LogInformation("All managed services initialized successfully"); + } + + public async Task DisposeAllServicesAsync() + { + _logger.LogInformation("Disposing all managed services"); + + var disposalTasks = _managedServices.Select(async service => + { + try + { + await service.DisposeAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error disposing service {ServiceType}", service.GetType().Name); + } + }); + + await Task.WhenAll(disposalTasks); + _managedServices.Clear(); + _singletonInstances.Clear(); + + _logger.LogInformation("All managed services disposed"); + } + + public void Dispose() + { + if (!_disposed) + { + _ = Task.Run(async () => await DisposeAllServicesAsync()); + _disposed = true; + } + } + } +} diff --git a/Services/SystemTrayService.cs b/Services/SystemTrayService.cs new file mode 100644 index 0000000..1087078 --- /dev/null +++ b/Services/SystemTrayService.cs @@ -0,0 +1,387 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing system tray icon and context menu + /// + public class SystemTrayService : ISystemTrayService + { + private readonly ILogger _logger; + private NotifyIcon? _notifyIcon; + private ContextMenuStrip? _contextMenu; + private ToolStripMenuItem? _quickApplyMenuItem; + private ToolStripMenuItem? _selectedProcessMenuItem; + private ToolStripMenuItem? _monitoringToggleMenuItem; + private ToolStripMenuItem? _gameBoostStatusMenuItem; + private ToolStripMenuItem? _settingsMenuItem; + private ApplicationSettingsModel _settings; + private bool _isMonitoring = true; + private bool _isWmiAvailable = true; + private bool _isGameBoostActive = false; + private string? _currentGameName = null; + private TrayIconState _currentIconState = TrayIconState.Normal; + private bool _disposed = false; + + public event EventHandler? QuickApplyRequested; + public event EventHandler? ShowMainWindowRequested; + public event EventHandler? ExitRequested; + public event EventHandler? MonitoringToggleRequested; + public event EventHandler? SettingsRequested; + + public SystemTrayService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _settings = new ApplicationSettingsModel(); // Default settings + } + + public void Initialize() + { + try + { + _logger.LogInformation("Initializing system tray service"); + + // Create the notify icon + _notifyIcon = new NotifyIcon + { + Text = "ThreadPilot - Process & Power Plan Manager", + Visible = false + }; + + // Try to load icon from resources or use default + try + { + // For now, use a simple system icon + _notifyIcon.Icon = SystemIcons.Application; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to load tray icon, using default"); + _notifyIcon.Icon = SystemIcons.Application; + } + + // Create context menu + CreateContextMenu(); + + // Set up event handlers + _notifyIcon.DoubleClick += OnTrayIconDoubleClick; + _notifyIcon.ContextMenuStrip = _contextMenu; + + // Set initial icon state + UpdateTrayIcon(TrayIconState.Normal); + + _logger.LogInformation("System tray service initialized successfully"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize system tray service"); + throw; + } + } + + private void CreateContextMenu() + { + _contextMenu = new ContextMenuStrip(); + + // Selected process info (disabled, for display only) + _selectedProcessMenuItem = new ToolStripMenuItem("No process selected") + { + Enabled = false, + Font = new Font(_contextMenu.Font, FontStyle.Bold) + }; + _contextMenu.Items.Add(_selectedProcessMenuItem); + + // Separator + _contextMenu.Items.Add(new ToolStripSeparator()); + + // Quick apply command + _quickApplyMenuItem = new ToolStripMenuItem("Quick Apply Affinity & Power Plan") + { + Enabled = false + }; + _quickApplyMenuItem.Click += OnQuickApplyClick; + _contextMenu.Items.Add(_quickApplyMenuItem); + + // Separator + _contextMenu.Items.Add(new ToolStripSeparator()); + + // Monitoring toggle + _monitoringToggleMenuItem = new ToolStripMenuItem("Disable Process Monitoring"); + _monitoringToggleMenuItem.Click += OnMonitoringToggleClick; + _contextMenu.Items.Add(_monitoringToggleMenuItem); + + // Game Boost status (disabled, for display only) + _gameBoostStatusMenuItem = new ToolStripMenuItem("Game Boost: Inactive") + { + Enabled = false, + Font = new Font(_contextMenu.Font, FontStyle.Italic) + }; + _contextMenu.Items.Add(_gameBoostStatusMenuItem); + + // Separator + _contextMenu.Items.Add(new ToolStripSeparator()); + + // Settings + _settingsMenuItem = new ToolStripMenuItem("Settings..."); + _settingsMenuItem.Click += OnSettingsClick; + _contextMenu.Items.Add(_settingsMenuItem); + + // Show main window + var showMenuItem = new ToolStripMenuItem("Show ThreadPilot"); + showMenuItem.Click += OnShowMainWindowClick; + _contextMenu.Items.Add(showMenuItem); + + // Separator + _contextMenu.Items.Add(new ToolStripSeparator()); + + // Exit + var exitMenuItem = new ToolStripMenuItem("Exit"); + exitMenuItem.Click += OnExitClick; + _contextMenu.Items.Add(exitMenuItem); + } + + public void Show() + { + if (_notifyIcon != null) + { + _notifyIcon.Visible = true; + _logger.LogDebug("System tray icon shown"); + } + } + + public void Hide() + { + if (_notifyIcon != null) + { + _notifyIcon.Visible = false; + _logger.LogDebug("System tray icon hidden"); + } + } + + public void UpdateTooltip(string tooltip) + { + if (_notifyIcon != null) + { + _notifyIcon.Text = tooltip.Length > 63 ? tooltip.Substring(0, 60) + "..." : tooltip; + } + } + + public void ShowBalloonTip(string title, string text, int timeoutMs = 3000) + { + if (_notifyIcon != null && _notifyIcon.Visible) + { + _notifyIcon.ShowBalloonTip(timeoutMs, title, text, ToolTipIcon.Info); + } + } + + public void UpdateContextMenu(string? selectedProcessName = null, bool hasSelection = false) + { + if (_selectedProcessMenuItem == null || _quickApplyMenuItem == null) return; + + if (hasSelection && !string.IsNullOrEmpty(selectedProcessName)) + { + _selectedProcessMenuItem.Text = $"Selected: {selectedProcessName}"; + _quickApplyMenuItem.Enabled = true; + _quickApplyMenuItem.Text = $"Quick Apply to {selectedProcessName}"; + } + else + { + _selectedProcessMenuItem.Text = "No process selected"; + _quickApplyMenuItem.Enabled = false; + _quickApplyMenuItem.Text = "Quick Apply Affinity & Power Plan"; + } + } + + private void OnTrayIconDoubleClick(object? sender, EventArgs e) + { + ShowMainWindowRequested?.Invoke(this, EventArgs.Empty); + } + + private void OnQuickApplyClick(object? sender, EventArgs e) + { + QuickApplyRequested?.Invoke(this, EventArgs.Empty); + } + + private void OnShowMainWindowClick(object? sender, EventArgs e) + { + ShowMainWindowRequested?.Invoke(this, EventArgs.Empty); + } + + private void OnExitClick(object? sender, EventArgs e) + { + ExitRequested?.Invoke(this, EventArgs.Empty); + } + + private void OnMonitoringToggleClick(object? sender, EventArgs e) + { + _isMonitoring = !_isMonitoring; + MonitoringToggleRequested?.Invoke(this, new MonitoringToggleEventArgs(_isMonitoring)); + UpdateMonitoringStatus(_isMonitoring, _isWmiAvailable); + } + + private void OnSettingsClick(object? sender, EventArgs e) + { + SettingsRequested?.Invoke(this, EventArgs.Empty); + } + + public void UpdateMonitoringStatus(bool isMonitoring, bool isWmiAvailable = true) + { + _isMonitoring = isMonitoring; + _isWmiAvailable = isWmiAvailable; + + if (_monitoringToggleMenuItem != null) + { + _monitoringToggleMenuItem.Text = isMonitoring ? "Disable Process Monitoring" : "Enable Process Monitoring"; + _monitoringToggleMenuItem.Enabled = isWmiAvailable; + } + + // Update tray icon state + var iconState = !isWmiAvailable ? TrayIconState.Error : + isMonitoring ? TrayIconState.Monitoring : TrayIconState.Disabled; + UpdateTrayIcon(iconState); + + // Update tooltip + var status = !isWmiAvailable ? "WMI Error" : + isMonitoring ? "Monitoring Active" : "Monitoring Disabled"; + UpdateTooltip($"ThreadPilot - {status}"); + } + + public void UpdateTrayIcon(TrayIconState state) + { + if (_notifyIcon == null) return; + + _currentIconState = state; + + try + { + // For now, use different system icons to represent states + // In a real implementation, you might want custom icons + _notifyIcon.Icon = state switch + { + TrayIconState.Normal => SystemIcons.Application, + TrayIconState.Monitoring => SystemIcons.Information, + TrayIconState.Error => SystemIcons.Error, + TrayIconState.Disabled => SystemIcons.Warning, + TrayIconState.GameBoost => SystemIcons.Shield, // Use shield icon for Game Boost + _ => SystemIcons.Application + }; + + _logger.LogDebug("Tray icon updated to state: {State}", state); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to update tray icon"); + } + } + + public void ShowTrayNotification(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000) + { + if (_notifyIcon == null || !_settings.EnableBalloonNotifications) return; + + try + { + var balloonIcon = type switch + { + NotificationType.Error => ToolTipIcon.Error, + NotificationType.Warning => ToolTipIcon.Warning, + NotificationType.Success => ToolTipIcon.Info, + _ => ToolTipIcon.Info + }; + + _notifyIcon.ShowBalloonTip(timeoutMs, title, message, balloonIcon); + _logger.LogDebug("Balloon tip shown: {Title}", title); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error showing balloon tip"); + } + } + + public void UpdateSettings(ApplicationSettingsModel settings) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + + // Update tray icon visibility + if (_notifyIcon != null) + { + _notifyIcon.Visible = settings.ShowTrayIcon; + } + + _logger.LogDebug("Tray service settings updated"); + } + + public void UpdateGameBoostStatus(bool isGameBoostActive, string? currentGameName = null) + { + _isGameBoostActive = isGameBoostActive; + _currentGameName = currentGameName; + + // Update Game Boost status menu item + if (_gameBoostStatusMenuItem != null) + { + if (isGameBoostActive && !string.IsNullOrEmpty(currentGameName)) + { + _gameBoostStatusMenuItem.Text = $"Game Boost: Active ({currentGameName})"; + _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Bold); + } + else if (isGameBoostActive) + { + _gameBoostStatusMenuItem.Text = "Game Boost: Active"; + _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Bold); + } + else + { + _gameBoostStatusMenuItem.Text = "Game Boost: Inactive"; + _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Italic); + } + } + + // Update tray icon state - Game Boost takes priority over monitoring state + var iconState = !_isWmiAvailable ? TrayIconState.Error : + isGameBoostActive ? TrayIconState.GameBoost : + _isMonitoring ? TrayIconState.Monitoring : TrayIconState.Disabled; + UpdateTrayIcon(iconState); + + // Update tooltip + var status = !_isWmiAvailable ? "WMI Error" : + isGameBoostActive ? $"Game Boost Active{(!string.IsNullOrEmpty(currentGameName) ? $" - {currentGameName}" : "")}" : + _isMonitoring ? "Monitoring Active" : "Monitoring Disabled"; + UpdateTooltip($"ThreadPilot - {status}"); + + _logger.LogDebug("Game Boost status updated: Active={IsActive}, Game={GameName}", isGameBoostActive, currentGameName); + } + + public void Dispose() + { + if (_disposed) return; + + try + { + _logger.LogInformation("Disposing system tray service"); + + if (_notifyIcon != null) + { + _notifyIcon.Visible = false; + _notifyIcon.Dispose(); + _notifyIcon = null; + } + + if (_contextMenu != null) + { + _contextMenu.Dispose(); + _contextMenu = null; + } + + _disposed = true; + _logger.LogInformation("System tray service disposed"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error disposing system tray service"); + } + } + } +} diff --git a/TestRunner.cs b/TestRunner.cs new file mode 100644 index 0000000..9461611 --- /dev/null +++ b/TestRunner.cs @@ -0,0 +1,34 @@ +using System; +using System.Threading.Tasks; +using ThreadPilot.Tests; + +namespace ThreadPilot +{ + /// + /// Simple test runner for CPU topology functionality + /// + public static class TestRunner + { + /// + /// Main test entry point + /// + public static async Task RunTests() + { + Console.WriteLine("ThreadPilot CPU Topology Test Runner"); + Console.WriteLine("===================================="); + + try + { + await CpuTopologyServiceTests.TestCpuTopologyDetection(); + } + catch (Exception ex) + { + Console.WriteLine($"Test failed with exception: {ex.Message}"); + Console.WriteLine($"Stack trace: {ex.StackTrace}"); + } + + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} diff --git a/Tests/CpuTopologyServiceTests.cs b/Tests/CpuTopologyServiceTests.cs new file mode 100644 index 0000000..391a253 --- /dev/null +++ b/Tests/CpuTopologyServiceTests.cs @@ -0,0 +1,119 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Services; +using ThreadPilot.Models; + +namespace ThreadPilot.Tests +{ + /// + /// Simple test class for CPU topology detection + /// + public static class CpuTopologyServiceTests + { + /// + /// Test CPU topology detection + /// + public static async Task TestCpuTopologyDetection() + { + Console.WriteLine("=== CPU Topology Detection Test ==="); + + try + { + // Create logger + using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); + var logger = loggerFactory.CreateLogger(); + + // Create service + var service = new CpuTopologyService(logger); + + // Subscribe to events + service.TopologyDetected += (sender, e) => + { + Console.WriteLine($"Topology detected: Success={e.DetectionSuccessful}"); + if (e.Topology != null) + { + PrintTopologyInfo(e.Topology); + } + }; + + // Detect topology + Console.WriteLine("Starting topology detection..."); + await service.DetectTopologyAsync(); + + // Get current topology + var topology = service.CurrentTopology; + if (topology != null) + { + Console.WriteLine("\n=== Current Topology ==="); + PrintTopologyInfo(topology); + + // Test affinity presets + Console.WriteLine("\n=== Affinity Presets ==="); + var presets = service.GetAffinityPresets(); + foreach (var preset in presets) + { + Console.WriteLine($"- {preset.Name}: {preset.Description}"); + Console.WriteLine($" Mask: 0x{preset.AffinityMask:X}"); + } + + // Test affinity validation + Console.WriteLine("\n=== Affinity Validation ==="); + var testMask = topology.CalculateAffinityMask(topology.LogicalCores); + var isValid = service.IsAffinityMaskValid(testMask); + Console.WriteLine($"Test mask 0x{testMask:X} is valid: {isValid}"); + } + else + { + Console.WriteLine("No topology detected"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine($"Stack trace: {ex.StackTrace}"); + } + + Console.WriteLine("\n=== Test Complete ==="); + } + + private static void PrintTopologyInfo(CpuTopologyModel topology) + { + Console.WriteLine($"Total Logical Cores: {topology.LogicalCores.Count}"); + Console.WriteLine($"Total Physical Cores: {topology.PhysicalCores.Count()}"); + Console.WriteLine($"Socket Count: {topology.SocketCount}"); + Console.WriteLine($"CCD Count: {topology.CcdCount}"); + Console.WriteLine($"Has Hybrid Architecture: {topology.HasHybridArchitecture}"); + Console.WriteLine($"Has SMT: {topology.HasSmt}"); + Console.WriteLine($"Architecture: {topology.Architecture}"); + + if (topology.HasHybridArchitecture) + { + var pCores = topology.LogicalCores.Count(c => c.CoreType == CpuCoreType.PerformanceCore); + var eCores = topology.LogicalCores.Count(c => c.CoreType == CpuCoreType.EfficiencyCore); + Console.WriteLine($"P-Cores: {pCores}, E-Cores: {eCores}"); + } + + if (topology.CcdCount > 1) + { + for (int i = 0; i < topology.CcdCount; i++) + { + var ccdCores = topology.LogicalCores.Count(c => c.CcdId == i); + Console.WriteLine($"CCD {i}: {ccdCores} cores"); + } + } + + Console.WriteLine("\nCore Details:"); + foreach (var core in topology.LogicalCores.Take(Math.Min(8, topology.LogicalCores.Count))) + { + Console.WriteLine($" Core {core.LogicalCoreId}: Physical={core.PhysicalCoreId}, " + + $"CCD={core.CcdId}, Type={core.CoreType}, HT={core.IsHyperThreaded}"); + } + + if (topology.LogicalCores.Count > 8) + { + Console.WriteLine($" ... and {topology.LogicalCores.Count - 8} more cores"); + } + } + } +} diff --git a/Tests/GameBoostIntegrationTest.cs b/Tests/GameBoostIntegrationTest.cs new file mode 100644 index 0000000..d05b04f --- /dev/null +++ b/Tests/GameBoostIntegrationTest.cs @@ -0,0 +1,211 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using ThreadPilot.Services; +using ThreadPilot.Models; + +namespace ThreadPilot.Tests +{ + /// + /// Integration test for Game Boost functionality + /// + public class GameBoostIntegrationTest + { + private readonly IServiceProvider _serviceProvider; + private readonly ILogger _logger; + + public GameBoostIntegrationTest(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + _logger = serviceProvider.GetRequiredService>(); + } + + /// + /// Tests the complete Game Boost workflow + /// + public async Task RunIntegrationTestAsync() + { + try + { + _logger.LogInformation("Starting Game Boost integration test..."); + + // Test 1: Service Resolution + if (!await TestServiceResolutionAsync()) + { + _logger.LogError("Service resolution test failed"); + return false; + } + + // Test 2: Game Detection Logic + if (!await TestGameDetectionAsync()) + { + _logger.LogError("Game detection test failed"); + return false; + } + + // Test 3: Known Games Management + if (!await TestKnownGamesManagementAsync()) + { + _logger.LogError("Known games management test failed"); + return false; + } + + // Test 4: System Tray Integration + if (!await TestSystemTrayIntegrationAsync()) + { + _logger.LogError("System tray integration test failed"); + return false; + } + + _logger.LogInformation("All Game Boost integration tests passed!"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Game Boost integration test failed with exception"); + return false; + } + } + + private async Task TestServiceResolutionAsync() + { + try + { + _logger.LogInformation("Testing service resolution..."); + + var gameBoostService = _serviceProvider.GetRequiredService(); + var systemTrayService = _serviceProvider.GetRequiredService(); + var processMonitorService = _serviceProvider.GetRequiredService(); + var settingsService = _serviceProvider.GetRequiredService(); + + if (gameBoostService == null || systemTrayService == null || + processMonitorService == null || settingsService == null) + { + _logger.LogError("One or more required services could not be resolved"); + return false; + } + + _logger.LogInformation("Service resolution test passed"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Service resolution test failed"); + return false; + } + } + + private async Task TestGameDetectionAsync() + { + try + { + _logger.LogInformation("Testing game detection logic..."); + + var gameBoostService = _serviceProvider.GetRequiredService(); + + // Test with known game processes + var testProcesses = new[] + { + new ProcessModel { Name = "steam.exe", ProcessId = 1234, ExecutablePath = @"C:\Program Files\Steam\steam.exe" }, + new ProcessModel { Name = "notepad.exe", ProcessId = 5678, ExecutablePath = @"C:\Windows\System32\notepad.exe" }, + new ProcessModel { Name = "csgo.exe", ProcessId = 9999, ExecutablePath = @"C:\Games\Counter-Strike\csgo.exe" } + }; + + foreach (var process in testProcesses) + { + var isGame = gameBoostService.IsGameProcess(process); + _logger.LogInformation("Process {ProcessName}: IsGame = {IsGame}", process.Name, isGame); + } + + _logger.LogInformation("Game detection test passed"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Game detection test failed"); + return false; + } + } + + private async Task TestKnownGamesManagementAsync() + { + try + { + _logger.LogInformation("Testing known games management..."); + + var gameBoostService = _serviceProvider.GetRequiredService(); + + // Get initial count + var initialCount = gameBoostService.KnownGameExecutables.Count; + _logger.LogInformation("Initial known games count: {Count}", initialCount); + + // Test adding a game + var testGame = "testgame.exe"; + var addResult = await gameBoostService.AddKnownGameAsync(testGame); + if (!addResult) + { + _logger.LogError("Failed to add test game"); + return false; + } + + // Verify it was added + var newCount = gameBoostService.KnownGameExecutables.Count; + if (newCount != initialCount + 1) + { + _logger.LogError("Game count did not increase after adding game"); + return false; + } + + // Test removing the game + var removeResult = await gameBoostService.RemoveKnownGameAsync(testGame); + if (!removeResult) + { + _logger.LogError("Failed to remove test game"); + return false; + } + + // Verify it was removed + var finalCount = gameBoostService.KnownGameExecutables.Count; + if (finalCount != initialCount) + { + _logger.LogError("Game count did not return to initial value after removing game"); + return false; + } + + _logger.LogInformation("Known games management test passed"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Known games management test failed"); + return false; + } + } + + private async Task TestSystemTrayIntegrationAsync() + { + try + { + _logger.LogInformation("Testing system tray integration..."); + + var systemTrayService = _serviceProvider.GetRequiredService(); + + // Test updating Game Boost status + systemTrayService.UpdateGameBoostStatus(true, "TestGame"); + await Task.Delay(100); // Allow UI to update + + systemTrayService.UpdateGameBoostStatus(false); + await Task.Delay(100); // Allow UI to update + + _logger.LogInformation("System tray integration test passed"); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "System tray integration test failed"); + return false; + } + } + } +} diff --git a/Tests/TestRunner.cs b/Tests/TestRunner.cs new file mode 100644 index 0000000..f62244a --- /dev/null +++ b/Tests/TestRunner.cs @@ -0,0 +1,89 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace ThreadPilot.Tests +{ + /// + /// Test runner for validating Game Boost functionality + /// + public static class TestRunner + { + /// + /// Runs all Game Boost integration tests + /// + public static async Task RunGameBoostTestsAsync(IServiceProvider serviceProvider) + { + var logger = serviceProvider.GetRequiredService>(); + + try + { + logger.LogInformation("=== Starting Game Boost Integration Tests ==="); + + var integrationTest = new GameBoostIntegrationTest(serviceProvider); + var result = await integrationTest.RunIntegrationTestAsync(); + + if (result) + { + logger.LogInformation("=== All Game Boost Tests PASSED ==="); + } + else + { + logger.LogError("=== Game Boost Tests FAILED ==="); + } + + return result; + } + catch (Exception ex) + { + logger.LogError(ex, "Test runner failed with exception"); + return false; + } + } + + /// + /// Validates that all required services are properly configured + /// + public static bool ValidateServiceConfiguration(IServiceProvider serviceProvider) + { + var logger = serviceProvider.GetRequiredService>(); + + try + { + logger.LogInformation("Validating service configuration..."); + + // Check all required services + var requiredServices = new[] + { + typeof(ThreadPilot.Services.IGameBoostService), + typeof(ThreadPilot.Services.ISystemTrayService), + typeof(ThreadPilot.Services.IProcessMonitorService), + typeof(ThreadPilot.Services.IApplicationSettingsService), + typeof(ThreadPilot.Services.INotificationService), + typeof(ThreadPilot.Services.IPowerPlanService), + typeof(ThreadPilot.Services.IProcessService) + }; + + foreach (var serviceType in requiredServices) + { + var service = serviceProvider.GetService(serviceType); + if (service == null) + { + logger.LogError("Required service {ServiceType} is not registered", serviceType.Name); + return false; + } + logger.LogDebug("Service {ServiceType} is properly registered", serviceType.Name); + } + + logger.LogInformation("Service configuration validation passed"); + return true; + } + catch (Exception ex) + { + logger.LogError(ex, "Service configuration validation failed"); + return false; + } + } + } +} diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 0eb3b5e..da6bded 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -2,15 +2,20 @@ WinExe - net9.0-windows + net8.0-windows enable enable true + true - + + + + + diff --git a/UI_STYLE_GUIDE.md b/UI_STYLE_GUIDE.md new file mode 100644 index 0000000..5277efc --- /dev/null +++ b/UI_STYLE_GUIDE.md @@ -0,0 +1,202 @@ +# 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 + - 📋 Activity Logs + - ⚙️ 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 diff --git a/ViewModels/BaseViewModel.cs b/ViewModels/BaseViewModel.cs index a086585..d5e80ce 100644 --- a/ViewModels/BaseViewModel.cs +++ b/ViewModels/BaseViewModel.cs @@ -1,25 +1,188 @@ using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.Extensions.Logging; +using System; +using System.Threading.Tasks; +using ThreadPilot.Services; namespace ThreadPilot.ViewModels { - public abstract partial class BaseViewModel : ObservableObject + /// + /// Base ViewModel with common functionality for all ViewModels + /// + public abstract partial class BaseViewModel : ObservableObject, IDisposable { + protected readonly ILogger Logger; + protected readonly IEnhancedLoggingService? EnhancedLoggingService; + private bool _disposed; + [ObservableProperty] private bool isBusy; [ObservableProperty] private string statusMessage = string.Empty; + [ObservableProperty] + private bool hasError; + + [ObservableProperty] + private string errorMessage = string.Empty; + + protected BaseViewModel(ILogger logger, IEnhancedLoggingService? enhancedLoggingService = null) + { + Logger = logger ?? throw new ArgumentNullException(nameof(logger)); + EnhancedLoggingService = enhancedLoggingService; + } + + /// + /// Set status message and busy state + /// protected void SetStatus(string message, bool isBusyState = true) { StatusMessage = message; IsBusy = isBusyState; + ClearError(); } + /// + /// Clear status and busy state + /// protected void ClearStatus() { StatusMessage = string.Empty; IsBusy = false; } + + /// + /// Set error message and clear busy state + /// + protected void SetError(string message, Exception? exception = null) + { + ErrorMessage = message; + HasError = true; + IsBusy = false; + + if (exception != null) + { + Logger.LogError(exception, "Error in {ViewModelType}: {Message}", GetType().Name, message); + } + else + { + Logger.LogWarning("Error in {ViewModelType}: {Message}", GetType().Name, message); + } + } + + /// + /// Clear error state + /// + protected void ClearError() + { + ErrorMessage = string.Empty; + HasError = false; + } + + /// + /// Execute an async operation with error handling and status updates + /// + protected async Task ExecuteAsync(Func operation, string? statusMessage = null, string? successMessage = null) + { + try + { + if (!string.IsNullOrEmpty(statusMessage)) + { + SetStatus(statusMessage); + } + + await operation(); + + if (!string.IsNullOrEmpty(successMessage)) + { + SetStatus(successMessage, false); + } + else + { + ClearStatus(); + } + } + catch (Exception ex) + { + SetError($"Operation failed: {ex.Message}", ex); + } + } + + /// + /// Execute an async operation with return value and error handling + /// + protected async Task ExecuteAsync(Func> operation, string? statusMessage = null, string? successMessage = null) + { + try + { + if (!string.IsNullOrEmpty(statusMessage)) + { + SetStatus(statusMessage); + } + + var result = await operation(); + + if (!string.IsNullOrEmpty(successMessage)) + { + SetStatus(successMessage, false); + } + else + { + ClearStatus(); + } + + return result; + } + catch (Exception ex) + { + SetError($"Operation failed: {ex.Message}", ex); + return default; + } + } + + /// + /// Log user action for audit purposes + /// + protected async Task LogUserActionAsync(string action, string details, string? context = null) + { + try + { + if (EnhancedLoggingService != null) + { + await EnhancedLoggingService.LogUserActionAsync(action, details, context); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to log user action: {Action}", action); + } + } + + /// + /// Initialize the ViewModel - override in derived classes + /// + public virtual async Task InitializeAsync() + { + // Base implementation does nothing + await Task.CompletedTask; + } + + /// + /// Cleanup resources - override in derived classes + /// + protected virtual void OnDispose() + { + // Base implementation does nothing + } + + public void Dispose() + { + if (!_disposed) + { + OnDispose(); + _disposed = true; + } + } } } \ No newline at end of file diff --git a/ViewModels/LogViewerViewModel.cs b/ViewModels/LogViewerViewModel.cs new file mode 100644 index 0000000..ed24cc4 --- /dev/null +++ b/ViewModels/LogViewerViewModel.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; +using ThreadPilot.Services; + +namespace ThreadPilot.ViewModels +{ + /// + /// ViewModel for the log viewer and management interface + /// + public partial class LogViewerViewModel : ObservableObject + { + private readonly IEnhancedLoggingService _loggingService; + private readonly IApplicationSettingsService _settingsService; + private readonly ILogger _logger; + + [ObservableProperty] + private ObservableCollection _logEntries = new(); + + [ObservableProperty] + private LogEntryDisplayModel? _selectedLogEntry; + + [ObservableProperty] + private string _searchText = string.Empty; + + [ObservableProperty] + private LogLevel _selectedLogLevel = LogLevel.Information; + + [ObservableProperty] + private string _selectedCategory = "All"; + + [ObservableProperty] + private DateTime _fromDate = DateTime.Today.AddDays(-7); + + [ObservableProperty] + private DateTime _toDate = DateTime.Today.AddDays(1); + + [ObservableProperty] + private bool _isLoading; + + [ObservableProperty] + private string _statusMessage = "Ready"; + + [ObservableProperty] + private LogFileStatistics? _logStatistics; + + [ObservableProperty] + private bool _enableDebugLogging; + + [ObservableProperty] + private int _maxLogFileSizeMb = 10; + + [ObservableProperty] + private int _logRetentionDays = 7; + + [ObservableProperty] + private bool _autoRefresh = true; + + [ObservableProperty] + private int _refreshIntervalSeconds = 30; + + public ObservableCollection AvailableCategories { get; } = new() + { + "All", "PowerPlan", "ProcessMonitoring", "GameBoost", "UserAction", "System", "Error", "Performance" + }; + + public ObservableCollection AvailableLogLevels { get; } = new() + { + LogLevel.Trace, LogLevel.Debug, LogLevel.Information, LogLevel.Warning, LogLevel.Error, LogLevel.Critical + }; + + public ICommand RefreshLogsCommand { get; } + public ICommand ClearLogsCommand { get; } + public ICommand ExportLogsCommand { get; } + public ICommand CleanupOldLogsCommand { get; } + public ICommand SaveSettingsCommand { get; } + public ICommand OpenLogDirectoryCommand { get; } + public ICommand CopyLogEntryCommand { get; } + + public LogViewerViewModel( + IEnhancedLoggingService loggingService, + IApplicationSettingsService settingsService, + ILogger logger) + { + _loggingService = loggingService ?? throw new ArgumentNullException(nameof(loggingService)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + // Initialize commands + RefreshLogsCommand = new AsyncRelayCommand(RefreshLogsAsync); + ClearLogsCommand = new AsyncRelayCommand(ClearLogsAsync); + ExportLogsCommand = new AsyncRelayCommand(ExportLogsAsync); + CleanupOldLogsCommand = new AsyncRelayCommand(CleanupOldLogsAsync); + SaveSettingsCommand = new AsyncRelayCommand(SaveSettingsAsync); + OpenLogDirectoryCommand = new RelayCommand(OpenLogDirectory); + CopyLogEntryCommand = new RelayCommand(CopyLogEntry); + + // Load initial settings + LoadSettings(); + + // Start auto-refresh if enabled + if (_autoRefresh) + { + StartAutoRefresh(); + } + } + + public async Task InitializeAsync() + { + try + { + IsLoading = true; + StatusMessage = "Loading logs..."; + + await RefreshLogsAsync(); + await RefreshStatisticsAsync(); + + StatusMessage = "Ready"; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize log viewer"); + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private async Task RefreshLogsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Refreshing logs..."; + + var logEntries = await _loggingService.GetLogEntriesAsync(FromDate, ToDate); + + // Filter by category and log level + var filteredEntries = logEntries.Where(entry => + { + var categoryMatch = SelectedCategory == "All" || entry.Category == SelectedCategory; + var levelMatch = entry.Level >= SelectedLogLevel; + var searchMatch = string.IsNullOrEmpty(SearchText) || + entry.Message.Contains(SearchText, StringComparison.OrdinalIgnoreCase) || + entry.Category.Contains(SearchText, StringComparison.OrdinalIgnoreCase); + + return categoryMatch && levelMatch && searchMatch; + }).ToList(); + + // Convert to display models + var displayModels = filteredEntries.Select(entry => new LogEntryDisplayModel + { + Timestamp = entry.Timestamp, + Level = entry.Level, + Category = entry.Category, + Message = entry.Message, + Exception = entry.Exception, + Properties = entry.Properties, + CorrelationId = entry.CorrelationId + }).ToList(); + + LogEntries.Clear(); + foreach (var model in displayModels) + { + LogEntries.Add(model); + } + + StatusMessage = $"Loaded {LogEntries.Count} log entries"; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to refresh logs"); + StatusMessage = $"Error refreshing logs: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private async Task RefreshStatisticsAsync() + { + try + { + LogStatistics = await _loggingService.GetLogStatisticsAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to refresh log statistics"); + } + } + + private async Task ClearLogsAsync() + { + try + { + LogEntries.Clear(); + StatusMessage = "Log display cleared"; + await _loggingService.LogUserActionAsync("LogsCleared", "User cleared log display"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to clear logs"); + StatusMessage = $"Error clearing logs: {ex.Message}"; + } + } + + private async Task ExportLogsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Exporting logs..."; + + var exportPath = await _loggingService.ExportLogsAsync(FromDate, ToDate); + StatusMessage = $"Logs exported to: {exportPath}"; + + await _loggingService.LogUserActionAsync("LogsExported", + $"Logs exported to {exportPath}", $"DateRange: {FromDate:yyyy-MM-dd} to {ToDate:yyyy-MM-dd}"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to export logs"); + StatusMessage = $"Error exporting logs: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private async Task CleanupOldLogsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Cleaning up old logs..."; + + await _loggingService.CleanupOldLogsAsync(); + await RefreshStatisticsAsync(); + + StatusMessage = "Old logs cleaned up successfully"; + await _loggingService.LogUserActionAsync("LogsCleanup", "User initiated log cleanup"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to cleanup old logs"); + StatusMessage = $"Error cleaning up logs: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private async Task SaveSettingsAsync() + { + try + { + await _loggingService.UpdateConfigurationAsync(EnableDebugLogging, MaxLogFileSizeMb, LogRetentionDays); + + _settingsService.Settings.EnableDebugLogging = EnableDebugLogging; + _settingsService.Settings.MaxLogFileSizeMb = MaxLogFileSizeMb; + _settingsService.Settings.LogRetentionDays = LogRetentionDays; + + await _settingsService.SaveSettingsAsync(); + + StatusMessage = "Logging settings saved successfully"; + await _loggingService.LogUserActionAsync("LoggingSettingsChanged", + $"Debug: {EnableDebugLogging}, MaxSize: {MaxLogFileSizeMb}MB, Retention: {LogRetentionDays} days"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to save logging settings"); + StatusMessage = $"Error saving settings: {ex.Message}"; + } + } + + private void OpenLogDirectory() + { + try + { + var logDirectory = _loggingService.LogDirectoryPath; + if (Directory.Exists(logDirectory)) + { + System.Diagnostics.Process.Start("explorer.exe", logDirectory); + } + else + { + StatusMessage = "Log directory not found"; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to open log directory"); + StatusMessage = $"Error opening log directory: {ex.Message}"; + } + } + + private void CopyLogEntry(LogEntryDisplayModel? logEntry) + { + if (logEntry == null) return; + + try + { + var logText = $"[{logEntry.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{logEntry.Level}] {logEntry.Category}: {logEntry.Message}"; + if (!string.IsNullOrEmpty(logEntry.Exception)) + { + logText += $"\nException: {logEntry.Exception}"; + } + + System.Windows.Clipboard.SetText(logText); + StatusMessage = "Log entry copied to clipboard"; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to copy log entry to clipboard"); + StatusMessage = "Failed to copy log entry"; + } + } + + private void LoadSettings() + { + var settings = _settingsService.Settings; + EnableDebugLogging = settings.EnableDebugLogging; + MaxLogFileSizeMb = settings.MaxLogFileSizeMb; + LogRetentionDays = settings.LogRetentionDays; + } + + private void StartAutoRefresh() + { + // Implementation for auto-refresh timer would go here + // For now, we'll keep it simple without the timer + } + + partial void OnSearchTextChanged(string value) + { + // Trigger refresh when search text changes + _ = Task.Run(RefreshLogsAsync); + } + + partial void OnSelectedCategoryChanged(string value) + { + // Trigger refresh when category changes + _ = Task.Run(RefreshLogsAsync); + } + + partial void OnSelectedLogLevelChanged(LogLevel value) + { + // Trigger refresh when log level changes + _ = Task.Run(RefreshLogsAsync); + } + } + + /// + /// Display model for log entries in the UI + /// + public class LogEntryDisplayModel + { + public DateTime Timestamp { get; set; } + public LogLevel Level { get; set; } + public string Category { get; set; } = string.Empty; + public string Message { get; set; } = string.Empty; + public string? Exception { get; set; } + public Dictionary Properties { get; set; } = new(); + public string? CorrelationId { get; set; } + + public string LevelColor => Level switch + { + LogLevel.Critical => "#FF0000", + LogLevel.Error => "#FF4444", + LogLevel.Warning => "#FFA500", + LogLevel.Information => "#0066CC", + LogLevel.Debug => "#808080", + LogLevel.Trace => "#C0C0C0", + _ => "#000000" + }; + + public string FormattedTimestamp => Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"); + public string ShortMessage => Message.Length > 100 ? Message.Substring(0, 100) + "..." : Message; + public bool HasException => !string.IsNullOrEmpty(Exception); + public bool HasProperties => Properties.Any(); + } +} diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index 962c5d6..12cc874 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -1,10 +1,218 @@ using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using System; +using System.Threading.Tasks; +using ThreadPilot.Models; +using ThreadPilot.Services; +using ThreadPilot.ViewModels; namespace ThreadPilot { - public partial class MainWindowViewModel : ObservableObject + public partial class MainWindowViewModel : BaseViewModel { + private readonly IGameBoostService? _gameBoostService; + private readonly IProcessMonitorManagerService? _processMonitorManagerService; + private readonly INotificationService? _notificationService; + [ObservableProperty] - private string statusMessage = string.Empty; + private bool isGameBoostActive = false; + + [ObservableProperty] + private string gameBoostStatusText = "Game Boost: Inactive"; + + [ObservableProperty] + private string? currentGameName = null; + + [ObservableProperty] + private bool isProcessMonitoringActive = false; + + [ObservableProperty] + private string processMonitoringStatusText = "Process Monitoring: Inactive"; + + public MainWindowViewModel( + ILogger logger, + IEnhancedLoggingService? enhancedLoggingService = null, + IGameBoostService? gameBoostService = null, + IProcessMonitorManagerService? processMonitorManagerService = null, + INotificationService? notificationService = null) + : base(logger, enhancedLoggingService) + { + _gameBoostService = gameBoostService; + _processMonitorManagerService = processMonitorManagerService; + _notificationService = notificationService; + } + + public override async Task InitializeAsync() + { + await ExecuteAsync(async () => + { + // Subscribe to service events + if (_gameBoostService != null) + { + _gameBoostService.GameBoostActivated += OnGameBoostActivated; + _gameBoostService.GameBoostDeactivated += OnGameBoostDeactivated; + } + + if (_processMonitorManagerService != null) + { + _processMonitorManagerService.ServiceStatusChanged += OnServiceStatusChanged; + } + + // Initialize status + await UpdateStatusAsync(); + + await LogUserActionAsync("MainWindow", "Initialized main window", "Application startup"); + }, "Initializing main window..."); + } + + [RelayCommand] + private async Task ToggleProcessMonitoringAsync() + { + if (_processMonitorManagerService == null) return; + + await ExecuteAsync(async () => + { + if (IsProcessMonitoringActive) + { + await _processMonitorManagerService.StopAsync(); + await LogUserActionAsync("ProcessMonitoring", "Stopped process monitoring", "User action"); + } + else + { + await _processMonitorManagerService.StartAsync(); + await LogUserActionAsync("ProcessMonitoring", "Started process monitoring", "User action"); + } + }, IsProcessMonitoringActive ? "Stopping monitoring..." : "Starting monitoring..."); + } + + [RelayCommand] + private async Task ToggleGameBoostAsync() + { + if (_gameBoostService == null) return; + + await ExecuteAsync(async () => + { + if (IsGameBoostActive) + { + await _gameBoostService.DeactivateGameBoostAsync(); + await LogUserActionAsync("GameBoost", "Deactivated game boost", "User action"); + } + else + { + // Game boost is typically activated automatically, but we can force it + await LogUserActionAsync("GameBoost", "Attempted to activate game boost", "User action"); + } + }, "Toggling game boost..."); + } + + private async Task UpdateStatusAsync() + { + try + { + // Update game boost status + if (_gameBoostService != null) + { + IsGameBoostActive = _gameBoostService.IsGameBoostActive; + CurrentGameName = _gameBoostService.CurrentGameProcess?.Name; + UpdateGameBoostStatusText(); + } + + // Update process monitoring status + if (_processMonitorManagerService != null) + { + IsProcessMonitoringActive = _processMonitorManagerService.IsRunning; + ProcessMonitoringStatusText = IsProcessMonitoringActive + ? "Process Monitoring: Active" + : "Process Monitoring: Inactive"; + } + } + catch (Exception ex) + { + SetError("Failed to update status", ex); + } + } + + private void UpdateGameBoostStatusText() + { + if (IsGameBoostActive && !string.IsNullOrEmpty(CurrentGameName)) + { + GameBoostStatusText = $"Game Boost: Active ({CurrentGameName})"; + } + else if (IsGameBoostActive) + { + GameBoostStatusText = "Game Boost: Active"; + } + else + { + GameBoostStatusText = "Game Boost: Inactive"; + } + } + + public void UpdateGameBoostStatus(bool isActive, string? gameName = null) + { + IsGameBoostActive = isActive; + CurrentGameName = gameName; + UpdateGameBoostStatusText(); + } + + private async void OnGameBoostActivated(object? sender, GameBoostActivatedEventArgs e) + { + IsGameBoostActive = true; + CurrentGameName = e.GameProcess?.Name; + UpdateGameBoostStatusText(); + + if (_notificationService != null) + { + await _notificationService.ShowNotificationAsync( + "Game Boost Activated", + $"Performance boost enabled for {CurrentGameName}", + NotificationType.Information); + } + } + + private async void OnGameBoostDeactivated(object? sender, GameBoostDeactivatedEventArgs e) + { + IsGameBoostActive = false; + CurrentGameName = null; + UpdateGameBoostStatusText(); + + if (_notificationService != null) + { + await _notificationService.ShowNotificationAsync( + "Game Boost Deactivated", + "Performance boost disabled", + NotificationType.Information); + } + } + + private void OnServiceStatusChanged(object? sender, ServiceStatusEventArgs e) + { + IsProcessMonitoringActive = e.IsRunning; + ProcessMonitoringStatusText = $"Process Monitoring: {e.Status}"; + } + + public void UpdateProcessMonitoringStatus(bool isActive, string status) + { + IsProcessMonitoringActive = isActive; + ProcessMonitoringStatusText = $"Process Monitoring: {status}"; + } + + protected override void OnDispose() + { + // Unsubscribe from events + if (_gameBoostService != null) + { + _gameBoostService.GameBoostActivated -= OnGameBoostActivated; + _gameBoostService.GameBoostDeactivated -= OnGameBoostDeactivated; + } + + if (_processMonitorManagerService != null) + { + _processMonitorManagerService.ServiceStatusChanged -= OnServiceStatusChanged; + } + + base.OnDispose(); + } } } \ No newline at end of file diff --git a/ViewModels/PowerPlanViewModel.cs b/ViewModels/PowerPlanViewModel.cs index 3613d38..aab38cf 100644 --- a/ViewModels/PowerPlanViewModel.cs +++ b/ViewModels/PowerPlanViewModel.cs @@ -5,8 +5,10 @@ using System.Threading.Tasks; using System.Windows.Input; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; using ThreadPilot.Models; using ThreadPilot.Services; +using ThreadPilot.ViewModels; namespace ThreadPilot.ViewModels { @@ -30,7 +32,11 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private PowerPlanModel? activePowerPlan; - public PowerPlanViewModel(IPowerPlanService powerPlanService) + public PowerPlanViewModel( + ILogger logger, + IPowerPlanService powerPlanService, + IEnhancedLoggingService? enhancedLoggingService = null) + : base(logger, enhancedLoggingService) { _powerPlanService = powerPlanService; SetupRefreshTimer(); diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs new file mode 100644 index 0000000..08ec072 --- /dev/null +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; +using ThreadPilot.Services; +using ThreadPilot.ViewModels; + +namespace ThreadPilot.ViewModels +{ + public partial class ProcessPowerPlanAssociationViewModel : BaseViewModel + { + private readonly IProcessPowerPlanAssociationService _associationService; + private readonly IPowerPlanService _powerPlanService; + private readonly IProcessService _processService; + private readonly IProcessMonitorManagerService _monitorManagerService; + + [ObservableProperty] + private ObservableCollection associations = new(); + + [ObservableProperty] + private ObservableCollection availablePowerPlans = new(); + + [ObservableProperty] + private ObservableCollection runningProcesses = new(); + + [ObservableProperty] + private ProcessPowerPlanAssociation? selectedAssociation; + + [ObservableProperty] + private PowerPlanModel? selectedPowerPlan; + + [ObservableProperty] + private ProcessModel? selectedProcess; + + [ObservableProperty] + private string newExecutableName = string.Empty; + + [ObservableProperty] + private string newExecutablePath = string.Empty; + + [ObservableProperty] + private bool matchByPath = false; + + [ObservableProperty] + private int priority = 0; + + [ObservableProperty] + private string description = string.Empty; + + [ObservableProperty] + private PowerPlanModel? defaultPowerPlan; + + [ObservableProperty] + private bool isMonitoringEnabled = true; + + [ObservableProperty] + private bool isEventBasedMonitoringEnabled = true; + + [ObservableProperty] + private bool isFallbackPollingEnabled = true; + + [ObservableProperty] + private int pollingIntervalSeconds = 5; + + [ObservableProperty] + private bool preventDuplicatePowerPlanChanges = true; + + [ObservableProperty] + private int powerPlanChangeDelayMs = 1000; + + [ObservableProperty] + private string serviceStatus = "Stopped"; + + [ObservableProperty] + private bool isServiceRunning = false; + + public ProcessPowerPlanAssociationViewModel( + ILogger logger, + IProcessPowerPlanAssociationService associationService, + IPowerPlanService powerPlanService, + IProcessService processService, + IProcessMonitorManagerService monitorManagerService, + IEnhancedLoggingService? enhancedLoggingService = null) + : base(logger, enhancedLoggingService) + { + _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); + _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _processService = processService ?? throw new ArgumentNullException(nameof(processService)); + _monitorManagerService = monitorManagerService ?? throw new ArgumentNullException(nameof(monitorManagerService)); + + // Subscribe to events + _associationService.ConfigurationChanged += OnConfigurationChanged; + _monitorManagerService.ServiceStatusChanged += OnServiceStatusChanged; + _monitorManagerService.ProcessPowerPlanChanged += OnProcessPowerPlanChanged; + + // Initialize + _ = InitializeAsync(); + } + + public override async Task InitializeAsync() + { + await LoadDataAsync(); + UpdateServiceStatus(); + } + + [RelayCommand] + public async Task LoadDataAsync() + { + try + { + SetStatus("Loading data..."); + + // Load associations + var associationsData = await _associationService.GetAssociationsAsync(); + Associations = new ObservableCollection(associationsData); + + // Load power plans + var powerPlans = await _powerPlanService.GetPowerPlansAsync(); + AvailablePowerPlans = powerPlans; + + // Load running processes + var processes = await _processService.GetProcessesAsync(); + RunningProcesses = processes; + + // Load configuration settings + var config = _associationService.Configuration; + IsEventBasedMonitoringEnabled = config.IsEventBasedMonitoringEnabled; + IsFallbackPollingEnabled = config.IsFallbackPollingEnabled; + PollingIntervalSeconds = config.PollingIntervalSeconds; + PreventDuplicatePowerPlanChanges = config.PreventDuplicatePowerPlanChanges; + PowerPlanChangeDelayMs = config.PowerPlanChangeDelayMs; + + // Load default power plan + var (defaultGuid, defaultName) = await _associationService.GetDefaultPowerPlanAsync(); + DefaultPowerPlan = AvailablePowerPlans.FirstOrDefault(p => p.Guid == defaultGuid); + + ClearStatus(); + } + catch (Exception ex) + { + SetStatus($"Error loading data: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task AddAssociationAsync() + { + try + { + if (string.IsNullOrWhiteSpace(NewExecutableName) || SelectedPowerPlan == null) + { + SetStatus("Please enter an executable name and select a power plan", false); + return; + } + + SetStatus("Adding association..."); + + var association = new ProcessPowerPlanAssociation + { + ExecutableName = NewExecutableName.Trim(), + ExecutablePath = NewExecutablePath.Trim(), + PowerPlanGuid = SelectedPowerPlan.Guid, + PowerPlanName = SelectedPowerPlan.Name, + MatchByPath = MatchByPath, + Priority = Priority, + Description = Description.Trim(), + IsEnabled = true + }; + + var success = await _associationService.AddAssociationAsync(association); + if (success) + { + // Clear form + NewExecutableName = string.Empty; + NewExecutablePath = string.Empty; + SelectedPowerPlan = null; + MatchByPath = false; + Priority = 0; + Description = string.Empty; + + await LoadDataAsync(); + SetStatus("Association added successfully"); + } + else + { + SetStatus("Failed to add association - it may already exist", false); + } + } + catch (Exception ex) + { + SetStatus($"Error adding association: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task UpdateAssociationAsync() + { + try + { + if (SelectedAssociation == null) + { + SetStatus("Please select an association to update", false); + return; + } + + SetStatus("Updating association..."); + + var success = await _associationService.UpdateAssociationAsync(SelectedAssociation); + if (success) + { + await LoadDataAsync(); + SetStatus("Association updated successfully"); + } + else + { + SetStatus("Failed to update association", false); + } + } + catch (Exception ex) + { + SetStatus($"Error updating association: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task RemoveAssociationAsync() + { + try + { + if (SelectedAssociation == null) + { + SetStatus("Please select an association to remove", false); + return; + } + + SetStatus("Removing association..."); + + var success = await _associationService.RemoveAssociationAsync(SelectedAssociation.Id); + if (success) + { + await LoadDataAsync(); + SetStatus("Association removed successfully"); + } + else + { + SetStatus("Failed to remove association", false); + } + } + catch (Exception ex) + { + SetStatus($"Error removing association: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task SetDefaultPowerPlanAsync() + { + try + { + if (DefaultPowerPlan == null) + { + SetStatus("Please select a default power plan", false); + return; + } + + SetStatus("Setting default power plan..."); + + var success = await _associationService.SetDefaultPowerPlanAsync(DefaultPowerPlan.Guid, DefaultPowerPlan.Name); + if (success) + { + SetStatus("Default power plan set successfully"); + } + else + { + SetStatus("Failed to set default power plan", false); + } + } + catch (Exception ex) + { + SetStatus($"Error setting default power plan: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task StartMonitoringAsync() + { + try + { + SetStatus("Starting monitoring service..."); + await _monitorManagerService.StartAsync(); + } + catch (Exception ex) + { + SetStatus($"Error starting monitoring: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task StopMonitoringAsync() + { + try + { + SetStatus("Stopping monitoring service..."); + await _monitorManagerService.StopAsync(); + } + catch (Exception ex) + { + SetStatus($"Error stopping monitoring: {ex.Message}", false); + } + } + + [RelayCommand] + public async Task SaveConfigurationAsync() + { + try + { + SetStatus("Saving configuration..."); + + // Update configuration with current settings + var config = _associationService.Configuration; + config.IsEventBasedMonitoringEnabled = IsEventBasedMonitoringEnabled; + config.IsFallbackPollingEnabled = IsFallbackPollingEnabled; + config.PollingIntervalSeconds = PollingIntervalSeconds; + config.PreventDuplicatePowerPlanChanges = PreventDuplicatePowerPlanChanges; + config.PowerPlanChangeDelayMs = PowerPlanChangeDelayMs; + + var success = await _associationService.SaveConfigurationAsync(); + if (success) + { + SetStatus("Configuration saved successfully"); + } + else + { + SetStatus("Failed to save configuration", false); + } + } + catch (Exception ex) + { + SetStatus($"Error saving configuration: {ex.Message}", false); + } + } + + [RelayCommand] + public void UseSelectedProcessForAssociation() + { + if (SelectedProcess != null) + { + NewExecutableName = SelectedProcess.Name; + NewExecutablePath = SelectedProcess.ExecutablePath; + } + } + + private void OnConfigurationChanged(object? sender, ConfigurationChangedEventArgs e) + { + // Reload data when configuration changes + _ = Task.Run(LoadDataAsync); + } + + private void OnServiceStatusChanged(object? sender, ServiceStatusEventArgs e) + { + ServiceStatus = e.Status; + IsServiceRunning = e.IsRunning; + } + + private void OnProcessPowerPlanChanged(object? sender, ProcessPowerPlanChangeEventArgs e) + { + // Update status when power plan changes occur + SetStatus($"Power plan changed: {e.NewPowerPlan?.Name} for {e.Process.Name}"); + } + + private void UpdateServiceStatus() + { + ServiceStatus = _monitorManagerService.Status; + IsServiceRunning = _monitorManagerService.IsRunning; + } + } +} diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index fbdf3b2..47ada2c 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using System.Windows.Input; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; using ThreadPilot.Models; using ThreadPilot.Services; @@ -14,6 +15,9 @@ namespace ThreadPilot.ViewModels public partial class ProcessViewModel : BaseViewModel { private readonly IProcessService _processService; + private readonly ICpuTopologyService _cpuTopologyService; + private readonly IPowerPlanService _powerPlanService; + private readonly ISystemTrayService _systemTrayService; private System.Timers.Timer? _refreshTimer; [ObservableProperty] @@ -31,94 +35,211 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private string profileName = string.Empty; - // CPU Affinity checkbox properties + // CPU Topology and Affinity [ObservableProperty] - private bool isCpu0Selected; - [ObservableProperty] - private bool isCpu1Selected; - [ObservableProperty] - private bool isCpu2Selected; - [ObservableProperty] - private bool isCpu3Selected; - [ObservableProperty] - private bool isCpu4Selected; - [ObservableProperty] - private bool isCpu5Selected; - [ObservableProperty] - private bool isCpu6Selected; - [ObservableProperty] - private bool isCpu7Selected; - [ObservableProperty] - private bool isCpu8Selected; - [ObservableProperty] - private bool isCpu9Selected; - [ObservableProperty] - private bool isCpu10Selected; - [ObservableProperty] - private bool isCpu11Selected; - [ObservableProperty] - private bool isCpu12Selected; - [ObservableProperty] - private bool isCpu13Selected; - [ObservableProperty] - private bool isCpu14Selected; - [ObservableProperty] - private bool isCpu15Selected; + private CpuTopologyModel? cpuTopology; - public ProcessViewModel(IProcessService processService) + [ObservableProperty] + private ObservableCollection cpuCores = new(); + + [ObservableProperty] + private ObservableCollection affinityPresets = new(); + + [ObservableProperty] + private bool isTopologyDetectionSuccessful = false; + + [ObservableProperty] + private string topologyStatus = "Detecting CPU topology..."; + + [ObservableProperty] + private bool areAdvancedFeaturesAvailable = false; + + [ObservableProperty] + private PowerPlanModel? selectedPowerPlan; + + [ObservableProperty] + private ObservableCollection powerPlans = new(); + + [ObservableProperty] + private bool enableHyperThreading = true; + + public ProcessViewModel( + ILogger logger, + IProcessService processService, + ICpuTopologyService cpuTopologyService, + IPowerPlanService powerPlanService, + ISystemTrayService systemTrayService, + IEnhancedLoggingService? enhancedLoggingService = null) + : base(logger, enhancedLoggingService) { - _processService = processService; + _processService = processService ?? throw new ArgumentNullException(nameof(processService)); + _cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService)); + _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _systemTrayService = systemTrayService ?? throw new ArgumentNullException(nameof(systemTrayService)); + + // Subscribe to topology detection events + _cpuTopologyService.TopologyDetected += OnTopologyDetected; + + // Subscribe to system tray events + _systemTrayService.QuickApplyRequested += OnTrayQuickApplyRequested; + SetupRefreshTimer(); + _ = InitializeAsync(); + } + + public override async Task InitializeAsync() + { + try + { + SetStatus("Initializing CPU topology and power plans..."); + + // Initialize CPU topology + await _cpuTopologyService.DetectTopologyAsync(); + + // Load power plans + await LoadPowerPlansAsync(); + + // Load processes automatically on startup (Bug #8 fix) + await LoadProcessesCommand.ExecuteAsync(null); + + // Start refresh timer for real-time updates + _refreshTimer?.Start(); + } + catch (Exception ex) + { + SetStatus($"Failed to initialize: {ex.Message}", false); + } + } + + private async Task LoadPowerPlansAsync() + { + try + { + var plans = await _powerPlanService.GetPowerPlansAsync(); + PowerPlans.Clear(); + foreach (var plan in plans) + { + PowerPlans.Add(plan); + } + + // Set current active power plan as selected + var activePlan = await _powerPlanService.GetActivePowerPlan(); + SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid); + } + catch (Exception ex) + { + SetStatus($"Failed to load power plans: {ex.Message}", false); + } } partial void OnSelectedProcessChanged(ProcessModel? value) { - if (value != null) + if (value != null && CpuTopology != null) { - UpdateAffinityCheckboxes(value.ProcessorAffinity); + // Refresh process info to get current affinity + _ = Task.Run(async () => + { + try + { + await _processService.RefreshProcessInfo(value); + // Update UI on main thread + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + UpdateCoreSelections(value.ProcessorAffinity); + }); + } + catch (Exception ex) + { + Logger.LogWarning(ex, "Failed to refresh process info for {ProcessName}", value.Name); + } + }); + } + + // Update system tray context menu + _systemTrayService.UpdateContextMenu(value?.Name, value != null); + } + + private async void OnTrayQuickApplyRequested(object? sender, EventArgs e) + { + try + { + await QuickApplyAffinityAndPowerPlanCommand.ExecuteAsync(null); + _systemTrayService.ShowBalloonTip("ThreadPilot", + $"Settings applied to {SelectedProcess?.Name ?? "selected process"}", 2000); + } + catch (Exception ex) + { + _systemTrayService.ShowBalloonTip("ThreadPilot Error", + $"Failed to apply settings: {ex.Message}", 3000); } } - private void UpdateAffinityCheckboxes(long affinityMask) + private void OnTopologyDetected(object? sender, CpuTopologyDetectedEventArgs e) { - IsCpu0Selected = (affinityMask & 1L) != 0; - IsCpu1Selected = (affinityMask & 2L) != 0; - IsCpu2Selected = (affinityMask & 4L) != 0; - IsCpu3Selected = (affinityMask & 8L) != 0; - IsCpu4Selected = (affinityMask & 16L) != 0; - IsCpu5Selected = (affinityMask & 32L) != 0; - IsCpu6Selected = (affinityMask & 64L) != 0; - IsCpu7Selected = (affinityMask & 128L) != 0; - IsCpu8Selected = (affinityMask & 256L) != 0; - IsCpu9Selected = (affinityMask & 512L) != 0; - IsCpu10Selected = (affinityMask & 1024L) != 0; - IsCpu11Selected = (affinityMask & 2048L) != 0; - IsCpu12Selected = (affinityMask & 4096L) != 0; - IsCpu13Selected = (affinityMask & 8192L) != 0; - IsCpu14Selected = (affinityMask & 16384L) != 0; - IsCpu15Selected = (affinityMask & 32768L) != 0; + CpuTopology = e.Topology; + IsTopologyDetectionSuccessful = e.DetectionSuccessful; + + if (e.DetectionSuccessful) + { + TopologyStatus = $"Detected: {e.Topology.TotalLogicalCores} logical cores, " + + $"{e.Topology.TotalPhysicalCores} physical cores"; + AreAdvancedFeaturesAvailable = e.Topology.HasIntelHybrid || e.Topology.HasAmdCcd || e.Topology.HasHyperThreading; + } + else + { + TopologyStatus = $"Detection failed: {e.ErrorMessage ?? "Unknown error"}"; + AreAdvancedFeaturesAvailable = false; + } + + UpdateCpuCores(); + UpdateAffinityPresets(); + } + + private void UpdateCpuCores() + { + if (CpuTopology == null) return; + + CpuCores.Clear(); + foreach (var core in CpuTopology.LogicalCores) + { + CpuCores.Add(core); + } + } + + private void UpdateAffinityPresets() + { + AffinityPresets.Clear(); + var presets = _cpuTopologyService.GetAffinityPresets(); + foreach (var preset in presets) + { + AffinityPresets.Add(preset); + } + } + + private void UpdateCoreSelections(long affinityMask) + { + if (CpuTopology == null) return; + + foreach (var core in CpuCores) + { + core.IsSelected = (affinityMask & core.AffinityMask) != 0; + } } private long CalculateAffinityMask() { - long mask = 0; - if (IsCpu0Selected) mask |= 1L; - if (IsCpu1Selected) mask |= 2L; - if (IsCpu2Selected) mask |= 4L; - if (IsCpu3Selected) mask |= 8L; - if (IsCpu4Selected) mask |= 16L; - if (IsCpu5Selected) mask |= 32L; - if (IsCpu6Selected) mask |= 64L; - if (IsCpu7Selected) mask |= 128L; - if (IsCpu8Selected) mask |= 256L; - if (IsCpu9Selected) mask |= 512L; - if (IsCpu10Selected) mask |= 1024L; - if (IsCpu11Selected) mask |= 2048L; - if (IsCpu12Selected) mask |= 4096L; - if (IsCpu13Selected) mask |= 8192L; - if (IsCpu14Selected) mask |= 16384L; - if (IsCpu15Selected) mask |= 32768L; - return mask; + if (CpuTopology == null) return 0; + + var selectedCores = CpuCores.Where(core => core.IsSelected); + + // If HyperThreading is disabled, exclude HT siblings + if (!EnableHyperThreading && CpuTopology.HasHyperThreading) + { + selectedCores = selectedCores.Where(core => !core.IsHyperThreaded || core.HyperThreadSibling == null || + core.LogicalCoreId < core.HyperThreadSibling); + } + + return selectedCores.Aggregate(0L, (mask, core) => mask | core.AffinityMask); } [RelayCommand] @@ -186,9 +307,26 @@ namespace ThreadPilot.ViewModels try { var affinityMask = CalculateAffinityMask(); + if (affinityMask == 0) + { + SetStatus("Please select at least one CPU core", false); + return; + } + SetStatus($"Setting affinity for {SelectedProcess.Name}..."); await _processService.SetProcessorAffinity(SelectedProcess, affinityMask); - ClearStatus(); + + // Refresh the process to get updated affinity from system + await _processService.RefreshProcessInfo(SelectedProcess); + + // Update UI to reflect the actual system affinity + UpdateCoreSelections(SelectedProcess.ProcessorAffinity); + + // Notify UI of changes + OnPropertyChanged(nameof(SelectedProcess)); + OnPropertyChanged(nameof(CpuCores)); + + SetStatus($"Affinity set successfully for {SelectedProcess.Name}"); } catch (Exception ex) { @@ -196,6 +334,176 @@ namespace ThreadPilot.ViewModels } } + [RelayCommand] + private void ApplyAffinityPreset(CpuAffinityPreset preset) + { + if (preset == null || !preset.IsAvailable || CpuTopology == null) return; + + // Clear all selections first + foreach (var core in CpuCores) + { + core.IsSelected = false; + } + + // Apply preset mask + foreach (var core in CpuCores) + { + core.IsSelected = (preset.AffinityMask & core.AffinityMask) != 0; + } + + // Notify UI of changes + OnPropertyChanged(nameof(CpuCores)); + SetStatus($"Applied preset: {preset.Name}"); + } + + [RelayCommand] + private void SelectAllCores() + { + foreach (var core in CpuCores) + { + core.IsSelected = true; + } + OnPropertyChanged(nameof(CpuCores)); + SetStatus("Selected all CPU cores"); + } + + [RelayCommand] + private void SelectPhysicalCoresOnly() + { + if (CpuTopology == null) return; + + foreach (var core in CpuCores) + { + core.IsSelected = false; + } + + foreach (var physicalCore in CpuTopology.PhysicalCores) + { + var coreModel = CpuCores.FirstOrDefault(c => c.LogicalCoreId == physicalCore.LogicalCoreId); + if (coreModel != null) + { + coreModel.IsSelected = true; + } + } + + OnPropertyChanged(nameof(CpuCores)); + SetStatus("Selected physical cores only (no HyperThreading)"); + } + + [RelayCommand] + private void SelectPerformanceCores() + { + if (CpuTopology == null || !CpuTopology.HasIntelHybrid) return; + + foreach (var core in CpuCores) + { + core.IsSelected = core.CoreType == CpuCoreType.PerformanceCore; + } + + OnPropertyChanged(nameof(CpuCores)); + SetStatus("Selected Intel Performance cores (P-cores)"); + } + + [RelayCommand] + private void SelectEfficiencyCores() + { + if (CpuTopology == null || !CpuTopology.HasIntelHybrid) return; + + foreach (var core in CpuCores) + { + core.IsSelected = core.CoreType == CpuCoreType.EfficiencyCore; + } + + OnPropertyChanged(nameof(CpuCores)); + SetStatus("Selected Intel Efficiency cores (E-cores)"); + } + + [RelayCommand] + private void SelectCcdCores(int ccdId) + { + if (CpuTopology == null || !CpuTopology.HasAmdCcd) return; + + foreach (var core in CpuCores) + { + core.IsSelected = core.CcdId == ccdId; + } + + OnPropertyChanged(nameof(CpuCores)); + SetStatus($"Selected AMD CCD {ccdId} cores"); + } + + [RelayCommand] + private void ClearCoreSelection() + { + foreach (var core in CpuCores) + { + core.IsSelected = false; + } + OnPropertyChanged(nameof(CpuCores)); + SetStatus("Cleared CPU core selection"); + } + + [RelayCommand] + private async Task QuickApplyAffinityAndPowerPlan() + { + if (SelectedProcess == null) return; + + try + { + SetStatus($"Applying settings to {SelectedProcess.Name}..."); + + // Apply CPU affinity + var affinityMask = CalculateAffinityMask(); + if (affinityMask > 0) + { + await _processService.SetProcessorAffinity(SelectedProcess, affinityMask); + } + + // Apply power plan if selected + if (SelectedPowerPlan != null) + { + await _powerPlanService.SetActivePowerPlan(SelectedPowerPlan); + } + + SetStatus($"Settings applied successfully to {SelectedProcess.Name}"); + } + catch (Exception ex) + { + SetStatus($"Error applying settings: {ex.Message}", false); + } + } + + [RelayCommand] + private async Task RefreshTopology() + { + try + { + SetStatus("Refreshing CPU topology..."); + await _cpuTopologyService.RefreshTopologyAsync(); + } + catch (Exception ex) + { + SetStatus($"Error refreshing topology: {ex.Message}", false); + } + } + + [RelayCommand] + private async Task SetPowerPlan() + { + if (SelectedPowerPlan == null) return; + + try + { + SetStatus($"Setting power plan to {SelectedPowerPlan.Name}..."); + await _powerPlanService.SetActivePowerPlan(SelectedPowerPlan); + SetStatus($"Power plan set to {SelectedPowerPlan.Name}"); + } + catch (Exception ex) + { + SetStatus($"Error setting power plan: {ex.Message}", false); + } + } + [RelayCommand] private async Task SetPriority(ProcessPriorityClass priority) { @@ -251,7 +559,19 @@ namespace ThreadPilot.ViewModels { _refreshTimer = new System.Timers.Timer(2000); // 2 second refresh _refreshTimer.Elapsed += async (s, e) => await RefreshProcessesCommand.ExecuteAsync(null); - _refreshTimer.Start(); + // Don't start automatically - only start when needed + } + + public void PauseRefresh() + { + _refreshTimer?.Stop(); + SetStatus("Process monitoring paused (minimized)"); + } + + public void ResumeRefresh() + { + _refreshTimer?.Start(); + SetStatus("Process monitoring resumed"); } partial void OnSearchTextChanged(string value) diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..a6a862e --- /dev/null +++ b/ViewModels/SettingsViewModel.cs @@ -0,0 +1,431 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; +using ThreadPilot.Services; + +namespace ThreadPilot.ViewModels +{ + /// + /// ViewModel for application settings + /// + public partial class SettingsViewModel : BaseViewModel + { + private readonly IApplicationSettingsService _settingsService; + private readonly INotificationService _notificationService; + private readonly IAutostartService _autostartService; + private readonly IPowerPlanService _powerPlanService; + private readonly IGameBoostService _gameBoostService; + private readonly IProcessMonitorManagerService _processMonitorManagerService; + + [ObservableProperty] + private ApplicationSettingsModel settings; + + [ObservableProperty] + private bool hasUnsavedChanges = false; + + [ObservableProperty] + private bool isLoading = false; + + [ObservableProperty] + private string statusMessage = string.Empty; + + [ObservableProperty] + private ObservableCollection availablePowerPlans = new(); + + [ObservableProperty] + private ObservableCollection knownGameExecutables = new(); + + [ObservableProperty] + private string newGameExecutableName = string.Empty; + + [ObservableProperty] + private string? selectedKnownGame; + + public ICommand SaveSettingsCommand { get; } + public ICommand ResetToDefaultsCommand { get; } + public ICommand ExportSettingsCommand { get; } + public ICommand ImportSettingsCommand { get; } + public ICommand TestNotificationCommand { get; } + public ICommand RefreshPowerPlansCommand { get; } + public ICommand AddKnownGameCommand { get; } + public ICommand RemoveKnownGameCommand { get; } + + public SettingsViewModel( + ILogger logger, + IApplicationSettingsService settingsService, + INotificationService notificationService, + IAutostartService autostartService, + IPowerPlanService powerPlanService, + IGameBoostService gameBoostService, + IProcessMonitorManagerService processMonitorManagerService, + IEnhancedLoggingService? enhancedLoggingService = null) + : base(logger, enhancedLoggingService) + { + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); + _autostartService = autostartService ?? throw new ArgumentNullException(nameof(autostartService)); + _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _gameBoostService = gameBoostService ?? throw new ArgumentNullException(nameof(gameBoostService)); + _processMonitorManagerService = processMonitorManagerService ?? throw new ArgumentNullException(nameof(processMonitorManagerService)); + + // Initialize with current settings + settings = (ApplicationSettingsModel)_settingsService.Settings.Clone(); + + // Initialize commands + SaveSettingsCommand = new AsyncRelayCommand(SaveSettingsAsync); + ResetToDefaultsCommand = new AsyncRelayCommand(ResetToDefaultsAsync); + ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync); + ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync); + TestNotificationCommand = new AsyncRelayCommand(TestNotificationAsync); + RefreshPowerPlansCommand = new AsyncRelayCommand(RefreshPowerPlansAsync); + AddKnownGameCommand = new AsyncRelayCommand(AddKnownGameAsync, CanAddKnownGame); + RemoveKnownGameCommand = new AsyncRelayCommand(RemoveKnownGameAsync, CanRemoveKnownGame); + + // Subscribe to property changes to track unsaved changes + Settings.PropertyChanged += OnSettingsPropertyChanged; + PropertyChanged += OnViewModelPropertyChanged; + + // Initialize data + _ = Task.Run(RefreshPowerPlansAsync); + _ = Task.Run(LoadKnownGamesAsync); + + Logger.LogInformation("Settings ViewModel initialized"); + } + + private void OnSettingsPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + HasUnsavedChanges = true; + StatusMessage = "Settings have been modified"; + } + + private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(NewGameExecutableName)) + { + ((AsyncRelayCommand)AddKnownGameCommand).NotifyCanExecuteChanged(); + } + else if (e.PropertyName == nameof(SelectedKnownGame)) + { + ((AsyncRelayCommand)RemoveKnownGameCommand).NotifyCanExecuteChanged(); + } + } + + private async Task SaveSettingsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Saving settings..."; + + // Handle autostart setting + if (Settings.AutostartWithWindows != _settingsService.Settings.AutostartWithWindows) + { + if (Settings.AutostartWithWindows) + { + await _autostartService.EnableAutostartAsync(Settings.StartMinimized); + } + else + { + await _autostartService.DisableAutostartAsync(); + } + } + + await _settingsService.UpdateSettingsAsync(Settings); + + // Update monitoring services with new settings + _processMonitorManagerService.UpdateSettings(); + + HasUnsavedChanges = false; + StatusMessage = "Settings saved successfully"; + + await _notificationService.ShowSuccessNotificationAsync( + "Settings Saved", + "Application settings have been saved successfully"); + + Logger.LogInformation("Settings saved successfully"); + } + catch (Exception ex) + { + StatusMessage = $"Error saving settings: {ex.Message}"; + Logger.LogError(ex, "Error saving settings"); + + await _notificationService.ShowErrorNotificationAsync( + "Settings Error", + "Failed to save settings", + ex); + } + finally + { + IsLoading = false; + } + } + + private async Task ResetToDefaultsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Resetting to defaults..."; + + var defaultSettings = new ApplicationSettingsModel(); + Settings.CopyFrom(defaultSettings); + + HasUnsavedChanges = true; + StatusMessage = "Settings reset to defaults (not saved yet)"; + + Logger.LogInformation("Settings reset to defaults"); + } + catch (Exception ex) + { + StatusMessage = $"Error resetting settings: {ex.Message}"; + Logger.LogError(ex, "Error resetting settings"); + } + finally + { + IsLoading = false; + } + } + + private async Task ExportSettingsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Exporting settings..."; + + // In a real implementation, you would show a file dialog + var exportPath = System.IO.Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + $"ThreadPilot_Settings_{DateTime.Now:yyyyMMdd_HHmmss}.json"); + + await _settingsService.ExportSettingsAsync(exportPath); + + StatusMessage = $"Settings exported to: {exportPath}"; + + await _notificationService.ShowSuccessNotificationAsync( + "Settings Exported", + $"Settings exported to {System.IO.Path.GetFileName(exportPath)}"); + + Logger.LogInformation("Settings exported to {Path}", exportPath); + } + catch (Exception ex) + { + StatusMessage = $"Error exporting settings: {ex.Message}"; + Logger.LogError(ex, "Error exporting settings"); + + await _notificationService.ShowErrorNotificationAsync( + "Export Error", + "Failed to export settings", + ex); + } + finally + { + IsLoading = false; + } + } + + private async Task ImportSettingsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Importing settings..."; + + // In a real implementation, you would show a file dialog + // For now, we'll just show a message + StatusMessage = "Import feature requires file dialog implementation"; + + Logger.LogInformation("Import settings requested"); + } + catch (Exception ex) + { + StatusMessage = $"Error importing settings: {ex.Message}"; + Logger.LogError(ex, "Error importing settings"); + } + finally + { + IsLoading = false; + } + } + + private async Task TestNotificationAsync() + { + try + { + await _notificationService.ShowNotificationAsync( + "Test Notification", + "This is a test notification to verify your settings are working correctly.", + NotificationType.Information); + + StatusMessage = "Test notification sent"; + Logger.LogInformation("Test notification sent"); + } + catch (Exception ex) + { + StatusMessage = $"Error sending test notification: {ex.Message}"; + Logger.LogError(ex, "Error sending test notification"); + } + } + + /// + /// Refreshes settings from the service + /// + public async Task RefreshSettingsAsync() + { + try + { + IsLoading = true; + StatusMessage = "Loading settings..."; + + await _settingsService.LoadSettingsAsync(); + Settings.CopyFrom(_settingsService.Settings); + + HasUnsavedChanges = false; + StatusMessage = "Settings loaded"; + + Logger.LogInformation("Settings refreshed"); + } + catch (Exception ex) + { + StatusMessage = $"Error loading settings: {ex.Message}"; + Logger.LogError(ex, "Error loading settings"); + } + finally + { + IsLoading = false; + } + } + + /// + /// Checks if there are unsaved changes + /// + public bool CanClose() + { + return !HasUnsavedChanges; + } + + private async Task RefreshPowerPlansAsync() + { + try + { + var powerPlans = await _powerPlanService.GetPowerPlansAsync(); + + AvailablePowerPlans.Clear(); + foreach (var plan in powerPlans) + { + AvailablePowerPlans.Add(plan); + } + + Logger.LogDebug("Refreshed {Count} power plans", AvailablePowerPlans.Count); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to refresh power plans"); + } + } + + /// + /// Loads known games from the GameBoostService + /// + private async Task LoadKnownGamesAsync() + { + try + { + var knownGames = _gameBoostService.GetKnownGameExecutables(); + KnownGameExecutables.Clear(); + foreach (var game in knownGames) + { + KnownGameExecutables.Add(game); + } + Logger.LogDebug("Loaded {Count} known games", KnownGameExecutables.Count); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error loading known games"); + } + } + + /// + /// Adds a new known game executable + /// + private async Task AddKnownGameAsync() + { + try + { + if (string.IsNullOrWhiteSpace(NewGameExecutableName)) + return; + + var success = await _gameBoostService.AddKnownGameAsync(NewGameExecutableName); + if (success) + { + await LoadKnownGamesAsync(); + var gameName = NewGameExecutableName; + NewGameExecutableName = string.Empty; + StatusMessage = $"Added game: {gameName}"; + Logger.LogInformation("Added known game: {GameName}", gameName); + } + else + { + StatusMessage = "Game already exists or invalid name"; + } + } + catch (Exception ex) + { + StatusMessage = $"Error adding game: {ex.Message}"; + Logger.LogError(ex, "Error adding known game: {GameName}", NewGameExecutableName); + } + } + + /// + /// Removes the selected known game executable + /// + private async Task RemoveKnownGameAsync() + { + try + { + if (string.IsNullOrWhiteSpace(SelectedKnownGame)) + return; + + var gameName = SelectedKnownGame; + var success = await _gameBoostService.RemoveKnownGameAsync(gameName); + if (success) + { + await LoadKnownGamesAsync(); + SelectedKnownGame = null; + StatusMessage = $"Removed game: {gameName}"; + Logger.LogInformation("Removed known game: {GameName}", gameName); + } + else + { + StatusMessage = "Game not found"; + } + } + catch (Exception ex) + { + StatusMessage = $"Error removing game: {ex.Message}"; + Logger.LogError(ex, "Error removing known game: {GameName}", SelectedKnownGame); + } + } + + /// + /// Determines if a new game can be added + /// + private bool CanAddKnownGame() + { + return !string.IsNullOrWhiteSpace(NewGameExecutableName); + } + + /// + /// Determines if the selected game can be removed + /// + private bool CanRemoveKnownGame() + { + return !string.IsNullOrWhiteSpace(SelectedKnownGame); + } + } +} diff --git a/ViewModels/ViewModelFactory.cs b/ViewModels/ViewModelFactory.cs new file mode 100644 index 0000000..d71668c --- /dev/null +++ b/ViewModels/ViewModelFactory.cs @@ -0,0 +1,129 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using ThreadPilot.Services; + +namespace ThreadPilot.ViewModels +{ + /// + /// Factory for creating and managing ViewModel instances + /// + public interface IViewModelFactory + { + /// + /// Create a ViewModel instance of the specified type + /// + T CreateViewModel() where T : BaseViewModel; + + /// + /// Create a ViewModel instance with initialization + /// + Task CreateAndInitializeViewModelAsync() where T : BaseViewModel; + + /// + /// Dispose all managed ViewModels + /// + void DisposeAllViewModels(); + } + + /// + /// Implementation of ViewModel factory with dependency injection support + /// + public class ViewModelFactory : IViewModelFactory, IDisposable + { + private readonly IServiceProvider _serviceProvider; + private readonly ILogger _logger; + private readonly List _managedViewModels = new(); + private bool _disposed; + + public ViewModelFactory(IServiceProvider serviceProvider, ILogger logger) + { + _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public T CreateViewModel() where T : BaseViewModel + { + try + { + var viewModel = _serviceProvider.GetRequiredService(); + _managedViewModels.Add(viewModel); + + _logger.LogDebug("Created ViewModel of type {ViewModelType}", typeof(T).Name); + return viewModel; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create ViewModel of type {ViewModelType}", typeof(T).Name); + throw; + } + } + + public async Task CreateAndInitializeViewModelAsync() where T : BaseViewModel + { + var viewModel = CreateViewModel(); + + try + { + await viewModel.InitializeAsync(); + _logger.LogDebug("Initialized ViewModel of type {ViewModelType}", typeof(T).Name); + return viewModel; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize ViewModel of type {ViewModelType}", typeof(T).Name); + + // Dispose the failed ViewModel + viewModel.Dispose(); + _managedViewModels.Remove(viewModel); + + throw; + } + } + + public void DisposeAllViewModels() + { + _logger.LogInformation("Disposing all managed ViewModels"); + + foreach (var viewModel in _managedViewModels) + { + try + { + viewModel.Dispose(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error disposing ViewModel {ViewModelType}", viewModel.GetType().Name); + } + } + + _managedViewModels.Clear(); + _logger.LogInformation("All managed ViewModels disposed"); + } + + public void Dispose() + { + if (!_disposed) + { + DisposeAllViewModels(); + _disposed = true; + } + } + } + + /// + /// Extension methods for ViewModel factory registration + /// + public static class ViewModelFactoryExtensions + { + /// + /// Register ViewModel factory in dependency injection container + /// + public static IServiceCollection AddViewModelFactory(this IServiceCollection services) + { + services.AddSingleton(); + return services; + } + } +} diff --git a/Views/LogViewerView.xaml b/Views/LogViewerView.xaml new file mode 100644 index 0000000..300cdf5 --- /dev/null +++ b/Views/LogViewerView.xaml @@ -0,0 +1,340 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +