Add process management, settings, and logging features
Introduces new models, services, and view models for process monitoring, power plan association, application settings, and enhanced logging. Updates main application files and views to support new features. Adds developer and architecture documentation.
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
# Advanced CPU Core Detection and Affinity Selection
|
||||
|
||||
## Overview
|
||||
|
||||
ThreadPilot now includes advanced CPU topology detection and dynamic core selection capabilities, supporting modern CPU architectures including multi-socket systems, AMD CCD (Core Complex Die), Intel Hybrid (P-core/E-core), and SMT/HyperThreading.
|
||||
|
||||
## Features
|
||||
|
||||
### 🔍 CPU Topology Detection
|
||||
- **Automatic Detection**: Uses WMI (Windows Management Instrumentation) to detect CPU topology
|
||||
- **Fallback Support**: Graceful degradation when advanced topology information is unavailable
|
||||
- **Real-time Updates**: Event-driven topology detection with UI updates
|
||||
- **Architecture Support**:
|
||||
- Intel Hybrid (Performance + Efficiency cores)
|
||||
- AMD CCD (Core Complex Die) detection
|
||||
- SMT/HyperThreading identification
|
||||
- Multi-socket systems
|
||||
|
||||
### 🎯 Quick Selection Controls
|
||||
- **All Cores**: Select all available CPU cores
|
||||
- **Physical Cores Only**: Select only physical cores (excludes hyperthreaded siblings)
|
||||
- **Performance Cores**: Select Intel P-cores only (Intel Hybrid)
|
||||
- **Efficiency Cores**: Select Intel E-cores only (Intel Hybrid)
|
||||
- **CCD Selection**: Select cores from specific CCDs (AMD processors)
|
||||
|
||||
### 🖥️ Dynamic UI
|
||||
- **Adaptive Interface**: CPU core grid adapts to detected topology
|
||||
- **Visual Indicators**: Color-coded core types and status
|
||||
- **Topology Status**: Real-time display of detection success/failure
|
||||
- **Scrollable Grid**: Supports systems with many CPU cores
|
||||
|
||||
### ⚡ Power Plan Integration
|
||||
- **Combined Application**: Apply both CPU affinity and power plan in one action
|
||||
- **Quick Apply**: Fast reapplication of settings to selected processes
|
||||
- **System Tray**: Context menu for quick access without opening main window
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage
|
||||
1. **Select a Process**: Choose a process from the process list
|
||||
2. **View Topology**: CPU topology is automatically detected and displayed
|
||||
3. **Select Cores**: Use quick selection buttons or manually select individual cores
|
||||
4. **Apply Settings**: Use "Apply Affinity" or "Quick Apply Affinity & Power Plan"
|
||||
|
||||
### Quick Selection Buttons
|
||||
- **All Cores**: Selects all available CPU cores
|
||||
- **Physical Only**: Selects only physical cores (useful for avoiding HT conflicts)
|
||||
- **P-Cores**: Selects Intel Performance cores (Intel 12th gen+)
|
||||
- **E-Cores**: Selects Intel Efficiency cores (Intel 12th gen+)
|
||||
- **CCD 0/1/2...**: Selects cores from specific AMD CCDs
|
||||
|
||||
### System Tray Integration
|
||||
- **Quick Apply**: Right-click tray icon → "Quick Apply to [ProcessName]"
|
||||
- **Show Window**: Double-click tray icon or right-click → "Show ThreadPilot"
|
||||
- **Minimize to Tray**: Window minimizes to system tray instead of taskbar
|
||||
|
||||
## Technical Details
|
||||
|
||||
### CPU Topology Models
|
||||
- **CpuTopologyModel**: Main topology container with architecture detection
|
||||
- **CpuCoreModel**: Individual core representation with type and topology info
|
||||
- **CpuAffinityPreset**: Pre-configured affinity selections for quick access
|
||||
|
||||
### Services
|
||||
- **ICpuTopologyService**: Interface for CPU topology detection and management
|
||||
- **CpuTopologyService**: WMI-based implementation with fallback mechanisms
|
||||
- **ISystemTrayService**: System tray icon and context menu management
|
||||
|
||||
### Architecture Detection
|
||||
- **Intel Hybrid**: Detects P-cores and E-cores using WMI processor information
|
||||
- **AMD CCD**: Identifies Core Complex Dies for NUMA-aware core selection
|
||||
- **SMT/HyperThreading**: Distinguishes physical cores from logical threads
|
||||
- **Multi-socket**: Supports systems with multiple CPU sockets
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Mode
|
||||
Run the application with `--test` parameter to execute CPU topology detection tests:
|
||||
```
|
||||
ThreadPilot.exe --test
|
||||
```
|
||||
|
||||
### Manual Testing
|
||||
1. Open ThreadPilot
|
||||
2. Navigate to Process Management tab
|
||||
3. Select any process
|
||||
4. Verify CPU topology detection status
|
||||
5. Test quick selection buttons
|
||||
6. Apply affinity settings and verify they take effect
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Topology Detection Failed
|
||||
- **Cause**: WMI access restrictions or unsupported hardware
|
||||
- **Solution**: Run as Administrator or use fallback mode
|
||||
- **Fallback**: Basic core enumeration without advanced features
|
||||
|
||||
### Quick Selection Not Working
|
||||
- **Cause**: No process selected or topology detection failed
|
||||
- **Solution**: Select a process and ensure topology detection succeeded
|
||||
- **Check**: Topology status indicator in the UI
|
||||
|
||||
### System Tray Not Visible
|
||||
- **Cause**: Windows Forms package not available or permissions issue
|
||||
- **Solution**: Ensure System.Windows.Forms package is installed
|
||||
- **Alternative**: Use main window controls
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
- **WMI Queries**: Topology detection uses cached results to minimize overhead
|
||||
- **UI Updates**: Core selection changes are batched for better performance
|
||||
- **Memory Usage**: Topology models are lightweight and reused across processes
|
||||
- **Background Detection**: Topology detection runs asynchronously without blocking UI
|
||||
|
||||
## Compatibility
|
||||
|
||||
- **Windows Version**: Windows 7 or later (WMI support required)
|
||||
- **CPU Support**: Intel and AMD processors with standard WMI interfaces
|
||||
- **Architecture**: x64 and ARM64 (where WMI topology data is available)
|
||||
- **.NET Version**: .NET 9.0 or later
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- **NUMA Awareness**: Automatic NUMA node detection and optimization
|
||||
- **Performance Monitoring**: Real-time CPU usage per core type
|
||||
- **Profile Management**: Save/load CPU affinity profiles
|
||||
- **Scheduler Integration**: Windows scheduler hint optimization
|
||||
- **Advanced Presets**: Custom affinity patterns for specific workloads
|
||||
@@ -0,0 +1,318 @@
|
||||
# ThreadPilot API Reference
|
||||
|
||||
## Core Interfaces
|
||||
|
||||
### ISystemService
|
||||
Base interface for all system services providing lifecycle management.
|
||||
|
||||
```csharp
|
||||
public interface ISystemService
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
Task InitializeAsync();
|
||||
Task DisposeAsync();
|
||||
}
|
||||
```
|
||||
|
||||
**Key Methods:**
|
||||
- `InitializeAsync()`: Initialize service resources
|
||||
- `DisposeAsync()`: Clean up service resources
|
||||
- `IsAvailable`: Indicates if service is operational
|
||||
|
||||
### IRepository<T>
|
||||
Generic repository interface for data access operations.
|
||||
|
||||
```csharp
|
||||
public interface IRepository<T> : IRepository<T, string> where T : class
|
||||
{
|
||||
Task<T?> GetByIdAsync(string id);
|
||||
Task<IEnumerable<T>> GetAllAsync();
|
||||
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
|
||||
Task<T> AddAsync(T entity);
|
||||
Task<T> UpdateAsync(T entity);
|
||||
Task<bool> DeleteAsync(string id);
|
||||
Task<bool> ExistsAsync(string id);
|
||||
Task<int> CountAsync();
|
||||
}
|
||||
```
|
||||
|
||||
## Core Services
|
||||
|
||||
### IProcessService
|
||||
Manages process enumeration and manipulation.
|
||||
|
||||
```csharp
|
||||
public interface IProcessService
|
||||
{
|
||||
Task<IEnumerable<ProcessModel>> GetRunningProcessesAsync();
|
||||
Task<bool> SetProcessPriorityAsync(int processId, ProcessPriorityClass priority);
|
||||
Task<bool> SetProcessAffinityAsync(int processId, long affinityMask);
|
||||
Task<ProcessModel?> GetProcessByIdAsync(int processId);
|
||||
bool IsProcessRunning(string processName);
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Async process enumeration
|
||||
- Priority and affinity management
|
||||
- Process existence checking
|
||||
|
||||
### IPowerPlanService
|
||||
Manages Windows power plans.
|
||||
|
||||
```csharp
|
||||
public interface IPowerPlanService
|
||||
{
|
||||
Task<IEnumerable<PowerPlanModel>> GetAvailablePowerPlansAsync();
|
||||
Task<PowerPlanModel?> GetActivePowerPlanAsync();
|
||||
Task<bool> SetActivePowerPlanAsync(string powerPlanGuid);
|
||||
Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string guid);
|
||||
event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Power plan enumeration and activation
|
||||
- Change event notifications
|
||||
- GUID-based plan identification
|
||||
|
||||
### ICpuTopologyService
|
||||
Provides CPU topology detection and affinity management.
|
||||
|
||||
```csharp
|
||||
public interface ICpuTopologyService
|
||||
{
|
||||
Task<CpuTopologyModel> DetectTopologyAsync();
|
||||
Task<bool> SetProcessAffinityAsync(int processId, IEnumerable<int> coreIds);
|
||||
Task<long> GetProcessAffinityAsync(int processId);
|
||||
event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Modern CPU architecture detection
|
||||
- Core affinity management
|
||||
- Support for hybrid architectures
|
||||
|
||||
## Business Logic Services
|
||||
|
||||
### IProcessMonitorManagerService
|
||||
Orchestrates process monitoring and power plan switching.
|
||||
|
||||
```csharp
|
||||
public interface IProcessMonitorManagerService
|
||||
{
|
||||
bool IsMonitoringActive { get; }
|
||||
Task StartMonitoringAsync();
|
||||
Task StopMonitoringAsync();
|
||||
event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
event EventHandler? MonitoringStarted;
|
||||
event EventHandler? MonitoringStopped;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- WMI-based process monitoring
|
||||
- Automatic power plan switching
|
||||
- Fallback polling mechanism
|
||||
|
||||
### IGameBoostService
|
||||
Manages game detection and performance optimization.
|
||||
|
||||
```csharp
|
||||
public interface IGameBoostService
|
||||
{
|
||||
bool IsGameBoostActive { get; }
|
||||
string? CurrentGameName { get; }
|
||||
Task<bool> ActivateGameBoostAsync(ProcessModel gameProcess);
|
||||
Task DeactivateGameBoostAsync();
|
||||
Task<bool> AddKnownGameAsync(string executableName);
|
||||
Task<bool> RemoveKnownGameAsync(string executableName);
|
||||
event EventHandler<GameBoostEventArgs>? GameBoostActivated;
|
||||
event EventHandler<GameBoostEventArgs>? GameBoostDeactivated;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Automatic game detection
|
||||
- Performance optimization
|
||||
- Configurable game database
|
||||
|
||||
## Application Services
|
||||
|
||||
### IApplicationSettingsService
|
||||
Manages application configuration and persistence.
|
||||
|
||||
```csharp
|
||||
public interface IApplicationSettingsService
|
||||
{
|
||||
ApplicationSettingsModel Settings { get; }
|
||||
Task LoadSettingsAsync();
|
||||
Task SaveSettingsAsync();
|
||||
Task ResetToDefaultsAsync();
|
||||
Task<bool> ExportSettingsAsync(string filePath);
|
||||
Task<bool> ImportSettingsAsync(string filePath);
|
||||
event EventHandler<SettingsChangedEventArgs>? SettingsChanged;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Automatic settings persistence
|
||||
- Import/export functionality
|
||||
- Change notifications
|
||||
|
||||
### INotificationService
|
||||
Handles user notifications and system tray integration.
|
||||
|
||||
```csharp
|
||||
public interface INotificationService
|
||||
{
|
||||
Task ShowNotificationAsync(string title, string message, NotificationType type);
|
||||
Task ShowBalloonNotificationAsync(string title, string message, int duration);
|
||||
Task ShowToastNotificationAsync(string title, string message);
|
||||
Task ClearAllNotificationsAsync();
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Multiple notification types
|
||||
- System tray balloon tips
|
||||
- Windows toast notifications
|
||||
|
||||
### IEnhancedLoggingService
|
||||
Provides structured logging with file persistence.
|
||||
|
||||
```csharp
|
||||
public interface IEnhancedLoggingService
|
||||
{
|
||||
Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason);
|
||||
Task LogProcessEventAsync(string processName, string eventType, string details);
|
||||
Task LogGameBoostEventAsync(string gameName, string action, string details);
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
Task LogErrorAsync(string source, string error, string? stackTrace = null);
|
||||
Task<IEnumerable<LogEntry>> GetLogEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null);
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Structured event logging
|
||||
- File rotation and management
|
||||
- Query capabilities
|
||||
|
||||
## Data Models
|
||||
|
||||
### ProcessModel
|
||||
Represents a system process with extended information.
|
||||
|
||||
```csharp
|
||||
public partial class ProcessModel : ObservableObject
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string ExecutablePath { get; set; }
|
||||
public ProcessPriorityClass Priority { get; set; }
|
||||
public long ProcessorAffinity { get; set; }
|
||||
public double CpuUsage { get; set; }
|
||||
public long WorkingSet { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### PowerPlanModel
|
||||
Represents a Windows power plan.
|
||||
|
||||
```csharp
|
||||
public partial class PowerPlanModel : ObservableObject
|
||||
{
|
||||
public string Guid { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### CpuTopologyModel
|
||||
Represents CPU topology information.
|
||||
|
||||
```csharp
|
||||
public partial class CpuTopologyModel : ObservableObject
|
||||
{
|
||||
public int TotalCores { get; set; }
|
||||
public int PhysicalCores { get; set; }
|
||||
public int LogicalCores { get; set; }
|
||||
public bool HasHybridArchitecture { get; set; }
|
||||
public ObservableCollection<CpuCoreModel> Cores { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
## Event Arguments
|
||||
|
||||
### ProcessEventArgs
|
||||
Provides data for process-related events.
|
||||
|
||||
```csharp
|
||||
public class ProcessEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel Process { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
public string EventType { get; }
|
||||
}
|
||||
```
|
||||
|
||||
### PowerPlanChangedEventArgs
|
||||
Provides data for power plan change events.
|
||||
|
||||
```csharp
|
||||
public class PowerPlanChangedEventArgs : EventArgs
|
||||
{
|
||||
public PowerPlanModel? PreviousPlan { get; }
|
||||
public PowerPlanModel CurrentPlan { get; }
|
||||
public string Reason { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
}
|
||||
```
|
||||
|
||||
### GameBoostEventArgs
|
||||
Provides data for game boost events.
|
||||
|
||||
```csharp
|
||||
public class GameBoostEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel? GameProcess { get; }
|
||||
public bool IsActivated { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration Enums
|
||||
|
||||
### NotificationType
|
||||
Defines notification types for the notification service.
|
||||
|
||||
```csharp
|
||||
public enum NotificationType
|
||||
{
|
||||
Information,
|
||||
Warning,
|
||||
Error,
|
||||
Success
|
||||
}
|
||||
```
|
||||
|
||||
### ProcessPriorityClass
|
||||
Standard .NET process priority enumeration.
|
||||
|
||||
```csharp
|
||||
public enum ProcessPriorityClass
|
||||
{
|
||||
Idle,
|
||||
BelowNormal,
|
||||
Normal,
|
||||
AboveNormal,
|
||||
High,
|
||||
RealTime
|
||||
}
|
||||
```
|
||||
|
||||
This API reference provides comprehensive documentation for all public interfaces and key classes in ThreadPilot.
|
||||
@@ -0,0 +1,199 @@
|
||||
# ThreadPilot Architecture Guide
|
||||
|
||||
## Overview
|
||||
This document describes the modular architecture of ThreadPilot, designed for maintainability, testability, and future extensibility.
|
||||
|
||||
## Architecture Principles
|
||||
|
||||
### 1. Separation of Concerns
|
||||
- **Core Services**: Direct OS interaction (Process, Power Plan, CPU Topology)
|
||||
- **Process Management**: Business logic for process monitoring and management
|
||||
- **Application Services**: UI and application-level functionality
|
||||
- **Presentation Layer**: ViewModels and Views with MVVM pattern
|
||||
|
||||
### 2. Dependency Injection
|
||||
- Centralized service configuration in `ServiceConfiguration.cs`
|
||||
- Service factory pattern for advanced service management
|
||||
- Proper lifecycle management for all services
|
||||
|
||||
### 3. Event-Driven Architecture
|
||||
- Services communicate through well-defined events
|
||||
- Loose coupling between components
|
||||
- Reactive UI updates through observable patterns
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
ThreadPilot/
|
||||
├── Services/
|
||||
│ ├── Core/ # Base interfaces and implementations
|
||||
│ │ ├── ISystemService.cs # Base interface for system services
|
||||
│ │ └── BaseSystemService.cs # Base implementation with common functionality
|
||||
│ ├── ProcessManagement/ # Process-related services
|
||||
│ │ └── IProcessManagementService.cs
|
||||
│ ├── ServiceConfiguration.cs # Centralized DI configuration
|
||||
│ └── ServiceFactory.cs # Service factory for advanced management
|
||||
├── Models/
|
||||
│ ├── Core/ # Base model interfaces and implementations
|
||||
│ │ └── IModel.cs # Base model interface and validation
|
||||
│ ├── Process/ # Process-related models
|
||||
│ ├── PowerPlan/ # Power plan models
|
||||
│ └── Configuration/ # Configuration models
|
||||
├── ViewModels/
|
||||
│ ├── BaseViewModel.cs # Enhanced base ViewModel with error handling
|
||||
│ └── ViewModelFactory.cs # Factory for ViewModel creation and management
|
||||
├── Views/ # XAML views and code-behind
|
||||
├── Converters/ # Value converters for data binding
|
||||
├── Helpers/ # Utility classes and extension methods
|
||||
└── Tests/ # Unit and integration tests
|
||||
```
|
||||
|
||||
## Service Layer Architecture
|
||||
|
||||
### Core Services (`Services/Core/`)
|
||||
Base interfaces and implementations for all services:
|
||||
|
||||
- **ISystemService**: Base interface with availability tracking and lifecycle management
|
||||
- **BaseSystemService**: Common functionality for initialization, disposal, and error handling
|
||||
|
||||
### Service Categories
|
||||
|
||||
#### 1. Core System Services
|
||||
Direct interaction with the operating system:
|
||||
- `IProcessService`: Process enumeration and manipulation
|
||||
- `IPowerPlanService`: Windows power plan management
|
||||
- `ICpuTopologyService`: CPU topology detection and affinity management
|
||||
|
||||
#### 2. Process Management Services
|
||||
Business logic for process monitoring:
|
||||
- `IProcessMonitorService`: WMI-based process event monitoring
|
||||
- `IProcessPowerPlanAssociationService`: Process-to-power plan associations
|
||||
- `IProcessMonitorManagerService`: Orchestrates process monitoring
|
||||
- `IGameBoostService`: Game detection and performance optimization
|
||||
|
||||
#### 3. Application Services
|
||||
Application-level functionality:
|
||||
- `IApplicationSettingsService`: Configuration persistence
|
||||
- `INotificationService`: User notifications and system tray
|
||||
- `IAutostartService`: Windows startup integration
|
||||
- `IEnhancedLoggingService`: Structured logging with file persistence
|
||||
|
||||
### Service Factory Pattern
|
||||
The `ServiceFactory` class provides:
|
||||
- Centralized service creation with dependency resolution
|
||||
- Lifecycle management for `ISystemService` implementations
|
||||
- Automatic initialization and disposal of managed services
|
||||
- Error handling and logging for service operations
|
||||
|
||||
## Presentation Layer Architecture
|
||||
|
||||
### Enhanced BaseViewModel
|
||||
The `BaseViewModel` class provides:
|
||||
- **Error Handling**: Centralized error management with logging
|
||||
- **Status Management**: Busy states and status messages
|
||||
- **Async Operations**: Helper methods for async operations with error handling
|
||||
- **Logging Integration**: Automatic user action logging
|
||||
- **Lifecycle Management**: Proper initialization and disposal
|
||||
|
||||
### ViewModel Factory
|
||||
The `ViewModelFactory` class provides:
|
||||
- Dependency injection for ViewModels
|
||||
- Automatic initialization of ViewModels
|
||||
- Lifecycle management and disposal
|
||||
- Error handling during creation and initialization
|
||||
|
||||
## Model Layer Architecture
|
||||
|
||||
### Base Model Interface
|
||||
The `IModel` interface provides:
|
||||
- **Identity**: Unique ID and timestamps
|
||||
- **Validation**: Built-in validation framework
|
||||
- **Change Tracking**: Property change notifications
|
||||
- **Cloning**: Deep copy support
|
||||
|
||||
### Domain-Specific Models
|
||||
Models are organized by domain:
|
||||
- **Process Models**: Process information and metadata
|
||||
- **Power Plan Models**: Power plan configurations
|
||||
- **Configuration Models**: Application settings and associations
|
||||
|
||||
## Configuration and Dependency Injection
|
||||
|
||||
### ServiceConfiguration Class
|
||||
Centralized configuration with methods for each service category:
|
||||
- `ConfigureServiceInfrastructure()`: Logging and factories
|
||||
- `ConfigureCoreSystemServices()`: OS interaction services
|
||||
- `ConfigureProcessManagementServices()`: Business logic services
|
||||
- `ConfigureApplicationLevelServices()`: UI and application services
|
||||
- `ConfigurePresentationLayer()`: ViewModels and Views
|
||||
|
||||
### Service Validation
|
||||
Automatic validation of service configuration at startup:
|
||||
- Ensures all required services can be resolved
|
||||
- Validates service dependencies
|
||||
- Provides clear error messages for configuration issues
|
||||
|
||||
## Error Handling and Logging
|
||||
|
||||
### Structured Logging
|
||||
- **Enhanced Logging Service**: File-based logging with rotation
|
||||
- **Structured Events**: Predefined event types for different operations
|
||||
- **User Action Logging**: Audit trail for user interactions
|
||||
- **Error Correlation**: Consistent error tracking across services
|
||||
|
||||
### Error Handling Patterns
|
||||
- **Service Level**: Try-catch with logging and graceful degradation
|
||||
- **ViewModel Level**: User-friendly error messages with technical logging
|
||||
- **Application Level**: Global exception handling with recovery
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Testing
|
||||
- Service interfaces enable easy mocking
|
||||
- BaseViewModel provides testable error handling
|
||||
- Model validation can be tested independently
|
||||
|
||||
### Integration Testing
|
||||
- Service factory enables testing of service interactions
|
||||
- Event-driven architecture allows testing of component communication
|
||||
- Configuration validation ensures proper setup
|
||||
|
||||
## Future Extensibility
|
||||
|
||||
### Adding New Services
|
||||
1. Implement appropriate base interface (`ISystemService` for system services)
|
||||
2. Add to relevant service category in `ServiceConfiguration`
|
||||
3. Follow established patterns for error handling and logging
|
||||
|
||||
### Adding New Features
|
||||
1. Create domain-specific models with validation
|
||||
2. Implement services following the established patterns
|
||||
3. Create ViewModels inheriting from `BaseViewModel`
|
||||
4. Use dependency injection for all dependencies
|
||||
|
||||
### Performance Optimization
|
||||
- Service factory enables lazy loading of services
|
||||
- Event-driven architecture allows for efficient updates
|
||||
- Structured logging provides performance monitoring data
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Service Development
|
||||
- Always implement proper disposal for resources
|
||||
- Use structured logging for all operations
|
||||
- Implement graceful degradation for optional features
|
||||
- Follow async/await patterns consistently
|
||||
|
||||
### ViewModel Development
|
||||
- Inherit from `BaseViewModel` for consistent functionality
|
||||
- Use `ExecuteAsync` methods for error handling
|
||||
- Implement proper disposal for event subscriptions
|
||||
- Log user actions for audit purposes
|
||||
|
||||
### Model Development
|
||||
- Implement validation for all business rules
|
||||
- Use property change notifications for UI binding
|
||||
- Provide meaningful error messages
|
||||
- Support cloning for undo/redo functionality
|
||||
|
||||
This architecture provides a solid foundation for maintainable, testable, and extensible code while following established patterns and best practices.
|
||||
@@ -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">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<helpers:BytesToMbConverter x:Key="BytesToMbConverter"/>
|
||||
<helpers:AffinityMaskConverter x:Key="AffinityMaskConverter"/>
|
||||
<helpers:BoolToFontWeightConverter x:Key="BoolToFontWeightConverter"/>
|
||||
<converters:BoolToColorConverter x:Key="BoolToColorConverter"/>
|
||||
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
|
||||
+64
-15
@@ -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<IProcessService, ProcessService>();
|
||||
services.AddSingleton<IPowerPlanService, PowerPlanService>();
|
||||
|
||||
// Register ViewModels
|
||||
services.AddTransient<ProcessViewModel>();
|
||||
services.AddTransient<PowerPlanViewModel>();
|
||||
|
||||
// Register Views
|
||||
services.AddTransient<MainWindow>();
|
||||
}
|
||||
|
||||
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>();
|
||||
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<ILogger<App>>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Converter for CPU core type to color
|
||||
/// </summary>
|
||||
public class CoreTypeToColorConverter : IMultiValueConverter
|
||||
{
|
||||
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (values.Length < 2) return 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for boolean to color (success/failure indication)
|
||||
/// </summary>
|
||||
public class BoolToColorConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool success)
|
||||
{
|
||||
return success ? 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for boolean to visibility
|
||||
/// </summary>
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool visible)
|
||||
{
|
||||
return visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
return System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for affinity mask to readable string
|
||||
/// </summary>
|
||||
public class AffinityMaskConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long mask)
|
||||
{
|
||||
if (mask == 0) return "None";
|
||||
|
||||
var cores = new System.Collections.Generic.List<int>();
|
||||
for (int i = 0; i < 64; i++)
|
||||
{
|
||||
if ((mask & (1L << i)) != 0)
|
||||
{
|
||||
cores.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (cores.Count == 0) return "None";
|
||||
if (cores.Count == 1) return $"Core {cores[0]}";
|
||||
if (cores.Count <= 4) return $"Cores {string.Join(", ", cores)}";
|
||||
|
||||
return $"Cores {cores[0]}-{cores[cores.Count - 1]} ({cores.Count} cores)";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for bytes to megabytes
|
||||
/// </summary>
|
||||
public class BytesToMbConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return (bytes / (1024.0 * 1024.0)).ToString("F1");
|
||||
}
|
||||
return "0.0";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for string to visibility (empty/null = collapsed)
|
||||
/// </summary>
|
||||
public class StringToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly StringToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return string.IsNullOrEmpty(value as string) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Converter to invert boolean values
|
||||
/// </summary>
|
||||
public class InverseBooleanConverter : IValueConverter
|
||||
{
|
||||
public static readonly InverseBooleanConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
# ThreadPilot Developer Guide
|
||||
|
||||
## Quick Start for New Developers
|
||||
|
||||
### Prerequisites
|
||||
- .NET 8.0 SDK
|
||||
- Visual Studio 2022 or VS Code with C# extension
|
||||
- Windows 10/11 (for WMI and power plan features)
|
||||
|
||||
### Building the Project
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd ThreadPilot
|
||||
dotnet restore
|
||||
dotnet build
|
||||
```
|
||||
|
||||
### Running the Application
|
||||
```bash
|
||||
dotnet run --project ThreadPilot
|
||||
```
|
||||
|
||||
## Key Architectural Concepts
|
||||
|
||||
### 1. Service-Oriented Architecture
|
||||
ThreadPilot uses a layered service architecture with dependency injection:
|
||||
|
||||
- **Core Services**: Direct OS interaction (Process, Power Plan, CPU)
|
||||
- **Business Services**: Application logic (Process Monitoring, Game Boost)
|
||||
- **Application Services**: UI and configuration (Settings, Notifications)
|
||||
|
||||
### 2. MVVM Pattern with Enhanced BaseViewModel
|
||||
All ViewModels inherit from `BaseViewModel` which provides:
|
||||
- Centralized error handling with logging
|
||||
- Async operation helpers with status management
|
||||
- User action logging for audit trails
|
||||
- Proper disposal and lifecycle management
|
||||
|
||||
### 3. Repository Pattern for Data Access
|
||||
Data persistence uses the repository pattern with:
|
||||
- Generic `IRepository<T>` interface for CRUD operations
|
||||
- JSON file-based implementation with thread-safe operations
|
||||
- Centralized data access through `IDataAccessService`
|
||||
- Model validation and integrity checking
|
||||
|
||||
## Adding New Features
|
||||
|
||||
### 1. Adding a New Service
|
||||
|
||||
**Step 1**: Create the interface in appropriate folder:
|
||||
```csharp
|
||||
// Services/YourDomain/IYourService.cs
|
||||
public interface IYourService : ISystemService
|
||||
{
|
||||
Task<bool> DoSomethingAsync();
|
||||
event EventHandler<YourEventArgs>? SomethingHappened;
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2**: Implement the service:
|
||||
```csharp
|
||||
// Services/YourDomain/YourService.cs
|
||||
public class YourService : BaseSystemService, IYourService
|
||||
{
|
||||
public YourService(ILogger<YourService> logger) : base(logger) { }
|
||||
|
||||
public async Task<bool> DoSomethingAsync()
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3**: Register in `ServiceConfiguration.cs`:
|
||||
```csharp
|
||||
services.AddSingleton<IYourService, YourService>();
|
||||
```
|
||||
|
||||
### 2. Adding a New ViewModel
|
||||
|
||||
**Step 1**: Create ViewModel inheriting from BaseViewModel:
|
||||
```csharp
|
||||
public partial class YourViewModel : BaseViewModel
|
||||
{
|
||||
private readonly IYourService _yourService;
|
||||
|
||||
public YourViewModel(
|
||||
ILogger<YourViewModel> logger,
|
||||
IYourService yourService,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
{
|
||||
_yourService = yourService;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task DoSomethingAsync()
|
||||
{
|
||||
await ExecuteAsync(async () =>
|
||||
{
|
||||
await _yourService.DoSomethingAsync();
|
||||
await LogUserActionAsync("YourAction", "Did something", "User interaction");
|
||||
}, "Doing something...", "Operation completed successfully");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2**: Register in `ServiceConfiguration.cs`:
|
||||
```csharp
|
||||
services.AddTransient<YourViewModel>();
|
||||
```
|
||||
|
||||
### 3. Adding a New Model
|
||||
|
||||
**Step 1**: Create model implementing IModel:
|
||||
```csharp
|
||||
public partial class YourModel : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
// IModel implementation
|
||||
public string Id => id;
|
||||
public DateTime CreatedAt => createdAt;
|
||||
public DateTime UpdatedAt => updatedAt;
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (string.IsNullOrWhiteSpace(Name))
|
||||
errors.Add("Name is required");
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new YourModel
|
||||
{
|
||||
id = Guid.NewGuid().ToString(),
|
||||
Name = this.Name,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns and Best Practices
|
||||
|
||||
### Error Handling
|
||||
Always use the BaseViewModel's error handling methods:
|
||||
```csharp
|
||||
// For async operations with user feedback
|
||||
await ExecuteAsync(async () =>
|
||||
{
|
||||
// Your operation
|
||||
}, "Loading...", "Completed successfully");
|
||||
|
||||
// For setting errors manually
|
||||
SetError("Something went wrong", exception);
|
||||
|
||||
// For clearing errors
|
||||
ClearError();
|
||||
```
|
||||
|
||||
### Logging
|
||||
Use structured logging throughout the application:
|
||||
```csharp
|
||||
// In services
|
||||
Logger.LogInformation("Operation completed for {EntityId}", entityId);
|
||||
|
||||
// In ViewModels (for user actions)
|
||||
await LogUserActionAsync("ActionName", "Description", "Context");
|
||||
```
|
||||
|
||||
### Event Handling
|
||||
Follow the established event pattern:
|
||||
```csharp
|
||||
public event EventHandler<YourEventArgs>? YourEvent;
|
||||
|
||||
protected virtual void OnYourEvent(YourEventArgs args)
|
||||
{
|
||||
YourEvent?.Invoke(this, args);
|
||||
}
|
||||
```
|
||||
|
||||
### Async Operations
|
||||
Always use proper async/await patterns:
|
||||
```csharp
|
||||
// Good
|
||||
public async Task<bool> DoSomethingAsync()
|
||||
{
|
||||
await SomeAsyncOperation();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Avoid blocking calls
|
||||
public bool DoSomething()
|
||||
{
|
||||
DoSomethingAsync().Wait(); // DON'T DO THIS
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### Unit Testing Services
|
||||
```csharp
|
||||
[Test]
|
||||
public async Task YourService_DoSomething_ReturnsExpectedResult()
|
||||
{
|
||||
// Arrange
|
||||
var logger = Mock.Of<ILogger<YourService>>();
|
||||
var service = new YourService(logger);
|
||||
|
||||
// Act
|
||||
var result = await service.DoSomethingAsync();
|
||||
|
||||
// Assert
|
||||
Assert.IsTrue(result);
|
||||
}
|
||||
```
|
||||
|
||||
### Testing ViewModels
|
||||
```csharp
|
||||
[Test]
|
||||
public async Task YourViewModel_DoSomething_UpdatesStatusCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var logger = Mock.Of<ILogger<YourViewModel>>();
|
||||
var service = Mock.Of<IYourService>();
|
||||
var viewModel = new YourViewModel(logger, service);
|
||||
|
||||
// Act
|
||||
await viewModel.DoSomethingCommand.ExecuteAsync(null);
|
||||
|
||||
// Assert
|
||||
Assert.IsFalse(viewModel.HasError);
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Memory Management
|
||||
- Always dispose of services that implement IDisposable
|
||||
- Unsubscribe from events in ViewModel disposal
|
||||
- Use weak event patterns for long-lived subscriptions
|
||||
|
||||
### Threading
|
||||
- UI operations must be on the UI thread
|
||||
- Use ConfigureAwait(false) for non-UI async operations
|
||||
- Protect shared resources with appropriate synchronization
|
||||
|
||||
### Data Access
|
||||
- Repository operations are thread-safe
|
||||
- Use batch operations when possible
|
||||
- Implement proper caching for frequently accessed data
|
||||
|
||||
## Troubleshooting Common Issues
|
||||
|
||||
### Service Resolution Errors
|
||||
Check `ServiceConfiguration.cs` to ensure all dependencies are registered with correct lifetimes.
|
||||
|
||||
### ViewModel Constructor Issues
|
||||
Ensure all ViewModels call the base constructor with required logger parameter.
|
||||
|
||||
### Data Persistence Issues
|
||||
Check file permissions and ensure data directory exists. Use logging to trace repository operations.
|
||||
|
||||
### Event Subscription Leaks
|
||||
Always unsubscribe from events in the ViewModel's OnDispose method.
|
||||
|
||||
## Configuration and Settings
|
||||
|
||||
### Application Settings
|
||||
Settings are managed through `IApplicationSettingsService` and persisted automatically:
|
||||
```csharp
|
||||
// Access current settings
|
||||
var settings = _settingsService.Settings;
|
||||
|
||||
// Modify settings
|
||||
settings.EnableNotifications = true;
|
||||
|
||||
// Save changes (automatic on property change)
|
||||
await _settingsService.SaveSettingsAsync();
|
||||
```
|
||||
|
||||
### Logging Configuration
|
||||
Enhanced logging is configured in `ServiceConfiguration.cs`:
|
||||
- Console logging for development
|
||||
- File-based logging with rotation for production
|
||||
- Structured events for different operation types
|
||||
|
||||
### Data Storage Locations
|
||||
- **Settings**: `%AppData%\ThreadPilot\settings.json`
|
||||
- **Associations**: `%AppData%\ThreadPilot\Data\ProcessAssociations.json`
|
||||
- **Profiles**: `%AppData%\ThreadPilot\Data\ProcessProfiles.json`
|
||||
- **Logs**: `%AppData%\ThreadPilot\Logs\`
|
||||
|
||||
## Deployment and Distribution
|
||||
|
||||
### Release Build
|
||||
```bash
|
||||
dotnet publish -c Release -r win-x64 --self-contained true
|
||||
```
|
||||
|
||||
### Installer Considerations
|
||||
- Register for Windows autostart if enabled
|
||||
- Create application data directories
|
||||
- Set appropriate file permissions
|
||||
- Register WMI event handlers
|
||||
|
||||
This guide provides the foundation for extending ThreadPilot while maintaining code quality and architectural consistency.
|
||||
@@ -0,0 +1,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
|
||||
{
|
||||
/// <summary>
|
||||
/// Implementation of data access service with JSON file repositories
|
||||
/// </summary>
|
||||
public class DataAccessService : IDataAccessService
|
||||
{
|
||||
private readonly ILogger<DataAccessService> _logger;
|
||||
private readonly string _dataDirectory;
|
||||
|
||||
public IRepository<ProcessPowerPlanAssociation> ProcessAssociations { get; }
|
||||
public IRepository<ApplicationSettingsModel> ApplicationSettings { get; }
|
||||
public IRepository<ProfileModel> ProcessProfiles { get; }
|
||||
|
||||
public DataAccessService(ILogger<DataAccessService> 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<ProcessPowerPlanAssociation>(
|
||||
Path.Combine(_dataDirectory, "ProcessAssociations.json"),
|
||||
loggerFactory.CreateLogger<JsonRepository<ProcessPowerPlanAssociation>>());
|
||||
|
||||
ApplicationSettings = new JsonRepository<ApplicationSettingsModel>(
|
||||
Path.Combine(_dataDirectory, "ApplicationSettings.json"),
|
||||
loggerFactory.CreateLogger<JsonRepository<ApplicationSettingsModel>>());
|
||||
|
||||
ProcessProfiles = new JsonRepository<ProfileModel>(
|
||||
Path.Combine(_dataDirectory, "ProcessProfiles.json"),
|
||||
loggerFactory.CreateLogger<JsonRepository<ProfileModel>>());
|
||||
}
|
||||
|
||||
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<DataValidationResult> ValidateDataIntegrityAsync()
|
||||
{
|
||||
var issues = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Data
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for coordinating data access operations across all repositories
|
||||
/// </summary>
|
||||
public interface IDataAccessService
|
||||
{
|
||||
/// <summary>
|
||||
/// Get repository for process-power plan associations
|
||||
/// </summary>
|
||||
IRepository<ProcessPowerPlanAssociation> ProcessAssociations { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Get repository for application settings
|
||||
/// </summary>
|
||||
IRepository<ApplicationSettingsModel> ApplicationSettings { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Get repository for process profiles
|
||||
/// </summary>
|
||||
IRepository<ProfileModel> ProcessProfiles { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initialize all repositories
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Backup all data to specified directory
|
||||
/// </summary>
|
||||
Task BackupDataAsync(string backupDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// Restore data from backup directory
|
||||
/// </summary>
|
||||
Task RestoreDataAsync(string backupDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// Validate data integrity across all repositories
|
||||
/// </summary>
|
||||
Task<DataValidationResult> ValidateDataIntegrityAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Clean up orphaned or invalid data
|
||||
/// </summary>
|
||||
Task CleanupDataAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of data validation operation
|
||||
/// </summary>
|
||||
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<string>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThreadPilot.Data
|
||||
{
|
||||
/// <summary>
|
||||
/// Generic repository interface for data access operations
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Entity type</typeparam>
|
||||
/// <typeparam name="TKey">Key type</typeparam>
|
||||
public interface IRepository<T, TKey> where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Get entity by ID
|
||||
/// </summary>
|
||||
Task<T?> GetByIdAsync(TKey id);
|
||||
|
||||
/// <summary>
|
||||
/// Get all entities
|
||||
/// </summary>
|
||||
Task<IEnumerable<T>> GetAllAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Find entities matching predicate
|
||||
/// </summary>
|
||||
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
|
||||
|
||||
/// <summary>
|
||||
/// Add new entity
|
||||
/// </summary>
|
||||
Task<T> AddAsync(T entity);
|
||||
|
||||
/// <summary>
|
||||
/// Update existing entity
|
||||
/// </summary>
|
||||
Task<T> UpdateAsync(T entity);
|
||||
|
||||
/// <summary>
|
||||
/// Delete entity by ID
|
||||
/// </summary>
|
||||
Task<bool> DeleteAsync(TKey id);
|
||||
|
||||
/// <summary>
|
||||
/// Delete entity
|
||||
/// </summary>
|
||||
Task<bool> DeleteAsync(T entity);
|
||||
|
||||
/// <summary>
|
||||
/// Check if entity exists
|
||||
/// </summary>
|
||||
Task<bool> ExistsAsync(TKey id);
|
||||
|
||||
/// <summary>
|
||||
/// Get count of entities
|
||||
/// </summary>
|
||||
Task<int> CountAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get count of entities matching predicate
|
||||
/// </summary>
|
||||
Task<int> CountAsync(Expression<Func<T, bool>> predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Repository interface for entities with string keys
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Entity type</typeparam>
|
||||
public interface IRepository<T> : IRepository<T, string> where T : class
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unit of work pattern for coordinating multiple repository operations
|
||||
/// </summary>
|
||||
public interface IUnitOfWork : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Get repository for entity type
|
||||
/// </summary>
|
||||
IRepository<T> GetRepository<T>() where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Save all changes
|
||||
/// </summary>
|
||||
Task<int> SaveChangesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Begin transaction
|
||||
/// </summary>
|
||||
Task BeginTransactionAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Commit transaction
|
||||
/// </summary>
|
||||
Task CommitTransactionAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Rollback transaction
|
||||
/// </summary>
|
||||
Task RollbackTransactionAsync();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// JSON file-based repository implementation
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Entity type that implements IModel</typeparam>
|
||||
public class JsonRepository<T> : IRepository<T> where T : class, IModel
|
||||
{
|
||||
private readonly string _filePath;
|
||||
private readonly ILogger<JsonRepository<T>> _logger;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private readonly SemaphoreSlim _fileLock = new(1, 1);
|
||||
|
||||
public JsonRepository(string filePath, ILogger<JsonRepository<T>> 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<T?> GetByIdAsync(string id)
|
||||
{
|
||||
var entities = await GetAllAsync();
|
||||
return entities.FirstOrDefault(e => e.Id == id);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> GetAllAsync()
|
||||
{
|
||||
await _fileLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_filePath))
|
||||
{
|
||||
return new List<T>();
|
||||
}
|
||||
|
||||
var json = await File.ReadAllTextAsync(_filePath);
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return new List<T>();
|
||||
}
|
||||
|
||||
var entities = JsonSerializer.Deserialize<List<T>>(json, _jsonOptions);
|
||||
return entities ?? new List<T>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to read entities from {FilePath}", _filePath);
|
||||
return new List<T>();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
|
||||
{
|
||||
var entities = await GetAllAsync();
|
||||
var compiledPredicate = predicate.Compile();
|
||||
return entities.Where(compiledPredicate);
|
||||
}
|
||||
|
||||
public async Task<T> 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<T> 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<bool> 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<bool> DeleteAsync(T entity)
|
||||
{
|
||||
if (entity == null) throw new ArgumentNullException(nameof(entity));
|
||||
return await DeleteAsync(entity.Id);
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsAsync(string id)
|
||||
{
|
||||
var entities = await GetAllAsync();
|
||||
return entities.Any(e => e.Id == id);
|
||||
}
|
||||
|
||||
public async Task<int> CountAsync()
|
||||
{
|
||||
var entities = await GetAllAsync();
|
||||
return entities.Count();
|
||||
}
|
||||
|
||||
public async Task<int> CountAsync(Expression<Func<T, bool>> predicate)
|
||||
{
|
||||
var entities = await FindAsync(predicate);
|
||||
return entities.Count();
|
||||
}
|
||||
|
||||
private async Task SaveAllAsync(IEnumerable<T> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -6,14 +6,14 @@ namespace ThreadPilot.Helpers
|
||||
{
|
||||
public static class AffinityHelper
|
||||
{
|
||||
public static long CalculateAffinityMask(IEnumerable<CheckBox> cpuCheckboxes)
|
||||
public static long CalculateAffinityMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes)
|
||||
{
|
||||
return cpuCheckboxes
|
||||
.Where(cb => cb.IsChecked == true)
|
||||
.Sum(cb => (long)cb.Tag);
|
||||
}
|
||||
|
||||
public static void UpdateCheckboxesFromMask(IEnumerable<CheckBox> cpuCheckboxes, long affinityMask)
|
||||
public static void UpdateCheckboxesFromMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes, long affinityMask)
|
||||
{
|
||||
foreach (var checkbox in cpuCheckboxes)
|
||||
{
|
||||
|
||||
+25
-7
@@ -12,10 +12,6 @@
|
||||
Width="1280"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
|
||||
<Window.DataContext>
|
||||
<local:MainWindowViewModel/>
|
||||
</Window.DataContext>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
@@ -24,16 +20,38 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TabControl Grid.Row="1" Margin="10">
|
||||
<TabItem Header="Process Management">
|
||||
<TabItem Header="🔧 Process Management">
|
||||
<views:ProcessView/>
|
||||
</TabItem>
|
||||
<TabItem Header="Power Plans">
|
||||
<TabItem Header="⚡ Power Plans">
|
||||
<views:PowerPlanView/>
|
||||
</TabItem>
|
||||
<TabItem Header="🔗 Process Associations">
|
||||
<views:ProcessPowerPlanAssociationView x:Name="AssociationView"/>
|
||||
</TabItem>
|
||||
<TabItem Header="📋 Activity Logs">
|
||||
<views:LogViewerView/>
|
||||
</TabItem>
|
||||
<TabItem Header="⚙️ Settings">
|
||||
<views:SettingsView/>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
|
||||
<StatusBar Grid.Row="2" Height="25">
|
||||
<TextBlock Text="{Binding StatusMessage}"/>
|
||||
<StatusBarItem>
|
||||
<TextBlock Text="{Binding StatusMessage}"/>
|
||||
</StatusBarItem>
|
||||
<Separator/>
|
||||
<StatusBarItem>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding GameBoostStatusText}"
|
||||
FontWeight="{Binding IsGameBoostActive, Converter={StaticResource BoolToFontWeightConverter}}"
|
||||
Foreground="{Binding IsGameBoostActive, Converter={StaticResource BoolToColorConverter}}"/>
|
||||
<TextBlock Text="🛡️"
|
||||
Margin="5,0,0,0"
|
||||
Visibility="{Binding IsGameBoostActive, Converter={StaticResource BoolToVisibilityConverter}}"/>
|
||||
</StackPanel>
|
||||
</StatusBarItem>
|
||||
</StatusBar>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
+408
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Model for application settings including notifications and tray preferences
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Copies settings from another instance
|
||||
/// </summary>
|
||||
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<string>();
|
||||
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification position options
|
||||
/// </summary>
|
||||
public enum NotificationPosition
|
||||
{
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
Center
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification sound options
|
||||
/// </summary>
|
||||
public enum NotificationSound
|
||||
{
|
||||
None,
|
||||
Default,
|
||||
Information,
|
||||
Warning,
|
||||
Error,
|
||||
Custom
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tray icon style options
|
||||
/// </summary>
|
||||
public enum TrayIconStyle
|
||||
{
|
||||
Default,
|
||||
Monochrome,
|
||||
Colored,
|
||||
Custom
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace ThreadPilot.Models.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Base interface for all domain models
|
||||
/// </summary>
|
||||
public interface IModel : INotifyPropertyChanged
|
||||
{
|
||||
/// <summary>
|
||||
/// Unique identifier for the model instance
|
||||
/// </summary>
|
||||
string Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp when the model was created
|
||||
/// </summary>
|
||||
DateTime CreatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp when the model was last updated
|
||||
/// </summary>
|
||||
DateTime UpdatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Validate the model state
|
||||
/// </summary>
|
||||
ValidationResult Validate();
|
||||
|
||||
/// <summary>
|
||||
/// Create a copy of the model
|
||||
/// </summary>
|
||||
IModel Clone();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validation result for model validation
|
||||
/// </summary>
|
||||
public class ValidationResult
|
||||
{
|
||||
public bool IsValid { get; }
|
||||
public string[] Errors { get; }
|
||||
|
||||
public ValidationResult(bool isValid, params string[] errors)
|
||||
{
|
||||
IsValid = isValid;
|
||||
Errors = errors ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
public static ValidationResult Success() => new(true);
|
||||
public static ValidationResult Failure(params string[] errors) => new(false, errors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base implementation for domain models
|
||||
/// </summary>
|
||||
public abstract class BaseModel : IModel
|
||||
{
|
||||
public string Id { get; protected set; }
|
||||
public DateTime CreatedAt { get; protected set; }
|
||||
public DateTime UpdatedAt { get; protected set; }
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
protected BaseModel()
|
||||
{
|
||||
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<T>(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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a logical CPU core with topology information
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the affinity mask bit for this logical core
|
||||
/// </summary>
|
||||
public long AffinityMask => 1L << LogicalCoreId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Types of CPU cores
|
||||
/// </summary>
|
||||
public enum CpuCoreType
|
||||
{
|
||||
Unknown,
|
||||
Standard,
|
||||
PerformanceCore, // Intel P-cores
|
||||
EfficiencyCore, // Intel E-cores
|
||||
Zen, // AMD Zen cores
|
||||
ZenPlus, // AMD Zen+ cores
|
||||
Zen2, // AMD Zen2 cores
|
||||
Zen3, // AMD Zen3 cores
|
||||
Zen4 // AMD Zen4 cores
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents CPU topology information
|
||||
/// </summary>
|
||||
public class CpuTopologyModel
|
||||
{
|
||||
public List<CpuCoreModel> LogicalCores { get; set; } = new();
|
||||
public int TotalLogicalCores => 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;
|
||||
|
||||
/// <summary>
|
||||
/// Gets all CCDs (Core Complex Dies) available
|
||||
/// </summary>
|
||||
public IEnumerable<int> AvailableCcds => LogicalCores
|
||||
.Where(c => c.CcdId.HasValue)
|
||||
.Select(c => c.CcdId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(id => id);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all performance cores (Intel P-cores)
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> PerformanceCores => LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.PerformanceCore);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all efficiency cores (Intel E-cores)
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> EfficiencyCores => LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.EfficiencyCore);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all physical cores (one logical core per physical core, excluding HT siblings)
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> PhysicalCores => LogicalCores
|
||||
.GroupBy(c => c.PhysicalCoreId)
|
||||
.Select(g => g.OrderBy(c => c.LogicalCoreId).First());
|
||||
|
||||
/// <summary>
|
||||
/// Gets cores by CCD ID
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> GetCoresByCcd(int ccdId) => LogicalCores
|
||||
.Where(c => c.CcdId == ccdId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets cores by socket ID
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> GetCoresBySocket(int socketId) => LogicalCores
|
||||
.Where(c => c.SocketId == socketId);
|
||||
|
||||
/// <summary>
|
||||
/// Calculates affinity mask for selected cores
|
||||
/// </summary>
|
||||
public long CalculateAffinityMask(IEnumerable<CpuCoreModel> cores)
|
||||
{
|
||||
return cores.Aggregate(0L, (mask, core) => mask | core.AffinityMask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for all physical cores (excluding HT siblings)
|
||||
/// </summary>
|
||||
public long GetPhysicalCoresAffinityMask() => CalculateAffinityMask(PhysicalCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for performance cores
|
||||
/// </summary>
|
||||
public long GetPerformanceCoresAffinityMask() => CalculateAffinityMask(PerformanceCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for efficiency cores
|
||||
/// </summary>
|
||||
public long GetEfficiencyCoresAffinityMask() => CalculateAffinityMask(EfficiencyCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for a specific CCD
|
||||
/// </summary>
|
||||
public long GetCcdAffinityMask(int ccdId) => CalculateAffinityMask(GetCoresByCcd(ccdId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quick selection preset for CPU affinity
|
||||
/// </summary>
|
||||
public class CpuAffinityPreset
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public long AffinityMask { get; set; }
|
||||
public bool IsAvailable { get; set; } = true;
|
||||
public string UnavailableReason { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines structured log event types and categories for consistent logging
|
||||
/// </summary>
|
||||
public static class LogEventTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Power plan related events
|
||||
/// </summary>
|
||||
public static class PowerPlan
|
||||
{
|
||||
public const string Changed = "PowerPlanChanged";
|
||||
public const string ChangeRequested = "PowerPlanChangeRequested";
|
||||
public const string ChangeFailed = "PowerPlanChangeFailed";
|
||||
public const string Restored = "PowerPlanRestored";
|
||||
public const string DefaultSet = "DefaultPowerPlanSet";
|
||||
public const string EnumerationFailed = "PowerPlanEnumerationFailed";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process monitoring events
|
||||
/// </summary>
|
||||
public static class ProcessMonitoring
|
||||
{
|
||||
public const string Started = "ProcessStarted";
|
||||
public const string Stopped = "ProcessStopped";
|
||||
public const string MonitoringStarted = "MonitoringStarted";
|
||||
public const string MonitoringStopped = "MonitoringStopped";
|
||||
public const string WmiEventReceived = "WmiEventReceived";
|
||||
public const string WmiConnectionFailed = "WmiConnectionFailed";
|
||||
public const string PollingFallback = "PollingFallbackActivated";
|
||||
public const string ProcessDetected = "ProcessDetected";
|
||||
public const string ProcessLost = "ProcessLost";
|
||||
public const string AssociationTriggered = "AssociationTriggered";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Game boost related events
|
||||
/// </summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// User action events
|
||||
/// </summary>
|
||||
public static class UserActions
|
||||
{
|
||||
public const string SettingsChanged = "SettingsChanged";
|
||||
public const string ProcessAffinityChanged = "ProcessAffinityChanged";
|
||||
public const string ProcessPriorityChanged = "ProcessPriorityChanged";
|
||||
public const string AssociationAdded = "AssociationAdded";
|
||||
public const string AssociationRemoved = "AssociationRemoved";
|
||||
public const string MonitoringToggled = "MonitoringToggled";
|
||||
public const string GameBoostToggled = "GameBoostToggled";
|
||||
public const string AutostartToggled = "AutostartToggled";
|
||||
public const string NotificationSettingsChanged = "NotificationSettingsChanged";
|
||||
public const string LogsExported = "LogsExported";
|
||||
public const string LogsCleared = "LogsCleared";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// System events
|
||||
/// </summary>
|
||||
public static class System
|
||||
{
|
||||
public const string ApplicationStarted = "ApplicationStarted";
|
||||
public const string ApplicationShutdown = "ApplicationShutdown";
|
||||
public const string ServiceInitialized = "ServiceInitialized";
|
||||
public const string ServiceStarted = "ServiceStarted";
|
||||
public const string ServiceStopped = "ServiceStopped";
|
||||
public const string ConfigurationLoaded = "ConfigurationLoaded";
|
||||
public const string ConfigurationSaved = "ConfigurationSaved";
|
||||
public const string CpuTopologyDetected = "CpuTopologyDetected";
|
||||
public const string SystemTrayInitialized = "SystemTrayInitialized";
|
||||
public const string NotificationSent = "NotificationSent";
|
||||
public const string ErrorRecovered = "ErrorRecovered";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Error categories
|
||||
/// </summary>
|
||||
public static class Errors
|
||||
{
|
||||
public const string ServiceFailure = "ServiceFailure";
|
||||
public const string ConfigurationError = "ConfigurationError";
|
||||
public const string FileSystemError = "FileSystemError";
|
||||
public const string PermissionError = "PermissionError";
|
||||
public const string NetworkError = "NetworkError";
|
||||
public const string WmiError = "WmiError";
|
||||
public const string UnhandledException = "UnhandledException";
|
||||
public const string ValidationError = "ValidationError";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performance events
|
||||
/// </summary>
|
||||
public static class Performance
|
||||
{
|
||||
public const string HighMemoryUsage = "HighMemoryUsage";
|
||||
public const string HighCpuUsage = "HighCpuUsage";
|
||||
public const string SlowOperation = "SlowOperation";
|
||||
public const string LargeLogFile = "LargeLogFile";
|
||||
public const string ProcessCountHigh = "ProcessCountHigh";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log categories for organizing log entries
|
||||
/// </summary>
|
||||
public static class LogCategories
|
||||
{
|
||||
public const string PowerPlan = "PowerPlan";
|
||||
public const string ProcessMonitoring = "ProcessMonitoring";
|
||||
public const string 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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Common log properties for structured logging
|
||||
/// </summary>
|
||||
public static class LogProperties
|
||||
{
|
||||
public const string ProcessName = "ProcessName";
|
||||
public const string ProcessId = "ProcessId";
|
||||
public const string PowerPlanId = "PowerPlanId";
|
||||
public const string PowerPlanName = "PowerPlanName";
|
||||
public const string GameName = "GameName";
|
||||
public const string UserId = "UserId";
|
||||
public const string SessionId = "SessionId";
|
||||
public const string CorrelationId = "CorrelationId";
|
||||
public const string Duration = "Duration";
|
||||
public const string ErrorCode = "ErrorCode";
|
||||
public const string StackTrace = "StackTrace";
|
||||
public const string MemoryUsage = "MemoryUsage";
|
||||
public const string CpuUsage = "CpuUsage";
|
||||
public const string ThreadId = "ThreadId";
|
||||
public const string Version = "Version";
|
||||
public const string Environment = "Environment";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for creating structured log data
|
||||
/// </summary>
|
||||
public static class LogDataBuilder
|
||||
{
|
||||
public static Dictionary<string, object> CreateProcessData(string processName, int processId)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ProcessName] = processName,
|
||||
[LogProperties.ProcessId] = processId
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePowerPlanData(string planId, string planName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.PowerPlanId] = planId,
|
||||
[LogProperties.PowerPlanName] = planName
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateGameData(string gameName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.GameName] = gameName
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePerformanceData(long memoryUsage, double cpuUsage)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.MemoryUsage] = memoryUsage,
|
||||
[LogProperties.CpuUsage] = cpuUsage
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateErrorData(Exception exception)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ErrorCode] = exception.HResult,
|
||||
[LogProperties.StackTrace] = exception.StackTrace ?? "N/A",
|
||||
["ExceptionType"] = exception.GetType().Name,
|
||||
["InnerException"] = exception.InnerException?.Message ?? "N/A"
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateTimingData(TimeSpan duration)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Duration] = duration.TotalMilliseconds
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateSystemData()
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Version] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown",
|
||||
[LogProperties.Environment] = Environment.OSVersion.ToString(),
|
||||
[LogProperties.ThreadId] = Thread.CurrentThread.ManagedThreadId,
|
||||
["MachineName"] = Environment.MachineName,
|
||||
["UserName"] = Environment.UserName
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Model representing a notification
|
||||
/// </summary>
|
||||
public partial class NotificationModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string title = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string message = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationType type = NotificationType.Information;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime timestamp = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private int durationMs = 3000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isRead = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isPersistent = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionText;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionCommand;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? iconPath;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationPriority priority = NotificationPriority.Normal;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? category;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? sourceService;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new notification
|
||||
/// </summary>
|
||||
public NotificationModel()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new notification with basic information
|
||||
/// </summary>
|
||||
public NotificationModel(string title, string message, NotificationType type = NotificationType.Information)
|
||||
{
|
||||
Title = title;
|
||||
Message = message;
|
||||
Type = type;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new notification with full information
|
||||
/// </summary>
|
||||
public NotificationModel(string title, string message, NotificationType type, int durationMs, bool isPersistent = false)
|
||||
{
|
||||
Title = title;
|
||||
Message = message;
|
||||
Type = type;
|
||||
DurationMs = durationMs;
|
||||
IsPersistent = isPersistent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the notification as read
|
||||
/// </summary>
|
||||
public void MarkAsRead()
|
||||
{
|
||||
IsRead = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display text for the notification type
|
||||
/// </summary>
|
||||
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"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets the formatted timestamp
|
||||
/// </summary>
|
||||
public string FormattedTimestamp => Timestamp.ToString("HH:mm:ss");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the formatted date and time
|
||||
/// </summary>
|
||||
public string FormattedDateTime => Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Types of notifications
|
||||
/// </summary>
|
||||
public enum NotificationType
|
||||
{
|
||||
Information,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
PowerPlanChange,
|
||||
ProcessMonitoring,
|
||||
CpuAffinity
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification priority levels
|
||||
/// </summary>
|
||||
public enum NotificationPriority
|
||||
{
|
||||
Low,
|
||||
Normal,
|
||||
High,
|
||||
Critical
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Configuration model for process monitoring and power plan associations
|
||||
/// </summary>
|
||||
public partial class ProcessMonitorConfiguration : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEventBasedMonitoringEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isFallbackPollingEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int pollingIntervalSeconds = 5;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool preventDuplicatePowerPlanChanges = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int powerPlanChangeDelayMs = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableLogging = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ProcessPowerPlanAssociation> associations = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastSavedDate = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private string configurationVersion = "1.0";
|
||||
|
||||
public ProcessMonitorConfiguration()
|
||||
{
|
||||
Associations = new List<ProcessPowerPlanAssociation>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all enabled associations sorted by priority (descending)
|
||||
/// </summary>
|
||||
public IEnumerable<ProcessPowerPlanAssociation> GetEnabledAssociations()
|
||||
{
|
||||
return Associations
|
||||
.Where(a => a.IsEnabled)
|
||||
.OrderByDescending(a => a.Priority)
|
||||
.ThenBy(a => a.ExecutableName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the best matching association for a process
|
||||
/// </summary>
|
||||
public ProcessPowerPlanAssociation? FindMatchingAssociation(ProcessModel process)
|
||||
{
|
||||
return GetEnabledAssociations()
|
||||
.FirstOrDefault(a => a.MatchesProcess(process));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds association by executable name
|
||||
/// </summary>
|
||||
public ProcessPowerPlanAssociation? FindAssociationByExecutable(string executableName)
|
||||
{
|
||||
return Associations
|
||||
.FirstOrDefault(a => a.MatchesExecutable(executableName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds or updates an association
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes an association
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the configuration
|
||||
/// </summary>
|
||||
public List<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents an association between an executable and a power plan
|
||||
/// </summary>
|
||||
public partial class ProcessPowerPlanAssociation : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string executableName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string executablePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Whether to match by exact executable name or path
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool matchByPath = false;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for this association (higher number = higher priority)
|
||||
/// Used when multiple associations could match the same process
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int priority = 0;
|
||||
|
||||
public ProcessPowerPlanAssociation()
|
||||
{
|
||||
}
|
||||
|
||||
public ProcessPowerPlanAssociation(string executableName, string powerPlanGuid, string powerPlanName)
|
||||
{
|
||||
ExecutableName = executableName;
|
||||
PowerPlanGuid = powerPlanGuid;
|
||||
PowerPlanName = powerPlanName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this association matches the given process
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this association matches the given executable name
|
||||
/// </summary>
|
||||
public bool MatchesExecutable(string executableName)
|
||||
{
|
||||
if (!IsEnabled) return false;
|
||||
return string.Equals(ExecutableName, executableName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
-4
@@ -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<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing application settings with JSON persistence
|
||||
/// </summary>
|
||||
public class ApplicationSettingsService : IApplicationSettingsService
|
||||
{
|
||||
private readonly ILogger<ApplicationSettingsService> _logger;
|
||||
private readonly string _settingsFilePath;
|
||||
private ApplicationSettingsModel _settings;
|
||||
|
||||
public event EventHandler<ApplicationSettingsChangedEventArgs>? SettingsChanged;
|
||||
|
||||
public ApplicationSettingsModel Settings => _settings;
|
||||
|
||||
public ApplicationSettingsService(ILogger<ApplicationSettingsService> 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<ApplicationSettingsModel>(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<ApplicationSettingsModel>(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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing Windows autostart functionality using registry
|
||||
/// </summary>
|
||||
public class AutostartService : IAutostartService
|
||||
{
|
||||
private const string REGISTRY_KEY_PATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
|
||||
private const string APPLICATION_NAME = "ThreadPilot";
|
||||
|
||||
private readonly ILogger<AutostartService> _logger;
|
||||
private bool _isAutostartEnabled;
|
||||
private string? _autostartPath;
|
||||
|
||||
public event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
public bool IsAutostartEnabled => _isAutostartEnabled;
|
||||
public string? AutostartPath => _autostartPath;
|
||||
|
||||
public AutostartService(ILogger<AutostartService> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
// Initialize current status
|
||||
_ = Task.Run(CheckAutostartStatusAsync);
|
||||
}
|
||||
|
||||
public async Task<bool> 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<bool> 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<bool> 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<bool> 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<string>();
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
args.Add("--start-minimized");
|
||||
}
|
||||
|
||||
// Add any other startup arguments as needed
|
||||
args.Add("--autostart");
|
||||
|
||||
return string.Join(" ", args);
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
|
||||
var location = assembly.Location;
|
||||
|
||||
// Handle .NET Core/5+ scenarios where Location might be empty
|
||||
if (string.IsNullOrEmpty(location))
|
||||
{
|
||||
location = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
|
||||
}
|
||||
|
||||
// If we're running from a .dll, try to find the .exe
|
||||
if (!string.IsNullOrEmpty(location) && location.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var exePath = Path.ChangeExtension(location, ".exe");
|
||||
if (File.Exists(exePath))
|
||||
{
|
||||
location = exePath;
|
||||
}
|
||||
}
|
||||
|
||||
return location;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to get executable path");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Base implementation for system services with common functionality
|
||||
/// </summary>
|
||||
public abstract class BaseSystemService : ISystemService, IDisposable
|
||||
{
|
||||
protected readonly ILogger Logger;
|
||||
private bool _isAvailable;
|
||||
private bool _disposed;
|
||||
|
||||
public bool IsAvailable
|
||||
{
|
||||
get => _isAvailable;
|
||||
protected set
|
||||
{
|
||||
if (_isAvailable != value)
|
||||
{
|
||||
_isAvailable = value;
|
||||
OnAvailabilityChanged(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler<ServiceAvailabilityChangedEventArgs>? 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Base interface for core system services that interact directly with the operating system
|
||||
/// </summary>
|
||||
public interface ISystemService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether the service is currently available and functional
|
||||
/// </summary>
|
||||
bool IsAvailable { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when the service availability changes
|
||||
/// </summary>
|
||||
event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the service
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Cleanup and dispose of service resources
|
||||
/// </summary>
|
||||
Task DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for service availability changes
|
||||
/// </summary>
|
||||
public class ServiceAvailabilityChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsAvailable { get; }
|
||||
public string? Reason { get; }
|
||||
|
||||
public ServiceAvailabilityChangedEventArgs(bool isAvailable, string? reason = null)
|
||||
{
|
||||
IsAvailable = isAvailable;
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for detecting CPU topology using WMI and Windows APIs
|
||||
/// </summary>
|
||||
public class CpuTopologyService : ICpuTopologyService
|
||||
{
|
||||
private readonly ILogger<CpuTopologyService> _logger;
|
||||
private CpuTopologyModel? _currentTopology;
|
||||
|
||||
public event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
public CpuTopologyModel? CurrentTopology => _currentTopology;
|
||||
|
||||
public CpuTopologyService(ILogger<CpuTopologyService> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task<CpuTopologyModel> 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<CpuAffinityPreset> GetAffinityPresets()
|
||||
{
|
||||
if (_currentTopology == null)
|
||||
return Enumerable.Empty<CpuAffinityPreset>();
|
||||
|
||||
var presets = new List<CpuAffinityPreset>();
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Enhanced logging service with file persistence and structured logging
|
||||
/// </summary>
|
||||
public class EnhancedLoggingService : IEnhancedLoggingService, IDisposable
|
||||
{
|
||||
private readonly ILogger<EnhancedLoggingService> _logger;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
private readonly SemaphoreSlim _fileLock = new(1, 1);
|
||||
private readonly ConcurrentQueue<LogEntry> _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<CriticalErrorEventArgs>? CriticalErrorOccurred;
|
||||
|
||||
public EnhancedLoggingService(ILogger<EnhancedLoggingService> 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<string, object>
|
||||
{
|
||||
["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<string, object>
|
||||
{
|
||||
["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<string, object>
|
||||
{
|
||||
["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<string, object>
|
||||
{
|
||||
["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<string, object>
|
||||
{
|
||||
["EventType"] = eventType
|
||||
};
|
||||
|
||||
await LogStructuredEventAsync("System", message, level, properties);
|
||||
}
|
||||
|
||||
public async Task LogErrorAsync(Exception exception, string context, Dictionary<string, object>? additionalData = null)
|
||||
{
|
||||
var properties = new Dictionary<string, object>
|
||||
{
|
||||
["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<string, object>
|
||||
{
|
||||
["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<string, object> 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<LogEntry>();
|
||||
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<LogEntry> 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<List<LogEntry>> GetRecentLogEntriesAsync(int count = 100)
|
||||
{
|
||||
return await GetLogEntriesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow);
|
||||
}
|
||||
|
||||
public async Task<List<LogEntry>> GetLogEntriesAsync(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
var entries = new List<LogEntry>();
|
||||
|
||||
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<List<LogEntry>> ReadLogEntriesFromFileAsync(string filePath, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
var entries = new List<LogEntry>();
|
||||
|
||||
try
|
||||
{
|
||||
var lines = await File.ReadAllLinesAsync(filePath);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
try
|
||||
{
|
||||
var logData = JsonSerializer.Deserialize<JsonElement>(line);
|
||||
var timestamp = DateTime.Parse(logData.GetProperty("timestamp").GetString()!);
|
||||
|
||||
if (timestamp >= fromDate && timestamp <= toDate)
|
||||
{
|
||||
var entry = new LogEntry
|
||||
{
|
||||
Timestamp = timestamp,
|
||||
Level = Enum.Parse<LogLevel>(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<Dictionary<string, object>>(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<LogFileStatistics> 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<string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing Game Boost mode functionality
|
||||
/// </summary>
|
||||
public class GameBoostService : IGameBoostService
|
||||
{
|
||||
private readonly ILogger<GameBoostService> _logger;
|
||||
private readonly IPowerPlanService _powerPlanService;
|
||||
private readonly IProcessService _processService;
|
||||
private readonly INotificationService _notificationService;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
|
||||
private ApplicationSettingsModel _settings;
|
||||
private bool _isGameBoostActive;
|
||||
private ProcessModel? _currentGameProcess;
|
||||
private string? _previousPowerPlanId;
|
||||
private DateTime? _gameBoostStartTime;
|
||||
private readonly List<string> _knownGameExecutables;
|
||||
|
||||
public event EventHandler<GameBoostActivatedEventArgs>? GameBoostActivated;
|
||||
public event EventHandler<GameBoostDeactivatedEventArgs>? GameBoostDeactivated;
|
||||
public event EventHandler<GameDetectedEventArgs>? GameDetected;
|
||||
|
||||
public bool IsGameBoostActive => _isGameBoostActive;
|
||||
public ProcessModel? CurrentGameProcess => _currentGameProcess;
|
||||
public IReadOnlyList<string> KnownGameExecutables => _knownGameExecutables.AsReadOnly();
|
||||
|
||||
public GameBoostService(
|
||||
ILogger<GameBoostService> logger,
|
||||
IPowerPlanService powerPlanService,
|
||||
IProcessService processService,
|
||||
INotificationService notificationService,
|
||||
IApplicationSettingsService settingsService)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));
|
||||
_processService = processService ?? throw new ArgumentNullException(nameof(processService));
|
||||
_notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
|
||||
_settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
|
||||
_settings = _settingsService.Settings;
|
||||
_knownGameExecutables = InitializeKnownGames();
|
||||
|
||||
// Subscribe to settings changes
|
||||
_settingsService.SettingsChanged += OnSettingsChanged;
|
||||
|
||||
_logger.LogInformation("Game Boost service initialized with {Count} known games", _knownGameExecutables.Count);
|
||||
}
|
||||
|
||||
public async Task<bool> EnableGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_settings.EnableGameBoostMode)
|
||||
{
|
||||
_logger.LogWarning("Game Boost mode is disabled in settings");
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Game Boost mode enabled");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to enable Game Boost mode");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DisableGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isGameBoostActive)
|
||||
{
|
||||
await DeactivateGameBoostAsync();
|
||||
}
|
||||
|
||||
_logger.LogInformation("Game Boost mode disabled");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to disable Game Boost mode");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ActivateGameBoostAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isGameBoostActive && _currentGameProcess?.ProcessId == process.ProcessId)
|
||||
{
|
||||
_logger.LogDebug("Game Boost already active for process {ProcessName}", process.Name);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deactivate current boost if active
|
||||
if (_isGameBoostActive)
|
||||
{
|
||||
await DeactivateGameBoostAsync();
|
||||
}
|
||||
|
||||
// Store current power plan
|
||||
var currentPowerPlan = await _powerPlanService.GetActivePowerPlan();
|
||||
_previousPowerPlanId = currentPowerPlan?.Guid;
|
||||
|
||||
// Apply Game Boost power plan
|
||||
var gameBoostPowerPlanId = !string.IsNullOrEmpty(_settings.GameBoostPowerPlanId)
|
||||
? _settings.GameBoostPowerPlanId
|
||||
: await GetHighPerformancePowerPlanIdAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(gameBoostPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(gameBoostPowerPlanId);
|
||||
}
|
||||
|
||||
// Set high priority if enabled
|
||||
if (_settings.GameBoostSetHighPriority)
|
||||
{
|
||||
await SetProcessPriorityAsync(process, ProcessPriorityClass.High);
|
||||
}
|
||||
|
||||
// Optimize CPU affinity if enabled
|
||||
if (_settings.GameBoostOptimizeCpuAffinity)
|
||||
{
|
||||
await OptimizeCpuAffinityAsync(process);
|
||||
}
|
||||
|
||||
_isGameBoostActive = true;
|
||||
_currentGameProcess = process;
|
||||
_gameBoostStartTime = DateTime.Now;
|
||||
|
||||
_logger.LogInformation("Game Boost activated for {ProcessName} (PID: {ProcessId})",
|
||||
process.Name, process.ProcessId);
|
||||
|
||||
// Fire events
|
||||
GameDetected?.Invoke(this, new GameDetectedEventArgs(process, _knownGameExecutables.Contains(process.Name.ToLowerInvariant())));
|
||||
GameBoostActivated?.Invoke(this, new GameBoostActivatedEventArgs(process, gameBoostPowerPlanId ?? ""));
|
||||
|
||||
await _notificationService.ShowSuccessNotificationAsync(
|
||||
"Game Boost Activated",
|
||||
$"Game Boost mode activated for {process.Name}");
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to activate Game Boost for process {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeactivateGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_isGameBoostActive)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var duration = _gameBoostStartTime.HasValue
|
||||
? DateTime.Now - _gameBoostStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
|
||||
// Restore previous power plan
|
||||
if (!string.IsNullOrEmpty(_previousPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(_previousPowerPlanId);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(_settings.DefaultPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(_settings.DefaultPowerPlanId);
|
||||
}
|
||||
|
||||
var gameProcess = _currentGameProcess;
|
||||
var restoredPowerPlanId = _previousPowerPlanId ?? _settings.DefaultPowerPlanId;
|
||||
|
||||
_isGameBoostActive = false;
|
||||
_currentGameProcess = null;
|
||||
_previousPowerPlanId = null;
|
||||
_gameBoostStartTime = null;
|
||||
|
||||
_logger.LogInformation("Game Boost deactivated after {Duration}", duration);
|
||||
|
||||
GameBoostDeactivated?.Invoke(this, new GameBoostDeactivatedEventArgs(
|
||||
gameProcess, restoredPowerPlanId, duration));
|
||||
|
||||
await _notificationService.ShowNotificationAsync(
|
||||
"Game Boost Deactivated",
|
||||
$"Game Boost mode deactivated after {duration:hh\\:mm\\:ss}",
|
||||
NotificationType.Information);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deactivate Game Boost");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> AddKnownGameAsync(string executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
return false;
|
||||
|
||||
var normalizedName = executableName.ToLowerInvariant();
|
||||
if (!_knownGameExecutables.Contains(normalizedName))
|
||||
{
|
||||
_knownGameExecutables.Add(normalizedName);
|
||||
_logger.LogInformation("Added known game: {ExecutableName}", executableName);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveKnownGameAsync(string executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
return false;
|
||||
|
||||
var normalizedName = executableName.ToLowerInvariant();
|
||||
var removed = _knownGameExecutables.Remove(normalizedName);
|
||||
|
||||
if (removed)
|
||||
{
|
||||
_logger.LogInformation("Removed known game: {ExecutableName}", executableName);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> GetKnownGameExecutables()
|
||||
{
|
||||
return _knownGameExecutables.ToList().AsReadOnly();
|
||||
}
|
||||
|
||||
public bool IsGameProcess(ProcessModel process)
|
||||
{
|
||||
if (process == null || string.IsNullOrEmpty(process.Name))
|
||||
return false;
|
||||
|
||||
var processName = process.Name.ToLowerInvariant();
|
||||
|
||||
// Check against known games list
|
||||
if (_knownGameExecutables.Contains(processName))
|
||||
return true;
|
||||
|
||||
// Auto-detection heuristics (if enabled)
|
||||
if (_settings.GameBoostAutoDetectGames)
|
||||
{
|
||||
return IsLikelyGameProcess(process);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
_settings = e.NewSettings;
|
||||
_logger.LogDebug("Game Boost settings updated");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error updating Game Boost settings");
|
||||
}
|
||||
}
|
||||
|
||||
private List<string> InitializeKnownGames()
|
||||
{
|
||||
return new List<string>
|
||||
{
|
||||
// Game Launchers
|
||||
"steam.exe",
|
||||
"steamwebhelper.exe",
|
||||
"origin.exe",
|
||||
"epicgameslauncher.exe",
|
||||
"uplay.exe",
|
||||
"ubisoft connect.exe",
|
||||
"battlenet.exe",
|
||||
"battle.net.exe",
|
||||
"gog.exe",
|
||||
"gog galaxy.exe",
|
||||
"rockstarlauncher.exe",
|
||||
"bethesdanetlauncher.exe",
|
||||
"ea desktop.exe",
|
||||
"xbox.exe",
|
||||
"xboxapp.exe",
|
||||
"gamepass.exe",
|
||||
|
||||
// Popular Games - FPS/Shooters
|
||||
"csgo.exe",
|
||||
"cs2.exe",
|
||||
"valorant.exe",
|
||||
"valorant-win64-shipping.exe",
|
||||
"fortniteclient-win64-shipping.exe",
|
||||
"fortnite.exe",
|
||||
"apex_legends.exe",
|
||||
"r5apex.exe",
|
||||
"overwatch.exe",
|
||||
"overwatch2.exe",
|
||||
"cod.exe",
|
||||
"modernwarfare.exe",
|
||||
"warzone.exe",
|
||||
"blackops.exe",
|
||||
"rainbow6.exe",
|
||||
"rainbowsix.exe",
|
||||
"pubg.exe",
|
||||
"tslgame.exe",
|
||||
"bf1.exe",
|
||||
"bfv.exe",
|
||||
"bf2042.exe",
|
||||
"titanfall2.exe",
|
||||
"doom.exe",
|
||||
"doomslayers.exe",
|
||||
"doom eternal.exe",
|
||||
"halo.exe",
|
||||
"haloinfinite.exe",
|
||||
"destiny2.exe",
|
||||
|
||||
// Popular Games - MOBA/Strategy
|
||||
"dota2.exe",
|
||||
"league of legends.exe",
|
||||
"lol.exe",
|
||||
"riotclientservices.exe",
|
||||
"teamfighttactics.exe",
|
||||
"starcraft2.exe",
|
||||
"sc2.exe",
|
||||
"warcraft3.exe",
|
||||
"aoe2de.exe",
|
||||
"aoe4.exe",
|
||||
"civilization6.exe",
|
||||
"civ6.exe",
|
||||
"totalwar.exe",
|
||||
|
||||
// Popular Games - RPG/Adventure
|
||||
"witcher3.exe",
|
||||
"cyberpunk2077.exe",
|
||||
"skyrim.exe",
|
||||
"skyrimse.exe",
|
||||
"fallout4.exe",
|
||||
"fallout76.exe",
|
||||
"elderscrollsonline.exe",
|
||||
"wow.exe",
|
||||
"worldofwarcraft.exe",
|
||||
"ffxiv.exe",
|
||||
"ffxiv_dx11.exe",
|
||||
"guildwars2.exe",
|
||||
"newworld.exe",
|
||||
"lostark.exe",
|
||||
"diablo3.exe",
|
||||
"diablo4.exe",
|
||||
"pathofexile.exe",
|
||||
"borderlands3.exe",
|
||||
"masseffect.exe",
|
||||
"dragonage.exe",
|
||||
"assassinscreed.exe",
|
||||
"farcry.exe",
|
||||
"watchdogs.exe",
|
||||
|
||||
// Popular Games - Open World/Action
|
||||
"gta5.exe",
|
||||
"gtav.exe",
|
||||
"rdr2.exe",
|
||||
"reddeadredemption2.exe",
|
||||
"minecraft.exe",
|
||||
"minecraftlauncher.exe",
|
||||
"javaw.exe", // Minecraft Java
|
||||
"terraria.exe",
|
||||
"stardewvalley.exe",
|
||||
"subnautica.exe",
|
||||
"nomanssky.exe",
|
||||
"spiderman.exe",
|
||||
"godofwar.exe",
|
||||
"horizonzerodawn.exe",
|
||||
"deathstranding.exe",
|
||||
|
||||
// Popular Games - Racing/Sports
|
||||
"forza.exe",
|
||||
"forzahorizon.exe",
|
||||
"granturismo.exe",
|
||||
"f1.exe",
|
||||
"dirt.exe",
|
||||
"wreckfest.exe",
|
||||
"fifa.exe",
|
||||
"nba2k.exe",
|
||||
"madden.exe",
|
||||
"rocketleague.exe",
|
||||
|
||||
// Popular Games - Simulation/Building
|
||||
"citiesskylines.exe",
|
||||
"simcity.exe",
|
||||
"planetcoaster.exe",
|
||||
"twopointcampus.exe",
|
||||
"kerbalspaceprogram.exe",
|
||||
"factorio.exe",
|
||||
"satisfactory.exe",
|
||||
"valheim.exe",
|
||||
"rust.exe",
|
||||
"ark.exe",
|
||||
"7daystodie.exe",
|
||||
"greenhell.exe",
|
||||
"theforest.exe",
|
||||
|
||||
// VR Games
|
||||
"vrchat.exe",
|
||||
"beatsaber.exe",
|
||||
"halflife alyx.exe",
|
||||
"pavlov.exe",
|
||||
"boneworks.exe",
|
||||
|
||||
// Indie/Popular Smaller Games
|
||||
"amongus.exe",
|
||||
"fallguys.exe",
|
||||
"cuphead.exe",
|
||||
"hollowknight.exe",
|
||||
"celeste.exe",
|
||||
"ori.exe",
|
||||
"hades.exe",
|
||||
"deadcells.exe",
|
||||
"riskofrain2.exe",
|
||||
"deeprockgalactic.exe",
|
||||
"seaofthieves.exe",
|
||||
"phasmophobia.exe",
|
||||
"genshinimpact.exe",
|
||||
"honkaiimpact.exe"
|
||||
};
|
||||
}
|
||||
|
||||
private bool IsLikelyGameProcess(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
var processName = process.Name.ToLowerInvariant();
|
||||
var processPath = process.ExecutablePath?.ToLowerInvariant() ?? "";
|
||||
|
||||
// Skip system processes and common applications
|
||||
if (IsSystemOrCommonProcess(processName))
|
||||
return false;
|
||||
|
||||
// Check for game-related keywords in process name
|
||||
if (HasGameKeywords(processName))
|
||||
return true;
|
||||
|
||||
// Check for game-related paths
|
||||
if (HasGamePath(processPath))
|
||||
return true;
|
||||
|
||||
// Check for game engines
|
||||
if (HasGameEngineIndicators(processName, processPath))
|
||||
return true;
|
||||
|
||||
// Check for executable patterns common in games
|
||||
if (HasGameExecutablePatterns(processName))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error in game detection heuristics for process {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsSystemOrCommonProcess(string processName)
|
||||
{
|
||||
var systemProcesses = new[]
|
||||
{
|
||||
"explorer.exe", "dwm.exe", "winlogon.exe", "csrss.exe", "smss.exe", "wininit.exe",
|
||||
"services.exe", "lsass.exe", "svchost.exe", "taskhost.exe", "taskhostw.exe",
|
||||
"conhost.exe", "audiodg.exe", "spoolsv.exe", "winlogon.exe", "userinit.exe",
|
||||
"chrome.exe", "firefox.exe", "msedge.exe", "iexplore.exe", "opera.exe",
|
||||
"notepad.exe", "calc.exe", "mspaint.exe", "wordpad.exe", "cmd.exe", "powershell.exe",
|
||||
"winword.exe", "excel.exe", "powerpoint.exe", "outlook.exe", "onenote.exe",
|
||||
"photoshop.exe", "illustrator.exe", "premiere.exe", "aftereffects.exe",
|
||||
"code.exe", "devenv.exe", "rider.exe", "intellij.exe", "eclipse.exe",
|
||||
"discord.exe", "slack.exe", "teams.exe", "zoom.exe", "skype.exe",
|
||||
"spotify.exe", "vlc.exe", "wmplayer.exe", "itunes.exe", "winamp.exe",
|
||||
"7z.exe", "winrar.exe", "winzip.exe", "filezilla.exe", "putty.exe"
|
||||
};
|
||||
|
||||
return systemProcesses.Contains(processName);
|
||||
}
|
||||
|
||||
private bool HasGameKeywords(string processName)
|
||||
{
|
||||
var gameKeywords = new[]
|
||||
{
|
||||
"game", "launcher", "client", "engine", "unity", "unreal", "godot", "cryengine",
|
||||
"steam", "epic", "origin", "uplay", "battlenet", "gog", "rockstar",
|
||||
"minecraft", "roblox", "fortnite", "valorant", "csgo", "dota", "lol",
|
||||
"wow", "overwatch", "apex", "pubg", "cod", "battlefield", "destiny",
|
||||
"cyberpunk", "witcher", "skyrim", "fallout", "gta", "rdr", "assassin",
|
||||
"farcry", "watchdog", "borderlands", "diablo", "starcraft", "warcraft",
|
||||
"civilization", "totalwar", "aoe", "fifa", "nba", "madden", "forza",
|
||||
"racing", "simulator", "tycoon", "builder", "strategy", "rpg", "mmo",
|
||||
"shooter", "adventure", "action", "puzzle", "platformer", "indie"
|
||||
};
|
||||
|
||||
return gameKeywords.Any(keyword => processName.Contains(keyword));
|
||||
}
|
||||
|
||||
private bool HasGamePath(string processPath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(processPath))
|
||||
return false;
|
||||
|
||||
var gamePaths = new[]
|
||||
{
|
||||
@"\steam\steamapps\", @"\steamapps\common\", @"\steam games\",
|
||||
@"\epic games\", @"\epicgames\", @"\epic\",
|
||||
@"\origin games\", @"\origin\", @"\ea games\",
|
||||
@"\ubisoft\", @"\uplay\", @"\ubisoft game launcher\",
|
||||
@"\gog galaxy\", @"\gog games\", @"\gog.com\",
|
||||
@"\battle.net\", @"\battlenet\", @"\blizzard\",
|
||||
@"\rockstar games\", @"\rockstar\",
|
||||
@"\xbox games\", @"\microsoft games\", @"\windowsapps\",
|
||||
@"\games\", @"\gaming\", @"\my games\",
|
||||
@"\program files\games\", @"\program files (x86)\games\",
|
||||
@"\minecraft\", @"\roblox\", @"\riot games\",
|
||||
@"\square enix\", @"\activision\", @"\electronic arts\",
|
||||
@"\2k games\", @"\bethesda\", @"\cd projekt red\",
|
||||
@"\valve\", @"\id software\", @"\bungie\"
|
||||
};
|
||||
|
||||
return gamePaths.Any(path => processPath.Contains(path));
|
||||
}
|
||||
|
||||
private bool HasGameEngineIndicators(string processName, string processPath)
|
||||
{
|
||||
var engineIndicators = new[]
|
||||
{
|
||||
"unity", "unreal", "ue4", "ue5", "godot", "cryengine", "frostbite",
|
||||
"source", "idtech", "creation", "anvil", "dunia", "snowdrop",
|
||||
"decima", "fox", "mt framework", "luminous", "crystal tools",
|
||||
"gamebryo", "havok", "physx", "directx", "opengl", "vulkan"
|
||||
};
|
||||
|
||||
return engineIndicators.Any(indicator =>
|
||||
processName.Contains(indicator) || processPath.Contains(indicator));
|
||||
}
|
||||
|
||||
private bool HasGameExecutablePatterns(string processName)
|
||||
{
|
||||
// Common patterns in game executables
|
||||
var patterns = new[]
|
||||
{
|
||||
// Shipping builds (Unreal Engine)
|
||||
"shipping.exe", "-shipping.exe", "_shipping.exe",
|
||||
// Win64 builds
|
||||
"win64.exe", "-win64.exe", "_win64.exe",
|
||||
// Game suffixes
|
||||
"game.exe", "_game.exe", "-game.exe",
|
||||
// Client executables
|
||||
"client.exe", "_client.exe", "-client.exe",
|
||||
// Launcher patterns
|
||||
"launcher.exe", "_launcher.exe", "-launcher.exe",
|
||||
// Engine patterns
|
||||
"engine.exe", "_engine.exe", "-engine.exe",
|
||||
// Common game number patterns (sequels)
|
||||
"2.exe", "3.exe", "4.exe", "5.exe", "2077.exe", "2042.exe"
|
||||
};
|
||||
|
||||
return patterns.Any(pattern => processName.EndsWith(pattern));
|
||||
}
|
||||
|
||||
private async Task<string?> GetHighPerformancePowerPlanIdAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var powerPlans = await _powerPlanService.GetPowerPlansAsync();
|
||||
var highPerformancePlan = powerPlans.FirstOrDefault(p =>
|
||||
p.Name.Contains("High performance", StringComparison.OrdinalIgnoreCase) ||
|
||||
p.Name.Contains("Ultimate Performance", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
return highPerformancePlan?.Guid;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to get high performance power plan");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SetProcessPriorityAsync(ProcessModel processModel, ProcessPriorityClass priority)
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = Process.GetProcessById(processModel.ProcessId);
|
||||
process.PriorityClass = priority;
|
||||
_logger.LogDebug("Set process {ProcessName} priority to {Priority}", processModel.Name, priority);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to set process priority for {ProcessName}", processModel.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OptimizeCpuAffinityAsync(ProcessModel processModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
// This would integrate with the CPU topology service
|
||||
// For now, just log the intent
|
||||
_logger.LogDebug("CPU affinity optimization requested for {ProcessName}", processModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to optimize CPU affinity for {ProcessName}", processModel.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing application settings
|
||||
/// </summary>
|
||||
public interface IApplicationSettingsService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when settings are changed
|
||||
/// </summary>
|
||||
event EventHandler<ApplicationSettingsChangedEventArgs>? SettingsChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current application settings
|
||||
/// </summary>
|
||||
ApplicationSettingsModel Settings { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads settings from storage
|
||||
/// </summary>
|
||||
Task LoadSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Saves current settings to storage
|
||||
/// </summary>
|
||||
Task SaveSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Updates settings and saves them
|
||||
/// </summary>
|
||||
Task UpdateSettingsAsync(ApplicationSettingsModel newSettings);
|
||||
|
||||
/// <summary>
|
||||
/// Resets settings to default values
|
||||
/// </summary>
|
||||
Task ResetToDefaultsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings file path
|
||||
/// </summary>
|
||||
string GetSettingsFilePath();
|
||||
|
||||
/// <summary>
|
||||
/// Validates settings and fixes any invalid values
|
||||
/// </summary>
|
||||
void ValidateAndFixSettings();
|
||||
|
||||
/// <summary>
|
||||
/// Exports settings to a file
|
||||
/// </summary>
|
||||
Task ExportSettingsAsync(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// Imports settings from a file
|
||||
/// </summary>
|
||||
Task ImportSettingsAsync(string filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for settings changed event
|
||||
/// </summary>
|
||||
public class ApplicationSettingsChangedEventArgs : EventArgs
|
||||
{
|
||||
public ApplicationSettingsModel OldSettings { get; }
|
||||
public ApplicationSettingsModel NewSettings { get; }
|
||||
public string[] ChangedProperties { get; }
|
||||
|
||||
public ApplicationSettingsChangedEventArgs(
|
||||
ApplicationSettingsModel oldSettings,
|
||||
ApplicationSettingsModel newSettings,
|
||||
string[] changedProperties)
|
||||
{
|
||||
OldSettings = oldSettings;
|
||||
NewSettings = newSettings;
|
||||
ChangedProperties = changedProperties;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for managing Windows autostart functionality
|
||||
/// </summary>
|
||||
public interface IAutostartService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when autostart status changes
|
||||
/// </summary>
|
||||
event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the application is currently set to autostart with Windows
|
||||
/// </summary>
|
||||
bool IsAutostartEnabled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current autostart registry entry path
|
||||
/// </summary>
|
||||
string? AutostartPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Enables autostart with Windows
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to start the application minimized</param>
|
||||
/// <returns>True if successful, false otherwise</returns>
|
||||
Task<bool> EnableAutostartAsync(bool startMinimized = true);
|
||||
|
||||
/// <summary>
|
||||
/// Disables autostart with Windows
|
||||
/// </summary>
|
||||
/// <returns>True if successful, false otherwise</returns>
|
||||
Task<bool> DisableAutostartAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if autostart is currently enabled
|
||||
/// </summary>
|
||||
/// <returns>True if autostart is enabled, false otherwise</returns>
|
||||
Task<bool> CheckAutostartStatusAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Updates the autostart entry with new parameters
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to start minimized</param>
|
||||
/// <returns>True if successful, false otherwise</returns>
|
||||
Task<bool> UpdateAutostartAsync(bool startMinimized = true);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command line arguments for autostart
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to include start minimized flag</param>
|
||||
/// <returns>Command line arguments string</returns>
|
||||
string GetAutostartArguments(bool startMinimized = true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for autostart status changes
|
||||
/// </summary>
|
||||
public class AutostartStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for detecting and managing CPU topology information
|
||||
/// </summary>
|
||||
public interface ICpuTopologyService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when CPU topology is detected or updated
|
||||
/// </summary>
|
||||
event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current CPU topology information
|
||||
/// </summary>
|
||||
CpuTopologyModel? CurrentTopology { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Detects CPU topology information
|
||||
/// </summary>
|
||||
Task<CpuTopologyModel> DetectTopologyAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets available affinity presets based on current topology
|
||||
/// </summary>
|
||||
IEnumerable<CpuAffinityPreset> GetAffinityPresets();
|
||||
|
||||
/// <summary>
|
||||
/// Validates if an affinity mask is valid for the current system
|
||||
/// </summary>
|
||||
bool IsAffinityMaskValid(long affinityMask);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum number of logical cores supported
|
||||
/// </summary>
|
||||
int GetMaxLogicalCores();
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes topology information (useful for hot-plug scenarios)
|
||||
/// </summary>
|
||||
Task RefreshTopologyAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for CPU topology detection
|
||||
/// </summary>
|
||||
public class CpuTopologyDetectedEventArgs : EventArgs
|
||||
{
|
||||
public CpuTopologyModel Topology { get; }
|
||||
public bool DetectionSuccessful { get; }
|
||||
public string? ErrorMessage { get; }
|
||||
public DateTime DetectionTime { get; }
|
||||
|
||||
public CpuTopologyDetectedEventArgs(CpuTopologyModel topology, bool successful, string? errorMessage = null)
|
||||
{
|
||||
Topology = topology;
|
||||
DetectionSuccessful = successful;
|
||||
ErrorMessage = errorMessage;
|
||||
DetectionTime = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Enhanced logging service interface for persistent, structured logging
|
||||
/// </summary>
|
||||
public interface IEnhancedLoggingService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the current log file path
|
||||
/// </summary>
|
||||
string CurrentLogFilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the log directory path
|
||||
/// </summary>
|
||||
string LogDirectoryPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether debug logging is enabled
|
||||
/// </summary>
|
||||
bool IsDebugLoggingEnabled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when a critical error occurs
|
||||
/// </summary>
|
||||
event EventHandler<CriticalErrorEventArgs>? CriticalErrorOccurred;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the logging service
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Log a power plan change event
|
||||
/// </summary>
|
||||
Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason, string? processName = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log a process monitoring event
|
||||
/// </summary>
|
||||
Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details);
|
||||
|
||||
/// <summary>
|
||||
/// Log a game boost event
|
||||
/// </summary>
|
||||
Task LogGameBoostEventAsync(string eventType, string gameName, string details);
|
||||
|
||||
/// <summary>
|
||||
/// Log a user action
|
||||
/// </summary>
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log a system event
|
||||
/// </summary>
|
||||
Task LogSystemEventAsync(string eventType, string message, LogLevel level = LogLevel.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Log an error with structured data
|
||||
/// </summary>
|
||||
Task LogErrorAsync(Exception exception, string context, Dictionary<string, object>? additionalData = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log application startup/shutdown events
|
||||
/// </summary>
|
||||
Task LogApplicationLifecycleEventAsync(string eventType, string details);
|
||||
|
||||
/// <summary>
|
||||
/// Get recent log entries
|
||||
/// </summary>
|
||||
Task<List<LogEntry>> GetRecentLogEntriesAsync(int count = 100);
|
||||
|
||||
/// <summary>
|
||||
/// Get log entries for a specific date range
|
||||
/// </summary>
|
||||
Task<List<LogEntry>> GetLogEntriesAsync(DateTime fromDate, DateTime toDate);
|
||||
|
||||
/// <summary>
|
||||
/// Clean up old log files based on retention policy
|
||||
/// </summary>
|
||||
Task CleanupOldLogsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get log file statistics
|
||||
/// </summary>
|
||||
Task<LogFileStatistics> GetLogStatisticsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Export logs to a file
|
||||
/// </summary>
|
||||
Task<string> ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null);
|
||||
|
||||
/// <summary>
|
||||
/// Update logging configuration
|
||||
/// </summary>
|
||||
Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for critical errors
|
||||
/// </summary>
|
||||
public class CriticalErrorEventArgs : EventArgs
|
||||
{
|
||||
public Exception Exception { get; }
|
||||
public string Context { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
public Dictionary<string, object> AdditionalData { get; }
|
||||
|
||||
public CriticalErrorEventArgs(Exception exception, string context, Dictionary<string, object>? additionalData = null)
|
||||
{
|
||||
Exception = exception;
|
||||
Context = context;
|
||||
Timestamp = DateTime.UtcNow;
|
||||
AdditionalData = additionalData ?? new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a log entry
|
||||
/// </summary>
|
||||
public class LogEntry
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
public LogLevel Level { get; set; }
|
||||
public string Category { get; set; } = string.Empty;
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public string? Exception { get; set; }
|
||||
public Dictionary<string, object> Properties { get; set; } = new();
|
||||
public string? CorrelationId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log file statistics
|
||||
/// </summary>
|
||||
public class LogFileStatistics
|
||||
{
|
||||
public long CurrentFileSizeBytes { get; set; }
|
||||
public int TotalLogFiles { get; set; }
|
||||
public long TotalLogSizeBytes { get; set; }
|
||||
public DateTime OldestLogDate { get; set; }
|
||||
public DateTime NewestLogDate { get; set; }
|
||||
public int ErrorCount { get; set; }
|
||||
public int WarningCount { get; set; }
|
||||
public int InfoCount { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for Game Boost mode functionality
|
||||
/// </summary>
|
||||
public interface IGameBoostService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when Game Boost mode is activated
|
||||
/// </summary>
|
||||
event EventHandler<GameBoostActivatedEventArgs>? GameBoostActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when Game Boost mode is deactivated
|
||||
/// </summary>
|
||||
event EventHandler<GameBoostDeactivatedEventArgs>? GameBoostDeactivated;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a game is detected
|
||||
/// </summary>
|
||||
event EventHandler<GameDetectedEventArgs>? GameDetected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether Game Boost mode is currently active
|
||||
/// </summary>
|
||||
bool IsGameBoostActive { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the currently detected game process
|
||||
/// </summary>
|
||||
ProcessModel? CurrentGameProcess { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of known game executables
|
||||
/// </summary>
|
||||
IReadOnlyList<string> KnownGameExecutables { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of known game executables as a collection
|
||||
/// </summary>
|
||||
IReadOnlyList<string> GetKnownGameExecutables();
|
||||
|
||||
/// <summary>
|
||||
/// Enables Game Boost mode
|
||||
/// </summary>
|
||||
Task<bool> EnableGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Disables Game Boost mode
|
||||
/// </summary>
|
||||
Task<bool> DisableGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Manually activates Game Boost for a specific process
|
||||
/// </summary>
|
||||
/// <param name="process">The process to boost</param>
|
||||
Task<bool> ActivateGameBoostAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Manually deactivates Game Boost
|
||||
/// </summary>
|
||||
Task<bool> DeactivateGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Adds a game executable to the known games list
|
||||
/// </summary>
|
||||
/// <param name="executableName">Name of the executable (e.g., "game.exe")</param>
|
||||
Task<bool> AddKnownGameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a game executable from the known games list
|
||||
/// </summary>
|
||||
/// <param name="executableName">Name of the executable to remove</param>
|
||||
Task<bool> RemoveKnownGameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a process is considered a game
|
||||
/// </summary>
|
||||
/// <param name="process">The process to check</param>
|
||||
bool IsGameProcess(ProcessModel process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for Game Boost activation
|
||||
/// </summary>
|
||||
public class GameBoostActivatedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel GameProcess { get; }
|
||||
public string PowerPlanId { get; }
|
||||
public DateTime ActivatedAt { get; }
|
||||
|
||||
public GameBoostActivatedEventArgs(ProcessModel gameProcess, string powerPlanId)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
PowerPlanId = powerPlanId;
|
||||
ActivatedAt = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for Game Boost deactivation
|
||||
/// </summary>
|
||||
public class GameBoostDeactivatedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel? GameProcess { get; }
|
||||
public string? RestoredPowerPlanId { get; }
|
||||
public DateTime DeactivatedAt { get; }
|
||||
public TimeSpan Duration { get; }
|
||||
|
||||
public GameBoostDeactivatedEventArgs(ProcessModel? gameProcess, string? restoredPowerPlanId, TimeSpan duration)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
RestoredPowerPlanId = restoredPowerPlanId;
|
||||
DeactivatedAt = DateTime.Now;
|
||||
Duration = duration;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for game detection
|
||||
/// </summary>
|
||||
public class GameDetectedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel GameProcess { get; }
|
||||
public bool IsKnownGame { get; }
|
||||
public DateTime DetectedAt { get; }
|
||||
|
||||
public GameDetectedEventArgs(ProcessModel gameProcess, bool isKnownGame)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
IsKnownGame = isKnownGame;
|
||||
DetectedAt = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing notifications (balloon tips and toast notifications)
|
||||
/// </summary>
|
||||
public interface INotificationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when a notification is shown
|
||||
/// </summary>
|
||||
event EventHandler<NotificationEventArgs>? NotificationShown;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a notification is dismissed
|
||||
/// </summary>
|
||||
event EventHandler<NotificationEventArgs>? NotificationDismissed;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a notification action is clicked
|
||||
/// </summary>
|
||||
event EventHandler<NotificationActionEventArgs>? NotificationActionClicked;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the notification history
|
||||
/// </summary>
|
||||
IReadOnlyList<NotificationModel> NotificationHistory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Shows a simple notification
|
||||
/// </summary>
|
||||
Task ShowNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification with custom settings
|
||||
/// </summary>
|
||||
Task ShowNotificationAsync(NotificationModel notification);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a balloon tip notification
|
||||
/// </summary>
|
||||
Task ShowBalloonTipAsync(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a Windows toast notification (if available)
|
||||
/// </summary>
|
||||
Task ShowToastNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for power plan changes
|
||||
/// </summary>
|
||||
Task ShowPowerPlanChangeNotificationAsync(string oldPlan, string newPlan, string processName = "");
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for process monitoring events
|
||||
/// </summary>
|
||||
Task ShowProcessMonitoringNotificationAsync(string message, bool isEnabled);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for CPU affinity changes
|
||||
/// </summary>
|
||||
Task ShowCpuAffinityNotificationAsync(string processName, string affinityInfo);
|
||||
|
||||
/// <summary>
|
||||
/// Shows an error notification
|
||||
/// </summary>
|
||||
Task ShowErrorNotificationAsync(string title, string message, Exception? exception = null);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a success notification
|
||||
/// </summary>
|
||||
Task ShowSuccessNotificationAsync(string title, string message);
|
||||
|
||||
/// <summary>
|
||||
/// Dismisses a specific notification
|
||||
/// </summary>
|
||||
Task DismissNotificationAsync(string notificationId);
|
||||
|
||||
/// <summary>
|
||||
/// Dismisses all notifications
|
||||
/// </summary>
|
||||
Task DismissAllNotificationsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Clears notification history
|
||||
/// </summary>
|
||||
Task ClearNotificationHistoryAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets unread notification count
|
||||
/// </summary>
|
||||
int GetUnreadNotificationCount();
|
||||
|
||||
/// <summary>
|
||||
/// Marks all notifications as read
|
||||
/// </summary>
|
||||
Task MarkAllNotificationsAsReadAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if notifications are enabled for the given type
|
||||
/// </summary>
|
||||
bool AreNotificationsEnabled(NotificationType type);
|
||||
|
||||
/// <summary>
|
||||
/// Updates notification settings
|
||||
/// </summary>
|
||||
void UpdateSettings(ApplicationSettingsModel settings);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the notification service
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the notification service
|
||||
/// </summary>
|
||||
void Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for notification events
|
||||
/// </summary>
|
||||
public class NotificationEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
|
||||
public NotificationEventArgs(NotificationModel notification)
|
||||
{
|
||||
Notification = notification;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for notification action events
|
||||
/// </summary>
|
||||
public class NotificationActionEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
public string ActionCommand { get; }
|
||||
|
||||
public NotificationActionEventArgs(NotificationModel notification, string actionCommand)
|
||||
{
|
||||
Notification = notification;
|
||||
ActionCommand = actionCommand;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when the active power plan changes
|
||||
/// </summary>
|
||||
event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
||||
|
||||
Task<ObservableCollection<PowerPlanModel>> GetPowerPlansAsync();
|
||||
Task<ObservableCollection<PowerPlanModel>> GetCustomPowerPlansAsync();
|
||||
Task<bool> SetActivePowerPlan(PowerPlanModel powerPlan);
|
||||
Task<PowerPlanModel?> GetActivePowerPlan();
|
||||
Task<bool> ImportCustomPowerPlan(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the active power plan by GUID with duplicate change prevention
|
||||
/// </summary>
|
||||
Task<bool> SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the currently active power plan GUID
|
||||
/// </summary>
|
||||
Task<string?> GetActivePowerPlanGuidAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a power plan with the given GUID exists
|
||||
/// </summary>
|
||||
Task<bool> PowerPlanExistsAsync(string powerPlanGuid);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a power plan by GUID
|
||||
/// </summary>
|
||||
Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string powerPlanGuid);
|
||||
|
||||
/// <summary>
|
||||
/// Validates that a power plan change is necessary
|
||||
/// </summary>
|
||||
Task<bool> IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for power plan changes
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Main orchestration service for process monitoring and power plan management
|
||||
/// </summary>
|
||||
public interface IProcessMonitorManagerService : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when a process-triggered power plan change occurs
|
||||
/// </summary>
|
||||
event EventHandler<ProcessPowerPlanChangeEventArgs>? ProcessPowerPlanChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when the service status changes
|
||||
/// </summary>
|
||||
event EventHandler<ServiceStatusEventArgs>? ServiceStatusChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the service is currently running
|
||||
/// </summary>
|
||||
bool IsRunning { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current service status
|
||||
/// </summary>
|
||||
string Status { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets currently running associated processes
|
||||
/// </summary>
|
||||
IEnumerable<ProcessModel> RunningAssociatedProcesses { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Starts the process monitoring and power plan management service
|
||||
/// </summary>
|
||||
Task StartAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stops the service
|
||||
/// </summary>
|
||||
Task StopAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Manually triggers a power plan evaluation for all running processes
|
||||
/// </summary>
|
||||
Task EvaluateCurrentProcessesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Forces a return to the default power plan
|
||||
/// </summary>
|
||||
Task ForceDefaultPowerPlanAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current active power plan information
|
||||
/// </summary>
|
||||
Task<PowerPlanModel?> GetCurrentActivePowerPlanAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the configuration from the association service
|
||||
/// </summary>
|
||||
Task RefreshConfigurationAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Updates the service settings (polling intervals, etc.)
|
||||
/// </summary>
|
||||
void UpdateSettings();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for process-triggered power plan changes
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for service status changes
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for process monitoring service that uses WMI events with fallback polling
|
||||
/// </summary>
|
||||
public interface IProcessMonitorService : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when a process starts
|
||||
/// </summary>
|
||||
event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a process stops
|
||||
/// </summary>
|
||||
event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when monitoring status changes
|
||||
/// </summary>
|
||||
event EventHandler<MonitoringStatusEventArgs>? MonitoringStatusChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the service is currently monitoring
|
||||
/// </summary>
|
||||
bool IsMonitoring { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether WMI monitoring is available and working
|
||||
/// </summary>
|
||||
bool IsWmiAvailable { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether fallback polling is currently active
|
||||
/// </summary>
|
||||
bool IsFallbackPollingActive { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Starts monitoring processes
|
||||
/// </summary>
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stops monitoring processes
|
||||
/// </summary>
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets all currently running processes
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessModel>> GetRunningProcessesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a specific process is currently running
|
||||
/// </summary>
|
||||
Task<bool> IsProcessRunningAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the service settings (polling intervals, etc.)
|
||||
/// </summary>
|
||||
void UpdateSettings();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for process events
|
||||
/// </summary>
|
||||
public class ProcessEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel Process { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
|
||||
public ProcessEventArgs(ProcessModel process)
|
||||
{
|
||||
Process = process;
|
||||
Timestamp = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for monitoring status changes
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for managing process-power plan associations
|
||||
/// </summary>
|
||||
public interface IProcessPowerPlanAssociationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when configuration changes
|
||||
/// </summary>
|
||||
event EventHandler<ConfigurationChangedEventArgs>? ConfigurationChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current configuration
|
||||
/// </summary>
|
||||
ProcessMonitorConfiguration Configuration { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads configuration from persistent storage
|
||||
/// </summary>
|
||||
Task<bool> LoadConfigurationAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Saves configuration to persistent storage
|
||||
/// </summary>
|
||||
Task<bool> SaveConfigurationAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets all associations
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessPowerPlanAssociation>> GetAssociationsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets enabled associations only
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessPowerPlanAssociation>> GetEnabledAssociationsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new association
|
||||
/// </summary>
|
||||
Task<bool> AddAssociationAsync(ProcessPowerPlanAssociation association);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing association
|
||||
/// </summary>
|
||||
Task<bool> UpdateAssociationAsync(ProcessPowerPlanAssociation association);
|
||||
|
||||
/// <summary>
|
||||
/// Removes an association
|
||||
/// </summary>
|
||||
Task<bool> RemoveAssociationAsync(string associationId);
|
||||
|
||||
/// <summary>
|
||||
/// Finds the best matching association for a process
|
||||
/// </summary>
|
||||
Task<ProcessPowerPlanAssociation?> FindMatchingAssociationAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Finds association by executable name
|
||||
/// </summary>
|
||||
Task<ProcessPowerPlanAssociation?> FindAssociationByExecutableAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the default power plan
|
||||
/// </summary>
|
||||
Task<bool> SetDefaultPowerPlanAsync(string powerPlanGuid, string powerPlanName);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default power plan
|
||||
/// </summary>
|
||||
Task<(string Guid, string Name)> GetDefaultPowerPlanAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Validates the current configuration
|
||||
/// </summary>
|
||||
Task<IEnumerable<string>> ValidateConfigurationAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Resets configuration to defaults
|
||||
/// </summary>
|
||||
Task ResetConfigurationAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Exports configuration to a file
|
||||
/// </summary>
|
||||
Task<bool> ExportConfigurationAsync(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// Imports configuration from a file
|
||||
/// </summary>
|
||||
Task<bool> ImportConfigurationAsync(string filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for configuration changes
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<bool> SaveProcessProfile(string profileName, ProcessModel process);
|
||||
Task<bool> LoadProcessProfile(string profileName, ProcessModel process);
|
||||
Task RefreshProcessInfo(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a process by its ID
|
||||
/// </summary>
|
||||
Task<ProcessModel?> GetProcessByIdAsync(int processId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets processes by executable name
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessModel>> GetProcessesByNameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a process with the given name is currently running
|
||||
/// </summary>
|
||||
Task<bool> IsProcessRunningAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all running processes with their executable paths
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessModel>> GetProcessesWithPathsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a ProcessModel from a System.Diagnostics.Process
|
||||
/// </summary>
|
||||
ProcessModel CreateProcessModel(Process process);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing system tray functionality
|
||||
/// </summary>
|
||||
public interface ISystemTrayService : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when quick apply is requested from tray
|
||||
/// </summary>
|
||||
event EventHandler? QuickApplyRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when show main window is requested from tray
|
||||
/// </summary>
|
||||
event EventHandler? ShowMainWindowRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when exit is requested from tray
|
||||
/// </summary>
|
||||
event EventHandler? ExitRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when monitoring enable/disable is requested from tray
|
||||
/// </summary>
|
||||
event EventHandler<MonitoringToggleEventArgs>? MonitoringToggleRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when settings are requested from tray
|
||||
/// </summary>
|
||||
event EventHandler? SettingsRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the system tray icon
|
||||
/// </summary>
|
||||
void Initialize();
|
||||
|
||||
/// <summary>
|
||||
/// Shows the system tray icon
|
||||
/// </summary>
|
||||
void Show();
|
||||
|
||||
/// <summary>
|
||||
/// Hides the system tray icon
|
||||
/// </summary>
|
||||
void Hide();
|
||||
|
||||
/// <summary>
|
||||
/// Updates the tray icon tooltip
|
||||
/// </summary>
|
||||
void UpdateTooltip(string tooltip);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a balloon tip notification
|
||||
/// </summary>
|
||||
void ShowBalloonTip(string title, string text, int timeoutMs = 3000);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the context menu with current process information
|
||||
/// </summary>
|
||||
void UpdateContextMenu(string? selectedProcessName = null, bool hasSelection = false);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the monitoring status in the context menu
|
||||
/// </summary>
|
||||
void UpdateMonitoringStatus(bool isMonitoring, bool isWmiAvailable = true);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the tray icon based on application state
|
||||
/// </summary>
|
||||
void UpdateTrayIcon(TrayIconState state);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification through the tray icon
|
||||
/// </summary>
|
||||
void ShowTrayNotification(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000);
|
||||
|
||||
/// <summary>
|
||||
/// Updates settings for the tray service
|
||||
/// </summary>
|
||||
void UpdateSettings(ApplicationSettingsModel settings);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the Game Boost status in the tray
|
||||
/// </summary>
|
||||
void UpdateGameBoostStatus(bool isGameBoostActive, string? currentGameName = null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for monitoring toggle events
|
||||
/// </summary>
|
||||
public class MonitoringToggleEventArgs : EventArgs
|
||||
{
|
||||
public bool EnableMonitoring { get; }
|
||||
|
||||
public MonitoringToggleEventArgs(bool enableMonitoring)
|
||||
{
|
||||
EnableMonitoring = enableMonitoring;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tray icon states
|
||||
/// </summary>
|
||||
public enum TrayIconState
|
||||
{
|
||||
Normal,
|
||||
Monitoring,
|
||||
Error,
|
||||
Disabled,
|
||||
GameBoost
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages log file operations including rotation, cleanup, and concurrent access
|
||||
/// </summary>
|
||||
public class LogFileManager : IDisposable
|
||||
{
|
||||
private readonly ILogger<LogFileManager> _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<LogFileManager> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the log file manager
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write log entries to the current log file with automatic rotation
|
||||
/// </summary>
|
||||
public async Task WriteLogEntriesAsync(IEnumerable<string> logLines)
|
||||
{
|
||||
await _fileLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
// Check if rotation is needed
|
||||
await CheckAndRotateLogFileAsync();
|
||||
|
||||
// Write entries
|
||||
await File.AppendAllLinesAsync(CurrentLogFilePath, logLines);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_fileLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write a single log entry
|
||||
/// </summary>
|
||||
public async Task WriteLogEntryAsync(string logLine)
|
||||
{
|
||||
await WriteLogEntriesAsync(new[] { logLine });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read log entries from all log files within date range
|
||||
/// </summary>
|
||||
public async Task<List<string>> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get log file statistics
|
||||
/// </summary>
|
||||
public async Task<LogFileStatistics> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clean up old log files based on retention policy
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Export logs to a specified file
|
||||
/// </summary>
|
||||
public async Task<string> 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<string>
|
||||
{
|
||||
$"# 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update configuration
|
||||
/// </summary>
|
||||
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<string> GetLogFiles()
|
||||
{
|
||||
return Directory.GetFiles(_logDirectory, "*.log")
|
||||
.OrderByDescending(f => new FileInfo(f).CreationTime)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<List<(DateTime timestamp, string line)>> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing notifications with balloon tips and toast support
|
||||
/// </summary>
|
||||
public class NotificationService : INotificationService, IDisposable
|
||||
{
|
||||
private readonly ILogger<NotificationService> _logger;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
private readonly ISystemTrayService _systemTrayService;
|
||||
private readonly List<NotificationModel> _notificationHistory;
|
||||
private ApplicationSettingsModel _settings;
|
||||
private bool _disposed = false;
|
||||
|
||||
public event EventHandler<NotificationEventArgs>? NotificationShown;
|
||||
public event EventHandler<NotificationEventArgs>? NotificationDismissed;
|
||||
public event EventHandler<NotificationActionEventArgs>? NotificationActionClicked;
|
||||
|
||||
public IReadOnlyList<NotificationModel> NotificationHistory => _notificationHistory.AsReadOnly();
|
||||
|
||||
public NotificationService(
|
||||
ILogger<NotificationService> 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<NotificationModel>();
|
||||
_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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<PowerPlanService> _logger;
|
||||
private readonly IEnhancedLoggingService _enhancedLogger;
|
||||
private string? _lastActivePowerPlanGuid;
|
||||
|
||||
public event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
||||
|
||||
public PowerPlanService(ILogger<PowerPlanService> logger, IEnhancedLoggingService enhancedLogger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger));
|
||||
}
|
||||
|
||||
public async Task<ObservableCollection<PowerPlanModel>> GetPowerPlansAsync()
|
||||
{
|
||||
@@ -83,16 +96,43 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<bool> SetActivePowerPlan(PowerPlanModel powerPlan)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
return await SetActivePowerPlanByGuidAsync(powerPlan.Guid, false);
|
||||
}
|
||||
|
||||
public async Task<bool> SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true)
|
||||
{
|
||||
return await Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check if change is needed when duplicate prevention is enabled
|
||||
if (preventDuplicateChanges)
|
||||
{
|
||||
var isChangeNeeded = await IsPowerPlanChangeNeededAsync(powerPlanGuid);
|
||||
if (!isChangeNeeded)
|
||||
{
|
||||
_logger.LogDebug("Power plan change skipped - already active: {PowerPlanGuid}", powerPlanGuid);
|
||||
return true; // No change needed, consider it successful
|
||||
}
|
||||
}
|
||||
|
||||
var previousPowerPlan = await GetActivePowerPlan();
|
||||
var targetPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid);
|
||||
|
||||
_logger.LogInformation("Attempting to change power plan from '{FromPlan}' to '{ToPlan}'",
|
||||
previousPowerPlan?.Name ?? "Unknown", targetPowerPlan?.Name ?? "Unknown");
|
||||
|
||||
await _enhancedLogger.LogPowerPlanChangeAsync(
|
||||
previousPowerPlan?.Name ?? "Unknown",
|
||||
targetPowerPlan?.Name ?? "Unknown",
|
||||
"Manual power plan change requested");
|
||||
|
||||
var process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "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<string, object>
|
||||
{
|
||||
["PowerPlanGuid"] = powerPlanGuid,
|
||||
["PreventDuplicateChanges"] = preventDuplicateChanges
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
@@ -186,5 +266,52 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<string?> GetActivePowerPlanGuidAsync()
|
||||
{
|
||||
var activePlan = await GetActivePowerPlan();
|
||||
return activePlan?.Guid;
|
||||
}
|
||||
|
||||
public async Task<bool> PowerPlanExistsAsync(string powerPlanGuid)
|
||||
{
|
||||
var powerPlans = await GetPowerPlansAsync();
|
||||
return powerPlans.Any(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public async Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string powerPlanGuid)
|
||||
{
|
||||
var powerPlans = await GetPowerPlansAsync();
|
||||
return powerPlans.FirstOrDefault(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public async Task<bool> IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid)
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentGuid = await GetActivePowerPlanGuidAsync();
|
||||
|
||||
// Check if the target power plan is already active
|
||||
if (string.Equals(currentGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false; // No change needed
|
||||
}
|
||||
|
||||
// Check if we recently set this power plan (to prevent rapid switching)
|
||||
lock (_lockObject)
|
||||
{
|
||||
if (string.Equals(_lastActivePowerPlanGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false; // We recently set this plan
|
||||
}
|
||||
}
|
||||
|
||||
return true; // Change is needed
|
||||
}
|
||||
catch
|
||||
{
|
||||
return true; // If we can't determine, assume change is needed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services.ProcessManagement
|
||||
{
|
||||
/// <summary>
|
||||
/// Unified interface for process management operations
|
||||
/// </summary>
|
||||
public interface IProcessManagementService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when a process starts
|
||||
/// </summary>
|
||||
event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a process stops
|
||||
/// </summary>
|
||||
event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when process monitoring status changes
|
||||
/// </summary>
|
||||
event EventHandler<MonitoringStatusChangedEventArgs>? MonitoringStatusChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether process monitoring is currently active
|
||||
/// </summary>
|
||||
bool IsMonitoringActive { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets all currently running processes
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessModel>> GetRunningProcessesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific process by ID
|
||||
/// </summary>
|
||||
Task<ProcessModel?> GetProcessByIdAsync(int processId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets processes by executable name
|
||||
/// </summary>
|
||||
Task<IEnumerable<ProcessModel>> GetProcessesByNameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Start monitoring for process events
|
||||
/// </summary>
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stop monitoring for process events
|
||||
/// </summary>
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Set processor affinity for a process
|
||||
/// </summary>
|
||||
Task SetProcessorAffinityAsync(ProcessModel process, long affinityMask);
|
||||
|
||||
/// <summary>
|
||||
/// Set priority for a process
|
||||
/// </summary>
|
||||
Task SetProcessPriorityAsync(ProcessModel process, ProcessPriorityClass priority);
|
||||
|
||||
/// <summary>
|
||||
/// Refresh process information
|
||||
/// </summary>
|
||||
Task RefreshProcessInfoAsync(ProcessModel process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for process events
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for monitoring status changes
|
||||
/// </summary>
|
||||
public class MonitoringStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsActive { get; }
|
||||
public string? Reason { get; }
|
||||
|
||||
public MonitoringStatusChangedEventArgs(bool isActive, string? reason = null)
|
||||
{
|
||||
IsActive = isActive;
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Main orchestration service that coordinates process monitoring and power plan management
|
||||
/// </summary>
|
||||
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<ProcessMonitorManagerService> _logger;
|
||||
private readonly IEnhancedLoggingService _enhancedLogger;
|
||||
private readonly object _lockObject = new();
|
||||
|
||||
private readonly ConcurrentDictionary<int, ProcessModel> _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<ProcessPowerPlanChangeEventArgs>? ProcessPowerPlanChanged;
|
||||
public event EventHandler<ServiceStatusEventArgs>? ServiceStatusChanged;
|
||||
|
||||
public bool IsRunning => _isRunning;
|
||||
public string Status => _status;
|
||||
public IEnumerable<ProcessModel> RunningAssociatedProcesses => _runningAssociatedProcesses.Values.ToList();
|
||||
|
||||
public ProcessMonitorManagerService(
|
||||
IProcessMonitorService processMonitorService,
|
||||
IProcessPowerPlanAssociationService associationService,
|
||||
IPowerPlanService powerPlanService,
|
||||
IGameBoostService gameBoostService,
|
||||
INotificationService notificationService,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<ProcessMonitorManagerService> 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<string, object> { ["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<ProcessModel>();
|
||||
|
||||
// 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<PowerPlanModel?> 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<string, object>
|
||||
{
|
||||
["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<ProcessModel> 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");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a process is a game and activates Game Boost if enabled
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a stopped process was the current game and deactivates Game Boost if needed
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Process monitoring service using WMI events with fallback polling
|
||||
/// </summary>
|
||||
public class ProcessMonitorService : IProcessMonitorService
|
||||
{
|
||||
private readonly IProcessService _processService;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
private readonly object _lockObject = new();
|
||||
private readonly ConcurrentDictionary<int, ProcessModel> _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<ProcessEventArgs>? ProcessStarted;
|
||||
public event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
public event EventHandler<MonitoringStatusEventArgs>? 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<IEnumerable<ProcessModel>> GetRunningProcessesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var processes = await _processService.GetProcessesAsync();
|
||||
return processes;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return Enumerable.Empty<ProcessModel>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> 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<bool> 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<ProcessModel?> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing process-power plan associations with persistence
|
||||
/// </summary>
|
||||
public class ProcessPowerPlanAssociationService : IProcessPowerPlanAssociationService
|
||||
{
|
||||
private readonly string _configurationDirectory;
|
||||
private readonly string _configurationFilePath;
|
||||
private readonly object _lockObject = new();
|
||||
|
||||
private ProcessMonitorConfiguration _configuration;
|
||||
|
||||
public event EventHandler<ConfigurationChangedEventArgs>? 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<bool> 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<ProcessMonitorConfiguration>(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<bool> 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<IEnumerable<ProcessPowerPlanAssociation>> GetAssociationsAsync()
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _configuration.Associations.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ProcessPowerPlanAssociation>> GetEnabledAssociationsAsync()
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _configuration.GetEnabledAssociations().ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> 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<bool> 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<bool> 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<ProcessPowerPlanAssociation?> FindMatchingAssociationAsync(ProcessModel process)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _configuration.FindMatchingAssociation(process);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ProcessPowerPlanAssociation?> FindAssociationByExecutableAsync(string executableName)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
lock (_lockObject)
|
||||
{
|
||||
return _configuration.FindAssociationByExecutable(executableName);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> 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<IEnumerable<string>> 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<bool> 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<bool> ImportConfigurationAsync(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(filePath)) return false;
|
||||
|
||||
var json = await File.ReadAllTextAsync(filePath);
|
||||
var importedConfig = JsonSerializer.Deserialize<ProcessMonitorConfiguration>(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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ProcessModel>(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<ProcessModel?> GetProcessByIdAsync(int processId)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = Process.GetProcessById(processId);
|
||||
return CreateProcessModel(process);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ProcessModel>> 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<ProcessModel>();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<bool> IsProcessRunningAsync(string executableName)
|
||||
{
|
||||
var processes = await GetProcessesByNameAsync(executableName);
|
||||
return processes.Any();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ProcessModel>> 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;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Centralized service configuration for dependency injection
|
||||
/// </summary>
|
||||
public static class ServiceConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Configure all application services
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure service infrastructure (logging, factories, etc.)
|
||||
/// </summary>
|
||||
private static IServiceCollection ConfigureServiceInfrastructure(this IServiceCollection services)
|
||||
{
|
||||
// Logging infrastructure
|
||||
services.AddLogging(builder =>
|
||||
{
|
||||
builder.AddConsole();
|
||||
builder.SetMinimumLevel(LogLevel.Information);
|
||||
});
|
||||
|
||||
// Enhanced logging service
|
||||
services.AddSingleton<IEnhancedLoggingService, EnhancedLoggingService>();
|
||||
|
||||
// Service factory for advanced service management
|
||||
services.AddSingleton<IServiceFactory, ServiceFactory>();
|
||||
|
||||
// Data access services
|
||||
services.AddSingleton<ThreadPilot.Data.IDataAccessService, ThreadPilot.Data.DataAccessService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure core system services that interact directly with the OS
|
||||
/// </summary>
|
||||
private static IServiceCollection ConfigureCoreSystemServices(this IServiceCollection services)
|
||||
{
|
||||
// Core system interaction services
|
||||
services.AddSingleton<IProcessService, ProcessService>();
|
||||
services.AddSingleton<IPowerPlanService, PowerPlanService>();
|
||||
services.AddSingleton<ICpuTopologyService, CpuTopologyService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure process monitoring and management services
|
||||
/// </summary>
|
||||
private static IServiceCollection ConfigureProcessManagementServices(this IServiceCollection services)
|
||||
{
|
||||
// Process monitoring services
|
||||
services.AddSingleton<IProcessMonitorService, ProcessMonitorService>();
|
||||
services.AddSingleton<IProcessPowerPlanAssociationService, ProcessPowerPlanAssociationService>();
|
||||
services.AddSingleton<IProcessMonitorManagerService, ProcessMonitorManagerService>();
|
||||
|
||||
// Game boost and optimization services
|
||||
services.AddSingleton<IGameBoostService, GameBoostService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure application-level services (settings, notifications, etc.)
|
||||
/// </summary>
|
||||
private static IServiceCollection ConfigureApplicationLevelServices(this IServiceCollection services)
|
||||
{
|
||||
// Application configuration and settings
|
||||
services.AddSingleton<IApplicationSettingsService, ApplicationSettingsService>();
|
||||
|
||||
// User interface services
|
||||
services.AddSingleton<INotificationService, NotificationService>();
|
||||
services.AddSingleton<ISystemTrayService, SystemTrayService>();
|
||||
|
||||
// System integration services
|
||||
services.AddSingleton<IAutostartService, AutostartService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure presentation layer (ViewModels and Views)
|
||||
/// </summary>
|
||||
private static IServiceCollection ConfigurePresentationLayer(this IServiceCollection services)
|
||||
{
|
||||
// ViewModel factory for centralized ViewModel management
|
||||
services.AddViewModelFactory();
|
||||
|
||||
// ViewModels - Transient for proper lifecycle management
|
||||
services.AddTransient<ProcessViewModel>();
|
||||
services.AddTransient<PowerPlanViewModel>();
|
||||
services.AddTransient<ProcessPowerPlanAssociationViewModel>();
|
||||
services.AddTransient<SettingsViewModel>();
|
||||
services.AddTransient<LogViewerViewModel>();
|
||||
services.AddTransient<MainWindowViewModel>();
|
||||
|
||||
// Views - Transient for proper lifecycle management
|
||||
services.AddTransient<MainWindow>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validate service configuration
|
||||
/// </summary>
|
||||
public static void ValidateServiceConfiguration(IServiceProvider serviceProvider)
|
||||
{
|
||||
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using ThreadPilot.Services.Core;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Factory for creating and managing service instances with proper dependency resolution
|
||||
/// </summary>
|
||||
public interface IServiceFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a service instance of the specified type
|
||||
/// </summary>
|
||||
T CreateService<T>() where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Create a service instance with additional parameters
|
||||
/// </summary>
|
||||
T CreateService<T>(params object[] parameters) where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Get or create a singleton service instance
|
||||
/// </summary>
|
||||
T GetSingletonService<T>() where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize all core services
|
||||
/// </summary>
|
||||
Task InitializeAllServicesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Dispose all managed services
|
||||
/// </summary>
|
||||
Task DisposeAllServicesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of service factory with dependency injection support
|
||||
/// </summary>
|
||||
public class ServiceFactory : IServiceFactory, IDisposable
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<ServiceFactory> _logger;
|
||||
private readonly Dictionary<Type, object> _singletonInstances = new();
|
||||
private readonly List<ISystemService> _managedServices = new();
|
||||
private bool _disposed;
|
||||
|
||||
public ServiceFactory(IServiceProvider serviceProvider, ILogger<ServiceFactory> logger)
|
||||
{
|
||||
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public T CreateService<T>() where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
var service = _serviceProvider.GetRequiredService<T>();
|
||||
|
||||
// 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<T>(params object[] parameters) where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
// For services with additional parameters, use ActivatorUtilities
|
||||
var service = ActivatorUtilities.CreateInstance<T>(_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<T>() where T : class
|
||||
{
|
||||
var serviceType = typeof(T);
|
||||
|
||||
if (_singletonInstances.TryGetValue(serviceType, out var existingInstance))
|
||||
{
|
||||
return (T)existingInstance;
|
||||
}
|
||||
|
||||
var newInstance = CreateService<T>();
|
||||
_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing system tray icon and context menu
|
||||
/// </summary>
|
||||
public class SystemTrayService : ISystemTrayService
|
||||
{
|
||||
private readonly ILogger<SystemTrayService> _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<MonitoringToggleEventArgs>? MonitoringToggleRequested;
|
||||
public event EventHandler? SettingsRequested;
|
||||
|
||||
public SystemTrayService(ILogger<SystemTrayService> 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Tests;
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
/// <summary>
|
||||
/// Simple test runner for CPU topology functionality
|
||||
/// </summary>
|
||||
public static class TestRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Main test entry point
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// Simple test class for CPU topology detection
|
||||
/// </summary>
|
||||
public static class CpuTopologyServiceTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Test CPU topology detection
|
||||
/// </summary>
|
||||
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<CpuTopologyService>();
|
||||
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Integration test for Game Boost functionality
|
||||
/// </summary>
|
||||
public class GameBoostIntegrationTest
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<GameBoostIntegrationTest> _logger;
|
||||
|
||||
public GameBoostIntegrationTest(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_logger = serviceProvider.GetRequiredService<ILogger<GameBoostIntegrationTest>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tests the complete Game Boost workflow
|
||||
/// </summary>
|
||||
public async Task<bool> 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<bool> TestServiceResolutionAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Testing service resolution...");
|
||||
|
||||
var gameBoostService = _serviceProvider.GetRequiredService<IGameBoostService>();
|
||||
var systemTrayService = _serviceProvider.GetRequiredService<ISystemTrayService>();
|
||||
var processMonitorService = _serviceProvider.GetRequiredService<IProcessMonitorService>();
|
||||
var settingsService = _serviceProvider.GetRequiredService<IApplicationSettingsService>();
|
||||
|
||||
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<bool> TestGameDetectionAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Testing game detection logic...");
|
||||
|
||||
var gameBoostService = _serviceProvider.GetRequiredService<IGameBoostService>();
|
||||
|
||||
// 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<bool> TestKnownGamesManagementAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Testing known games management...");
|
||||
|
||||
var gameBoostService = _serviceProvider.GetRequiredService<IGameBoostService>();
|
||||
|
||||
// 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<bool> TestSystemTrayIntegrationAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Testing system tray integration...");
|
||||
|
||||
var systemTrayService = _serviceProvider.GetRequiredService<ISystemTrayService>();
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ThreadPilot.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// Test runner for validating Game Boost functionality
|
||||
/// </summary>
|
||||
public static class TestRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Runs all Game Boost integration tests
|
||||
/// </summary>
|
||||
public static async Task<bool> RunGameBoostTestsAsync(IServiceProvider serviceProvider)
|
||||
{
|
||||
var logger = serviceProvider.GetRequiredService<ILogger<GameBoostIntegrationTest>>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates that all required services are properly configured
|
||||
/// </summary>
|
||||
public static bool ValidateServiceConfiguration(IServiceProvider serviceProvider)
|
||||
{
|
||||
var logger = serviceProvider.GetRequiredService<ILogger<GameBoostIntegrationTest>>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -2,15 +2,20 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net9.0-windows</TargetFramework>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.7" />
|
||||
<PackageReference Include="System.Management" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -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
|
||||
+164
-1
@@ -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
|
||||
/// <summary>
|
||||
/// Base ViewModel with common functionality for all ViewModels
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set status message and busy state
|
||||
/// </summary>
|
||||
protected void SetStatus(string message, bool isBusyState = true)
|
||||
{
|
||||
StatusMessage = message;
|
||||
IsBusy = isBusyState;
|
||||
ClearError();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clear status and busy state
|
||||
/// </summary>
|
||||
protected void ClearStatus()
|
||||
{
|
||||
StatusMessage = string.Empty;
|
||||
IsBusy = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set error message and clear busy state
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clear error state
|
||||
/// </summary>
|
||||
protected void ClearError()
|
||||
{
|
||||
ErrorMessage = string.Empty;
|
||||
HasError = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Execute an async operation with error handling and status updates
|
||||
/// </summary>
|
||||
protected async Task ExecuteAsync(Func<Task> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Execute an async operation with return value and error handling
|
||||
/// </summary>
|
||||
protected async Task<T?> ExecuteAsync<T>(Func<Task<T>> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log user action for audit purposes
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the ViewModel - override in derived classes
|
||||
/// </summary>
|
||||
public virtual async Task InitializeAsync()
|
||||
{
|
||||
// Base implementation does nothing
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleanup resources - override in derived classes
|
||||
/// </summary>
|
||||
protected virtual void OnDispose()
|
||||
{
|
||||
// Base implementation does nothing
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
OnDispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// ViewModel for the log viewer and management interface
|
||||
/// </summary>
|
||||
public partial class LogViewerViewModel : ObservableObject
|
||||
{
|
||||
private readonly IEnhancedLoggingService _loggingService;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
private readonly ILogger<LogViewerViewModel> _logger;
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<LogEntryDisplayModel> _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<string> AvailableCategories { get; } = new()
|
||||
{
|
||||
"All", "PowerPlan", "ProcessMonitoring", "GameBoost", "UserAction", "System", "Error", "Performance"
|
||||
};
|
||||
|
||||
public ObservableCollection<LogLevel> 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<LogViewerViewModel> 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<LogEntryDisplayModel>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Display model for log entries in the UI
|
||||
/// </summary>
|
||||
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<string, object> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<MainWindowViewModel> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<PowerPlanViewModel> logger,
|
||||
IPowerPlanService powerPlanService,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
{
|
||||
_powerPlanService = powerPlanService;
|
||||
SetupRefreshTimer();
|
||||
|
||||
@@ -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<ProcessPowerPlanAssociation> associations = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<PowerPlanModel> availablePowerPlans = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<ProcessModel> 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<ProcessPowerPlanAssociationViewModel> 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<ProcessPowerPlanAssociation>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+393
-73
@@ -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<CpuCoreModel> cpuCores = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<CpuAffinityPreset> 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<PowerPlanModel> powerPlans = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableHyperThreading = true;
|
||||
|
||||
public ProcessViewModel(
|
||||
ILogger<ProcessViewModel> 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)
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// ViewModel for application settings
|
||||
/// </summary>
|
||||
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<PowerPlanModel> availablePowerPlans = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<string> 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<SettingsViewModel> 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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes settings from the service
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if there are unsaved changes
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads known games from the GameBoostService
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new known game executable
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the selected known game executable
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if a new game can be added
|
||||
/// </summary>
|
||||
private bool CanAddKnownGame()
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(NewGameExecutableName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the selected game can be removed
|
||||
/// </summary>
|
||||
private bool CanRemoveKnownGame()
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(SelectedKnownGame);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
namespace ThreadPilot.ViewModels
|
||||
{
|
||||
/// <summary>
|
||||
/// Factory for creating and managing ViewModel instances
|
||||
/// </summary>
|
||||
public interface IViewModelFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a ViewModel instance of the specified type
|
||||
/// </summary>
|
||||
T CreateViewModel<T>() where T : BaseViewModel;
|
||||
|
||||
/// <summary>
|
||||
/// Create a ViewModel instance with initialization
|
||||
/// </summary>
|
||||
Task<T> CreateAndInitializeViewModelAsync<T>() where T : BaseViewModel;
|
||||
|
||||
/// <summary>
|
||||
/// Dispose all managed ViewModels
|
||||
/// </summary>
|
||||
void DisposeAllViewModels();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of ViewModel factory with dependency injection support
|
||||
/// </summary>
|
||||
public class ViewModelFactory : IViewModelFactory, IDisposable
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<ViewModelFactory> _logger;
|
||||
private readonly List<BaseViewModel> _managedViewModels = new();
|
||||
private bool _disposed;
|
||||
|
||||
public ViewModelFactory(IServiceProvider serviceProvider, ILogger<ViewModelFactory> logger)
|
||||
{
|
||||
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public T CreateViewModel<T>() where T : BaseViewModel
|
||||
{
|
||||
try
|
||||
{
|
||||
var viewModel = _serviceProvider.GetRequiredService<T>();
|
||||
_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<T> CreateAndInitializeViewModelAsync<T>() where T : BaseViewModel
|
||||
{
|
||||
var viewModel = CreateViewModel<T>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for ViewModel factory registration
|
||||
/// </summary>
|
||||
public static class ViewModelFactoryExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Register ViewModel factory in dependency injection container
|
||||
/// </summary>
|
||||
public static IServiceCollection AddViewModelFactory(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IViewModelFactory, ViewModelFactory>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
<UserControl x:Class="ThreadPilot.Views.LogViewerView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:viewmodels="clr-namespace:ThreadPilot.ViewModels"
|
||||
xmlns:local="clr-namespace:ThreadPilot.Views"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="600" d:DesignWidth="1000"
|
||||
d:DataContext="{d:DesignInstance Type=viewmodels:LogViewerViewModel}">
|
||||
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="LogLevelTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="4,2"/>
|
||||
<Setter Property="HorizontalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="LogEntryStyle" TargetType="ListViewItem">
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
|
||||
<Setter Property="Padding" Value="2"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Level}" Value="Error">
|
||||
<Setter Property="Background" Value="#FFEEEE"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding Level}" Value="Critical">
|
||||
<Setter Property="Background" Value="#FFDDDD"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding Level}" Value="Warning">
|
||||
<Setter Property="Background" Value="#FFFAEE"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="200"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Filter and Control Panel -->
|
||||
<Border Grid.Row="0" Background="#F5F5F5" Padding="10" BorderBrush="#CCCCCC" BorderThickness="0,0,0,1">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Filters Row 1 -->
|
||||
<StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal" Margin="0,0,0,5">
|
||||
<TextBlock Text="Search:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"
|
||||
Width="200" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Category:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<ComboBox ItemsSource="{Binding AvailableCategories}"
|
||||
SelectedItem="{Binding SelectedCategory}"
|
||||
Width="120" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Level:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<ComboBox ItemsSource="{Binding AvailableLogLevels}"
|
||||
SelectedItem="{Binding SelectedLogLevel}"
|
||||
Width="100" Margin="0,0,15,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Filters Row 2 -->
|
||||
<StackPanel Grid.Row="1" Grid.Column="0" Orientation="Horizontal">
|
||||
<TextBlock Text="From:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<DatePicker SelectedDate="{Binding FromDate}" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="To:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<DatePicker SelectedDate="{Binding ToDate}" Margin="0,0,15,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<StackPanel Grid.Row="0" Grid.RowSpan="2" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Button Content="Refresh" Command="{Binding RefreshLogsCommand}"
|
||||
Margin="5,0" Padding="10,5">
|
||||
<Button.IsEnabled>
|
||||
<Binding Path="IsLoading">
|
||||
<Binding.Converter>
|
||||
<local:InverseBooleanConverter/>
|
||||
</Binding.Converter>
|
||||
</Binding>
|
||||
</Button.IsEnabled>
|
||||
</Button>
|
||||
<Button Content="Clear Display" Command="{Binding ClearLogsCommand}"
|
||||
Margin="5,0" Padding="10,5"/>
|
||||
<Button Content="Export" Command="{Binding ExportLogsCommand}"
|
||||
Margin="5,0" Padding="10,5"/>
|
||||
<Button Content="Cleanup Old" Command="{Binding CleanupOldLogsCommand}"
|
||||
Margin="5,0" Padding="10,5"/>
|
||||
<Button Content="Open Directory" Command="{Binding OpenLogDirectoryCommand}"
|
||||
Margin="5,0" Padding="10,5"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Log Entries List -->
|
||||
<ListView Grid.Row="1" ItemsSource="{Binding LogEntries}"
|
||||
SelectedItem="{Binding SelectedLogEntry}"
|
||||
ItemContainerStyle="{StaticResource LogEntryStyle}"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Auto"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Auto">
|
||||
<ListView.View>
|
||||
<GridView>
|
||||
<GridViewColumn Header="Time" Width="150">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding FormattedTimestamp}" FontFamily="Consolas"/>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Level" Width="80">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Level}"
|
||||
Foreground="{Binding LevelColor}"
|
||||
Style="{StaticResource LogLevelTextStyle}"/>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Category" Width="120">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Category}" FontWeight="SemiBold"/>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Message" Width="500">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding ShortMessage}" TextWrapping="NoWrap"/>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Exception" Width="60">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Foreground="Red" FontWeight="Bold">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="True">
|
||||
<Setter Property="Text" Value="⚠"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<Setter Property="Text" Value=""/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="ID" Width="60">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding CorrelationId}" FontFamily="Consolas" FontSize="10"/>
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
|
||||
<ListView.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="Copy Entry" Command="{Binding CopyLogEntryCommand}"
|
||||
CommandParameter="{Binding SelectedLogEntry}"/>
|
||||
<Separator/>
|
||||
<MenuItem Header="Refresh" Command="{Binding RefreshLogsCommand}"/>
|
||||
</ContextMenu>
|
||||
</ListView.ContextMenu>
|
||||
</ListView>
|
||||
|
||||
<!-- Splitter -->
|
||||
<GridSplitter Grid.Row="2" Height="5" HorizontalAlignment="Stretch"
|
||||
Background="#CCCCCC" ResizeBehavior="PreviousAndNext"/>
|
||||
|
||||
<!-- Log Entry Details -->
|
||||
<Border Grid.Row="3" Background="White" BorderBrush="#CCCCCC" BorderThickness="0,1,0,0">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="10" DataContext="{Binding SelectedLogEntry}">
|
||||
<TextBlock Text="Log Entry Details" FontWeight="Bold" FontSize="14" Margin="0,0,0,10"/>
|
||||
|
||||
<Grid>
|
||||
<Grid.Style>
|
||||
<Style TargetType="Grid">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding}" Value="{x:Null}">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Grid.Style>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="Timestamp:" FontWeight="Bold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding FormattedTimestamp}" Margin="0,0,0,5"/>
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Level:" FontWeight="Bold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Level}"
|
||||
Foreground="{Binding LevelColor}" FontWeight="Bold" Margin="0,0,0,5"/>
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="Category:" FontWeight="Bold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Category}" Margin="0,0,0,5"/>
|
||||
|
||||
<TextBlock Grid.Row="3" Grid.Column="0" Text="Message:" FontWeight="Bold" Margin="0,0,10,5" VerticalAlignment="Top"/>
|
||||
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Message, Mode=OneWay}"
|
||||
IsReadOnly="True" TextWrapping="Wrap" Background="Transparent"
|
||||
BorderThickness="0" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Grid.Row="4" Grid.Column="0" Text="Exception:" FontWeight="Bold" Margin="0,0,10,5"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding Exception, Mode=OneWay}"
|
||||
IsReadOnly="True" TextWrapping="Wrap" Background="#FFEEEE"
|
||||
BorderThickness="1" BorderBrush="#FFCCCC" Margin="0,0,0,10">
|
||||
<TextBox.Style>
|
||||
<Style TargetType="TextBox">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBox.Style>
|
||||
</TextBox>
|
||||
|
||||
<TextBlock Grid.Row="5" Grid.Column="0" Text="Correlation ID:" FontWeight="Bold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="5" Grid.Column="1" Text="{Binding CorrelationId}" FontFamily="Consolas"/>
|
||||
</Grid>
|
||||
|
||||
<TextBlock Text="No log entry selected"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
Foreground="Gray" FontStyle="Italic">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding DataContext.SelectedLogEntry, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="{x:Null}">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
|
||||
<!-- Status and Settings Panel -->
|
||||
<Border Grid.Row="4" Background="#F5F5F5" Padding="10" BorderBrush="#CCCCCC" BorderThickness="0,1,0,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Status and Statistics -->
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding StatusMessage}" VerticalAlignment="Center" Margin="0,0,20,0"/>
|
||||
|
||||
<TextBlock Text="Files:" VerticalAlignment="Center" Margin="0,0,5,0" FontWeight="Bold"/>
|
||||
<TextBlock Text="{Binding LogStatistics.TotalLogFiles}" VerticalAlignment="Center" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Size:" VerticalAlignment="Center" Margin="0,0,5,0" FontWeight="Bold"/>
|
||||
<TextBlock VerticalAlignment="Center" Margin="0,0,15,0">
|
||||
<TextBlock.Text>
|
||||
<MultiBinding StringFormat="{}{0:F1} MB">
|
||||
<Binding Path="LogStatistics.TotalLogSizeBytes" Converter="{x:Static local:BytesToMegabytesConverter.Instance}"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
|
||||
<ProgressBar IsIndeterminate="{Binding IsLoading}" Width="100" Height="16">
|
||||
<ProgressBar.Style>
|
||||
<Style TargetType="ProgressBar">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsLoading}" Value="False">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</ProgressBar.Style>
|
||||
</ProgressBar>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Settings Panel -->
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<CheckBox Content="Debug Logging" IsChecked="{Binding EnableDebugLogging}"
|
||||
VerticalAlignment="Center" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Max Size (MB):" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<TextBox Text="{Binding MaxLogFileSizeMb}" Width="50" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Retention (Days):" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<TextBox Text="{Binding LogRetentionDays}" Width="50" Margin="0,0,15,0"/>
|
||||
|
||||
<Button Content="Save Settings" Command="{Binding SaveSettingsCommand}"
|
||||
Padding="10,5" Margin="5,0"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for LogViewerView.xaml
|
||||
/// </summary>
|
||||
public partial class LogViewerView : System.Windows.Controls.UserControl
|
||||
{
|
||||
public LogViewerView()
|
||||
{
|
||||
InitializeComponent();
|
||||
Loaded += OnLoaded;
|
||||
}
|
||||
|
||||
private async void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is LogViewerViewModel viewModel)
|
||||
{
|
||||
await viewModel.InitializeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter to convert bytes to megabytes for display
|
||||
/// </summary>
|
||||
public class BytesToMegabytesConverter : IValueConverter
|
||||
{
|
||||
public static readonly BytesToMegabytesConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return bytes / (1024.0 * 1024.0);
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter to invert boolean values
|
||||
/// </summary>
|
||||
public class InverseBooleanConverter : IValueConverter
|
||||
{
|
||||
public static readonly InverseBooleanConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter to invert boolean values for visibility
|
||||
/// </summary>
|
||||
public class InverseBooleanToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly InverseBooleanToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return boolValue ? Visibility.Collapsed : Visibility.Visible;
|
||||
}
|
||||
return Visibility.Visible;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,8 @@
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- System Power Plans -->
|
||||
<GroupBox Grid.Row="0" Grid.RowSpan="2" Grid.Column="0"
|
||||
Header="System Power Plans"
|
||||
<GroupBox Grid.Row="0" Grid.RowSpan="2" Grid.Column="0"
|
||||
Header="⚡ Available Power Plans"
|
||||
Margin="0,0,5,0">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
@@ -30,12 +30,13 @@
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Button Grid.Row="0"
|
||||
<Button Grid.Row="0"
|
||||
Command="{Binding LoadPowerPlansCommand}"
|
||||
Content="Refresh Plans"
|
||||
Content="🔄 Refresh Plans"
|
||||
HorizontalAlignment="Right"
|
||||
Padding="10,5"
|
||||
Margin="0,0,0,10"/>
|
||||
Margin="0,0,0,10"
|
||||
ToolTip="Refresh the list of available power plans"/>
|
||||
|
||||
<ListView Grid.Row="1"
|
||||
ItemsSource="{Binding PowerPlans}"
|
||||
@@ -93,7 +94,8 @@
|
||||
<Button Command="{Binding SetActivePlanCommand}"
|
||||
Content="Set Active"
|
||||
Padding="20,5"
|
||||
Margin="0,0,10,0"/>
|
||||
Margin="0,0,10,0"
|
||||
ToolTip="Activate the selected power plan"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="2" Grid.Column="1"
|
||||
@@ -101,7 +103,8 @@
|
||||
Margin="5,10,0,0">
|
||||
<Button Command="{Binding ImportCustomPlanCommand}"
|
||||
Content="Import Custom Plan"
|
||||
Padding="20,5"/>
|
||||
Padding="20,5"
|
||||
ToolTip="Import a custom power plan from file"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -4,7 +4,7 @@ using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
public partial class PowerPlanView : UserControl
|
||||
public partial class PowerPlanView : System.Windows.Controls.UserControl
|
||||
{
|
||||
public PowerPlanView()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
<UserControl x:Class="ThreadPilot.Views.ProcessPowerPlanAssociationView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:converters="clr-namespace:ThreadPilot.Converters"
|
||||
xmlns:local="clr-namespace:ThreadPilot.Views"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="800" d:DesignWidth="1200">
|
||||
|
||||
<UserControl.Resources>
|
||||
<converters:BoolToColorConverter x:Key="BoolToColorConverter"/>
|
||||
<converters:InverseBooleanConverter x:Key="InverseBoolConverter"/>
|
||||
</UserControl.Resources>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Header -->
|
||||
<Border Grid.Row="0" Background="#F0F0F0" Padding="10" BorderBrush="#D0D0D0" BorderThickness="0,0,0,1">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Process-Power Plan Associations"
|
||||
FontSize="18" FontWeight="Bold"
|
||||
Foreground="#333333" Margin="0,0,0,5"/>
|
||||
<TextBlock Text="Configure automatic power plan switching based on running processes"
|
||||
FontSize="12" Foreground="#666666"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Main Content -->
|
||||
<TabControl Grid.Row="1" Background="White" BorderThickness="0">
|
||||
|
||||
<!-- Associations Tab -->
|
||||
<TabItem Header="🔗 Process Associations">
|
||||
<Grid Margin="10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="2*"/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Associations List -->
|
||||
<GroupBox Grid.Column="0" Header="📋 Current Associations">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<DataGrid Grid.Row="0"
|
||||
ItemsSource="{Binding Associations}"
|
||||
SelectedItem="{Binding SelectedAssociation}"
|
||||
AutoGenerateColumns="False"
|
||||
CanUserAddRows="False"
|
||||
GridLinesVisibility="Horizontal"
|
||||
HeadersVisibility="Column"
|
||||
BorderThickness="1">
|
||||
<DataGrid.Columns>
|
||||
<DataGridCheckBoxColumn Header="Enabled"
|
||||
Binding="{Binding IsEnabled}"
|
||||
Width="60"/>
|
||||
<DataGridTextColumn Header="Executable"
|
||||
Binding="{Binding ExecutableName}"
|
||||
Width="150"/>
|
||||
<DataGridTextColumn Header="Power Plan"
|
||||
Binding="{Binding PowerPlanName}"
|
||||
Width="150"/>
|
||||
<DataGridTextColumn Header="Priority"
|
||||
Binding="{Binding Priority}"
|
||||
Width="60"/>
|
||||
<DataGridCheckBoxColumn Header="Match by Path"
|
||||
Binding="{Binding MatchByPath}"
|
||||
Width="100"/>
|
||||
<DataGridTextColumn Header="Description"
|
||||
Binding="{Binding Description}"
|
||||
Width="*"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal"
|
||||
HorizontalAlignment="Right" Margin="0,10,0,0">
|
||||
<Button Content="Update"
|
||||
Command="{Binding UpdateAssociationCommand}"
|
||||
Margin="0,0,5,0" Padding="10,5"
|
||||
ToolTip="Update the selected association"/>
|
||||
<Button Content="Remove"
|
||||
Command="{Binding RemoveAssociationCommand}"
|
||||
Padding="10,5"
|
||||
ToolTip="Remove the selected association"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Add New Association -->
|
||||
<GroupBox Grid.Column="2" Header="Add New Association">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Executable Name:" Margin="0,0,0,5"/>
|
||||
<TextBox Text="{Binding NewExecutableName}"
|
||||
Padding="5" Margin="0,0,0,10"
|
||||
ToolTip="Enter the executable name (e.g., game.exe)"/>
|
||||
|
||||
<TextBlock Text="Executable Path (optional):" Margin="0,0,0,5"/>
|
||||
<TextBox Text="{Binding NewExecutablePath}"
|
||||
Padding="5" Margin="0,0,0,10"
|
||||
ToolTip="Enter the full path to the executable (optional)"/>
|
||||
|
||||
<CheckBox Content="Match by Path"
|
||||
IsChecked="{Binding MatchByPath}"
|
||||
Margin="0,0,0,10"
|
||||
ToolTip="Match processes by full path instead of just executable name"/>
|
||||
|
||||
<TextBlock Text="Power Plan:" Margin="0,0,0,5"/>
|
||||
<ComboBox ItemsSource="{Binding AvailablePowerPlans}"
|
||||
SelectedItem="{Binding SelectedPowerPlan}"
|
||||
DisplayMemberPath="Name"
|
||||
Padding="5" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Text="Priority:" Margin="0,0,0,5"/>
|
||||
<TextBox Text="{Binding Priority}"
|
||||
Padding="5" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Text="Description:" Margin="0,0,0,5"/>
|
||||
<TextBox Text="{Binding Description}"
|
||||
Padding="5" Margin="0,0,0,15"/>
|
||||
|
||||
<Button Content="Add Association"
|
||||
Command="{Binding AddAssociationCommand}"
|
||||
Padding="10,8"/>
|
||||
|
||||
<Separator Margin="0,15,0,15"/>
|
||||
|
||||
<TextBlock Text="Quick Add from Running Processes:"
|
||||
FontWeight="Bold" Margin="0,0,0,10"/>
|
||||
|
||||
<ComboBox ItemsSource="{Binding RunningProcesses}"
|
||||
SelectedItem="{Binding SelectedProcess}"
|
||||
DisplayMemberPath="Name"
|
||||
Padding="5" Margin="0,0,0,10"/>
|
||||
|
||||
<Button Content="Use Selected Process"
|
||||
Command="{Binding UseSelectedProcessForAssociationCommand}"
|
||||
Padding="10,5"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<!-- Settings Tab -->
|
||||
<TabItem Header="⚙️ Configuration">
|
||||
<ScrollViewer Margin="10">
|
||||
<StackPanel>
|
||||
<!-- Service Control -->
|
||||
<GroupBox Header="Service Control" Margin="0,0,0,15">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="Status: " VerticalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding ServiceStatus}"
|
||||
Foreground="{Binding IsServiceRunning, Converter={StaticResource BoolToColorConverter}}"
|
||||
FontWeight="Bold" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Content="Start Monitoring"
|
||||
Command="{Binding StartMonitoringCommand}"
|
||||
IsEnabled="{Binding IsServiceRunning, Converter={StaticResource InverseBoolConverter}}"
|
||||
Padding="15,8" Margin="0,0,10,0"/>
|
||||
<Button Content="Stop Monitoring"
|
||||
Command="{Binding StopMonitoringCommand}"
|
||||
IsEnabled="{Binding IsServiceRunning}"
|
||||
Padding="15,8"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Default Power Plan -->
|
||||
<GroupBox Header="Default Power Plan" Margin="0,0,0,15">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Power plan to use when no associated processes are running:"
|
||||
Foreground="#666666" Margin="0,0,0,10"/>
|
||||
|
||||
<ComboBox ItemsSource="{Binding AvailablePowerPlans}"
|
||||
SelectedItem="{Binding DefaultPowerPlan}"
|
||||
DisplayMemberPath="Name"
|
||||
Padding="5" Margin="0,0,0,10"/>
|
||||
|
||||
<Button Content="Set Default Power Plan"
|
||||
Command="{Binding SetDefaultPowerPlanCommand}"
|
||||
Padding="10,5" HorizontalAlignment="Left"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Monitoring Settings -->
|
||||
<GroupBox Header="Monitoring Settings" Margin="0,0,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Enable Event-Based Monitoring (WMI)"
|
||||
IsChecked="{Binding IsEventBasedMonitoringEnabled}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<CheckBox Content="Enable Fallback Polling"
|
||||
IsChecked="{Binding IsFallbackPollingEnabled}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="Polling Interval (seconds): "
|
||||
VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<TextBox Text="{Binding PollingIntervalSeconds}"
|
||||
Width="60" Padding="5"/>
|
||||
</StackPanel>
|
||||
|
||||
<CheckBox Content="Prevent Duplicate Power Plan Changes"
|
||||
IsChecked="{Binding PreventDuplicatePowerPlanChanges}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,15">
|
||||
<TextBlock Text="Power Plan Change Delay (ms): "
|
||||
VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<TextBox Text="{Binding PowerPlanChangeDelayMs}"
|
||||
Width="80" Padding="5"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Content="Save Configuration"
|
||||
Command="{Binding SaveConfigurationCommand}"
|
||||
Padding="15,8" HorizontalAlignment="Left"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for ProcessPowerPlanAssociationView.xaml
|
||||
/// </summary>
|
||||
public partial class ProcessPowerPlanAssociationView : System.Windows.Controls.UserControl
|
||||
{
|
||||
public ProcessPowerPlanAssociationView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+168
-37
@@ -1,12 +1,21 @@
|
||||
<UserControl x:Class="ThreadPilot.Views.ProcessView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:ThreadPilot.Views"
|
||||
xmlns:helpers="clr-namespace:ThreadPilot.Helpers"
|
||||
mc:Ignorable="d"
|
||||
xmlns:converters="clr-namespace:ThreadPilot.Converters"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="650" d:DesignWidth="1200">
|
||||
|
||||
<UserControl.Resources>
|
||||
<converters:CoreTypeToColorConverter x:Key="CoreTypeToColorConverter"/>
|
||||
<converters:BoolToColorConverter x:Key="BoolToColorConverter"/>
|
||||
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
|
||||
<converters:AffinityMaskConverter x:Key="AffinityMaskConverter"/>
|
||||
<converters:BytesToMbConverter x:Key="BytesToMbConverter"/>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="10">
|
||||
<Grid.RowDefinitions>
|
||||
@@ -16,14 +25,19 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Search and Refresh Controls -->
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBox Width="200"
|
||||
Margin="0,0,10,0"
|
||||
Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
<Button Command="{Binding LoadProcessesCommand}"
|
||||
Content="Refresh"
|
||||
Padding="10,5"/>
|
||||
</StackPanel>
|
||||
<GroupBox Grid.Row="0" Header="🔍 Process Search & Control" Margin="0,0,0,10">
|
||||
<StackPanel Orientation="Horizontal" Margin="5">
|
||||
<TextBox Width="200"
|
||||
Margin="0,0,10,0"
|
||||
Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"
|
||||
ToolTip="Search processes by name"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Command="{Binding LoadProcessesCommand}"
|
||||
Content="🔄 Refresh"
|
||||
Padding="10,5"
|
||||
ToolTip="Refresh the process list"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Process List -->
|
||||
<DataGrid Grid.Row="1"
|
||||
@@ -62,6 +76,7 @@
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Priority Controls -->
|
||||
@@ -79,42 +94,158 @@
|
||||
<Button Command="{Binding SetPriorityCommand}"
|
||||
CommandParameter="{Binding SelectedProcess.Priority}"
|
||||
Content="Set Priority"
|
||||
Padding="10,5"/>
|
||||
Padding="10,5"
|
||||
ToolTip="Apply the selected priority to the process"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Affinity Controls -->
|
||||
<GroupBox Grid.Column="1" Header="CPU Affinity" Margin="5,0,0,0">
|
||||
<!-- Power Plan Selection -->
|
||||
<GroupBox Grid.Column="1" Header="Power Plan" Margin="5,0,5,0">
|
||||
<StackPanel Margin="5">
|
||||
<ComboBox ItemsSource="{Binding PowerPlans}"
|
||||
SelectedItem="{Binding SelectedPowerPlan}"
|
||||
DisplayMemberPath="Name"
|
||||
Margin="0,0,0,5"/>
|
||||
<Button Command="{Binding SetPowerPlanCommand}"
|
||||
Content="Set Power Plan"
|
||||
Padding="10,5"
|
||||
ToolTip="Apply the selected power plan to the system"/>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- Advanced CPU Affinity Controls -->
|
||||
<GroupBox Grid.Column="2" Header="Advanced CPU Affinity" Margin="5,0,0,0">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<WrapPanel x:Name="CpuAffinityPanel" Grid.Row="0">
|
||||
<CheckBox Content="CPU 0" Tag="1" Margin="5" IsChecked="{Binding IsCpu0Selected}"/>
|
||||
<CheckBox Content="CPU 1" Tag="2" Margin="5" IsChecked="{Binding IsCpu1Selected}"/>
|
||||
<CheckBox Content="CPU 2" Tag="4" Margin="5" IsChecked="{Binding IsCpu2Selected}"/>
|
||||
<CheckBox Content="CPU 3" Tag="8" Margin="5" IsChecked="{Binding IsCpu3Selected}"/>
|
||||
<CheckBox Content="CPU 4" Tag="16" Margin="5" IsChecked="{Binding IsCpu4Selected}"/>
|
||||
<CheckBox Content="CPU 5" Tag="32" Margin="5" IsChecked="{Binding IsCpu5Selected}"/>
|
||||
<CheckBox Content="CPU 6" Tag="64" Margin="5" IsChecked="{Binding IsCpu6Selected}"/>
|
||||
<CheckBox Content="CPU 7" Tag="128" Margin="5" IsChecked="{Binding IsCpu7Selected}"/>
|
||||
<CheckBox Content="CPU 8" Tag="256" Margin="5" IsChecked="{Binding IsCpu8Selected}"/>
|
||||
<CheckBox Content="CPU 9" Tag="512" Margin="5" IsChecked="{Binding IsCpu9Selected}"/>
|
||||
<CheckBox Content="CPU 10" Tag="1024" Margin="5" IsChecked="{Binding IsCpu10Selected}"/>
|
||||
<CheckBox Content="CPU 11" Tag="2048" Margin="5" IsChecked="{Binding IsCpu11Selected}"/>
|
||||
<CheckBox Content="CPU 12" Tag="4096" Margin="5" IsChecked="{Binding IsCpu12Selected}"/>
|
||||
<CheckBox Content="CPU 13" Tag="8192" Margin="5" IsChecked="{Binding IsCpu13Selected}"/>
|
||||
<CheckBox Content="CPU 14" Tag="16384" Margin="5" IsChecked="{Binding IsCpu14Selected}"/>
|
||||
<CheckBox Content="CPU 15" Tag="32768" Margin="5" IsChecked="{Binding IsCpu15Selected}"/>
|
||||
</WrapPanel>
|
||||
<!-- Topology Status and HyperThreading Control -->
|
||||
<StackPanel Grid.Row="0" Orientation="Vertical" Margin="0,0,0,5">
|
||||
<TextBlock Text="{Binding TopologyStatus}"
|
||||
FontSize="10"
|
||||
Foreground="{Binding IsTopologyDetectionSuccessful, Converter={StaticResource BoolToColorConverter}}"/>
|
||||
<CheckBox Content="Enable HyperThreading"
|
||||
IsChecked="{Binding EnableHyperThreading}"
|
||||
IsEnabled="{Binding CpuTopology.HasHyperThreading}"
|
||||
FontSize="10"
|
||||
Margin="0,2,0,0"
|
||||
ToolTip="Include HyperThreading siblings in affinity calculations"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Row="1"
|
||||
Command="{Binding SetAffinityCommand}"
|
||||
Content="Set Affinity"
|
||||
Margin="0,5,0,0"
|
||||
Padding="10,5"/>
|
||||
<!-- Quick Selection Presets -->
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,0,0,5">
|
||||
<Button Command="{Binding SelectAllCoresCommand}"
|
||||
Content="All"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"
|
||||
ToolTip="Select all CPU cores"/>
|
||||
<Button Command="{Binding SelectPhysicalCoresOnlyCommand}"
|
||||
Content="Physical"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"
|
||||
IsEnabled="{Binding CpuTopology.HasHyperThreading}"
|
||||
ToolTip="Select only physical cores (no hyperthreading)"/>
|
||||
<Button Command="{Binding SelectPerformanceCoresCommand}"
|
||||
Content="P-Cores"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"
|
||||
IsEnabled="{Binding CpuTopology.HasIntelHybrid}"
|
||||
ToolTip="Select performance cores (Intel hybrid architecture)"/>
|
||||
<Button Command="{Binding SelectEfficiencyCoresCommand}"
|
||||
Content="E-Cores"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"
|
||||
IsEnabled="{Binding CpuTopology.HasIntelHybrid}"
|
||||
ToolTip="Select efficiency cores (Intel hybrid architecture)"/>
|
||||
<Button Command="{Binding ClearCoreSelectionCommand}"
|
||||
Content="Clear"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"
|
||||
ToolTip="Clear all core selections"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- CCD Selection (AMD) -->
|
||||
<ItemsControl Grid.Row="2"
|
||||
ItemsSource="{Binding CpuTopology.AvailableCcds}"
|
||||
Visibility="{Binding CpuTopology.HasAmdCcd, Converter={StaticResource BoolToVisibilityConverter}}"
|
||||
Margin="0,0,0,5">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Button Command="{Binding DataContext.SelectCcdCoresCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
CommandParameter="{Binding}"
|
||||
Content="{Binding StringFormat=CCD {0}}"
|
||||
Padding="5,2"
|
||||
Margin="0,0,3,0"
|
||||
FontSize="10"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
<!-- CPU Core Grid -->
|
||||
<ScrollViewer Grid.Row="3"
|
||||
MaxHeight="120"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Disabled"
|
||||
Margin="0,0,0,5">
|
||||
<ItemsControl ItemsSource="{Binding CpuCores}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<CheckBox Content="{Binding Label}"
|
||||
IsChecked="{Binding IsSelected}"
|
||||
IsEnabled="{Binding IsEnabled}"
|
||||
Margin="2"
|
||||
FontSize="9"
|
||||
ToolTip="{Binding StringFormat=Core {0}: {1}}">
|
||||
<CheckBox.Foreground>
|
||||
<MultiBinding Converter="{StaticResource CoreTypeToColorConverter}">
|
||||
<Binding Path="CoreType"/>
|
||||
<Binding Path="IsHyperThreaded"/>
|
||||
</MultiBinding>
|
||||
</CheckBox.Foreground>
|
||||
</CheckBox>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<StackPanel Grid.Row="4" Orientation="Horizontal">
|
||||
<Button Command="{Binding SetAffinityCommand}"
|
||||
Content="Set Affinity"
|
||||
Padding="10,5"
|
||||
Margin="0,0,5,0"
|
||||
ToolTip="Apply the selected CPU core affinity to the process"/>
|
||||
<Button Command="{Binding QuickApplyAffinityAndPowerPlanCommand}"
|
||||
Content="Quick Apply"
|
||||
Padding="10,5"
|
||||
Margin="0,0,5,0"
|
||||
ToolTip="Apply both CPU affinity and power plan"/>
|
||||
<Button Command="{Binding RefreshTopologyCommand}"
|
||||
Content="Refresh"
|
||||
Padding="5,5"
|
||||
FontSize="10"
|
||||
ToolTip="Refresh CPU topology detection"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
</Grid>
|
||||
|
||||
@@ -4,7 +4,7 @@ using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
public partial class ProcessView : UserControl
|
||||
public partial class ProcessView : System.Windows.Controls.UserControl
|
||||
{
|
||||
public ProcessView()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
<UserControl x:Class="ThreadPilot.Views.SettingsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:ThreadPilot.Views"
|
||||
xmlns:converters="clr-namespace:ThreadPilot.Converters"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="600" d:DesignWidth="800">
|
||||
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="SectionHeaderStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="16"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Margin" Value="0,10,0,5"/>
|
||||
<Setter Property="Foreground" Value="#2E3440"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="DescriptionStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="11"/>
|
||||
<Setter Property="Foreground" Value="#5E81AC"/>
|
||||
<Setter Property="Margin" Value="0,2,0,0"/>
|
||||
<Setter Property="TextWrapping" Value="Wrap"/>
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="20">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Header -->
|
||||
<StackPanel Grid.Row="0" Margin="0,0,0,20">
|
||||
<TextBlock Text="Application Settings" FontSize="24" FontWeight="Bold" Foreground="#2E3440"/>
|
||||
<TextBlock Text="Configure notifications, system tray, and application behavior"
|
||||
Style="{StaticResource DescriptionStyle}" FontSize="12"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Settings Content -->
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
|
||||
<!-- Notifications Section -->
|
||||
<TextBlock Text="Notifications" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Enable notifications"
|
||||
IsChecked="{Binding Settings.EnableNotifications}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<CheckBox Content="Enable balloon notifications (system tray)"
|
||||
IsChecked="{Binding Settings.EnableBalloonNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Enable toast notifications (Windows 10+)"
|
||||
IsChecked="{Binding Settings.EnableToastNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Separator Margin="0,10"/>
|
||||
|
||||
<TextBlock Text="Notification Types" FontWeight="SemiBold" Margin="0,5"/>
|
||||
|
||||
<CheckBox Content="Power plan changes"
|
||||
IsChecked="{Binding Settings.EnablePowerPlanChangeNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,5,0,5"/>
|
||||
|
||||
<CheckBox Content="Process monitoring events"
|
||||
IsChecked="{Binding Settings.EnableProcessMonitoringNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Error notifications"
|
||||
IsChecked="{Binding Settings.EnableErrorNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Success notifications"
|
||||
IsChecked="{Binding Settings.EnableSuccessNotifications}"
|
||||
IsEnabled="{Binding Settings.EnableNotifications}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Separator Margin="0,10"/>
|
||||
|
||||
<Grid Margin="0,5">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Notification duration (ms):" VerticalAlignment="Center"/>
|
||||
<Slider Grid.Column="1"
|
||||
Value="{Binding Settings.NotificationDisplayDurationMs}"
|
||||
Minimum="1000" Maximum="30000"
|
||||
TickFrequency="1000"
|
||||
IsSnapToTickEnabled="True"
|
||||
Margin="10,0"/>
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Settings.NotificationDisplayDurationMs}"
|
||||
VerticalAlignment="Center" MinWidth="50"/>
|
||||
</Grid>
|
||||
|
||||
<Button Content="Test Notification"
|
||||
Command="{Binding TestNotificationCommand}"
|
||||
HorizontalAlignment="Left"
|
||||
Margin="0,10,0,0"
|
||||
Padding="15,5"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- System Tray Section -->
|
||||
<TextBlock Text="System Tray" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Show tray icon"
|
||||
IsChecked="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<CheckBox Content="Minimize to tray"
|
||||
IsChecked="{Binding Settings.MinimizeToTray}"
|
||||
IsEnabled="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Close to tray (instead of exit)"
|
||||
IsChecked="{Binding Settings.CloseToTray}"
|
||||
IsEnabled="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Start minimized"
|
||||
IsChecked="{Binding Settings.StartMinimized}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Separator Margin="0,10"/>
|
||||
|
||||
<CheckBox Content="Enable quick apply from tray"
|
||||
IsChecked="{Binding Settings.EnableQuickApplyFromTray}"
|
||||
IsEnabled="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="0,5"/>
|
||||
|
||||
<CheckBox Content="Enable monitoring controls from tray"
|
||||
IsChecked="{Binding Settings.EnableMonitoringControlFromTray}"
|
||||
IsEnabled="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="0,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Show detailed tooltips"
|
||||
IsChecked="{Binding Settings.ShowDetailedTooltips}"
|
||||
IsEnabled="{Binding Settings.ShowTrayIcon}"
|
||||
Margin="0,0,0,10"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Autostart Section -->
|
||||
<TextBlock Text="Autostart" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Start with Windows"
|
||||
IsChecked="{Binding Settings.AutostartWithWindows}"
|
||||
Margin="0,0,0,10"/>
|
||||
<TextBlock Text="Automatically start ThreadPilot when Windows starts"
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="20,0,0,10"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Power Plan Settings Section -->
|
||||
<TextBlock Text="Power Plan Settings" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<Grid Margin="0,0,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Default power plan:" VerticalAlignment="Center"/>
|
||||
<ComboBox Grid.Column="1"
|
||||
ItemsSource="{Binding AvailablePowerPlans}"
|
||||
SelectedValue="{Binding Settings.DefaultPowerPlanId}"
|
||||
SelectedValuePath="Id"
|
||||
DisplayMemberPath="Name"
|
||||
Margin="10,0"/>
|
||||
<Button Grid.Column="2" Content="Refresh"
|
||||
Command="{Binding RefreshPowerPlansCommand}"
|
||||
Padding="10,5" Margin="5,0,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<CheckBox Content="Restore default power plan on exit"
|
||||
IsChecked="{Binding Settings.RestoreDefaultPowerPlanOnExit}"
|
||||
Margin="0,0,0,10"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Game Boost Mode Section -->
|
||||
<TextBlock Text="Game Boost Mode" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Enable Game Boost mode"
|
||||
IsChecked="{Binding Settings.EnableGameBoostMode}"
|
||||
Margin="0,0,0,10"/>
|
||||
<TextBlock Text="Automatically optimize performance when games are detected"
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Grid Margin="0,5,0,10" IsEnabled="{Binding Settings.EnableGameBoostMode}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Game Boost power plan:" VerticalAlignment="Center"/>
|
||||
<ComboBox Grid.Column="1"
|
||||
ItemsSource="{Binding AvailablePowerPlans}"
|
||||
SelectedValue="{Binding Settings.GameBoostPowerPlanId}"
|
||||
SelectedValuePath="Id"
|
||||
DisplayMemberPath="Name"
|
||||
Margin="10,0"/>
|
||||
</Grid>
|
||||
|
||||
<CheckBox Content="Auto-detect games"
|
||||
IsChecked="{Binding Settings.GameBoostAutoDetectGames}"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Set high process priority"
|
||||
IsChecked="{Binding Settings.GameBoostSetHighPriority}"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"
|
||||
Margin="20,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Optimize CPU affinity"
|
||||
IsChecked="{Binding Settings.GameBoostOptimizeCpuAffinity}"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Grid Margin="20,5,0,10" IsEnabled="{Binding Settings.EnableGameBoostMode}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Detection delay (ms):" VerticalAlignment="Center"/>
|
||||
<Slider Grid.Column="1"
|
||||
Value="{Binding Settings.GameBoostDetectionDelayMs}"
|
||||
Minimum="500" Maximum="10000"
|
||||
TickFrequency="500"
|
||||
IsSnapToTickEnabled="True"
|
||||
Margin="10,0"/>
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Settings.GameBoostDetectionDelayMs}"
|
||||
VerticalAlignment="Center" MinWidth="50"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Game Management Section -->
|
||||
<Separator Margin="0,10,0,10" IsEnabled="{Binding Settings.EnableGameBoostMode}"/>
|
||||
<TextBlock Text="Known Games Management"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,0,5"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"/>
|
||||
|
||||
<Grid Margin="0,5,0,10" IsEnabled="{Binding Settings.EnableGameBoostMode}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBox x:Name="NewGameTextBox"
|
||||
Grid.Column="0"
|
||||
Text="{Binding NewGameExecutableName, UpdateSourceTrigger=PropertyChanged}"
|
||||
ToolTip="Enter game executable name (e.g., game.exe)"
|
||||
Margin="0,0,5,0"/>
|
||||
<Button Grid.Column="1"
|
||||
Content="Add Game"
|
||||
Command="{Binding AddKnownGameCommand}"
|
||||
Margin="5,0"/>
|
||||
<Button Grid.Column="2"
|
||||
Content="Remove Selected"
|
||||
Command="{Binding RemoveKnownGameCommand}"
|
||||
Margin="5,0,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<ListBox ItemsSource="{Binding KnownGameExecutables}"
|
||||
SelectedItem="{Binding SelectedKnownGame}"
|
||||
Height="120"
|
||||
Margin="0,5,0,10"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Auto">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}" Padding="5,2"/>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<TextBlock Text="{Binding KnownGameExecutables.Count, StringFormat='Total known games: {0}'}"
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="0,0,0,5"
|
||||
IsEnabled="{Binding Settings.EnableGameBoostMode}"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Monitoring Settings Section -->
|
||||
<TextBlock Text="Monitoring Settings" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Enable WMI monitoring"
|
||||
IsChecked="{Binding Settings.EnableWmiMonitoring}"
|
||||
Margin="0,0,0,10"/>
|
||||
<TextBlock Text="Use Windows Management Instrumentation for real-time process monitoring"
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<CheckBox Content="Enable fallback polling"
|
||||
IsChecked="{Binding Settings.EnableFallbackPolling}"
|
||||
Margin="0,0,0,10"/>
|
||||
<TextBlock Text="Use polling as backup when WMI monitoring fails"
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="20,0,0,10"/>
|
||||
|
||||
<Grid Margin="0,5,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Polling interval (ms):" VerticalAlignment="Center"/>
|
||||
<Slider Grid.Column="1"
|
||||
Value="{Binding Settings.PollingIntervalMs}"
|
||||
Minimum="1000" Maximum="30000"
|
||||
TickFrequency="1000"
|
||||
IsSnapToTickEnabled="True"
|
||||
Margin="10,0"/>
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Settings.PollingIntervalMs}"
|
||||
VerticalAlignment="Center" MinWidth="50"/>
|
||||
</Grid>
|
||||
|
||||
<Grid Margin="0,5,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Fallback polling interval (ms):" VerticalAlignment="Center"/>
|
||||
<Slider Grid.Column="1"
|
||||
Value="{Binding Settings.FallbackPollingIntervalMs}"
|
||||
Minimum="5000" Maximum="60000"
|
||||
TickFrequency="5000"
|
||||
IsSnapToTickEnabled="True"
|
||||
Margin="10,0"/>
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Settings.FallbackPollingIntervalMs}"
|
||||
VerticalAlignment="Center" MinWidth="50"/>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Advanced Section -->
|
||||
<TextBlock Text="Advanced" Style="{StaticResource SectionHeaderStyle}"/>
|
||||
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
|
||||
<StackPanel>
|
||||
<CheckBox Content="Enable notification history"
|
||||
IsChecked="{Binding Settings.EnableNotificationHistory}"
|
||||
Margin="0,0,0,10"/>
|
||||
|
||||
<Grid Margin="0,5" IsEnabled="{Binding Settings.EnableNotificationHistory}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="Max history items:" VerticalAlignment="Center"/>
|
||||
<Slider Grid.Column="1"
|
||||
Value="{Binding Settings.MaxNotificationHistoryItems}"
|
||||
Minimum="10" Maximum="1000"
|
||||
TickFrequency="10"
|
||||
IsSnapToTickEnabled="True"
|
||||
Margin="10,0"/>
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Settings.MaxNotificationHistoryItems}"
|
||||
VerticalAlignment="Center" MinWidth="50"/>
|
||||
</Grid>
|
||||
|
||||
<CheckBox Content="Auto-hide notifications"
|
||||
IsChecked="{Binding Settings.AutoHideNotifications}"
|
||||
Margin="0,10,0,5"/>
|
||||
|
||||
<CheckBox Content="Enable notification sound"
|
||||
IsChecked="{Binding Settings.EnableNotificationSound}"
|
||||
Margin="0,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Enable debug logging"
|
||||
IsChecked="{Binding Settings.EnableDebugLogging}"
|
||||
Margin="0,0,0,5"/>
|
||||
|
||||
<CheckBox Content="Enable performance counters"
|
||||
IsChecked="{Binding Settings.EnablePerformanceCounters}"
|
||||
Margin="0,0,0,10"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Footer with buttons and status -->
|
||||
<Grid Grid.Row="2" Margin="0,20,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Status -->
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="{Binding StatusMessage}"
|
||||
Foreground="#5E81AC"
|
||||
Margin="0,0,0,10"
|
||||
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}"/>
|
||||
|
||||
<!-- Buttons -->
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
|
||||
<Button Content="Reset to Defaults"
|
||||
Command="{Binding ResetToDefaultsCommand}"
|
||||
Margin="0,0,10,0"
|
||||
Padding="15,8"/>
|
||||
|
||||
<Button Content="Export Settings"
|
||||
Command="{Binding ExportSettingsCommand}"
|
||||
Margin="0,0,10,0"
|
||||
Padding="15,8"/>
|
||||
|
||||
<Button Content="Import Settings"
|
||||
Command="{Binding ImportSettingsCommand}"
|
||||
Margin="0,0,20,0"
|
||||
Padding="15,8"/>
|
||||
|
||||
<Button Content="Save Settings"
|
||||
Command="{Binding SaveSettingsCommand}"
|
||||
Background="#5E81AC"
|
||||
Foreground="White"
|
||||
Padding="20,8"
|
||||
FontWeight="SemiBold"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Windows.Controls;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for SettingsView.xaml
|
||||
/// </summary>
|
||||
public partial class SettingsView : System.Windows.Controls.UserControl
|
||||
{
|
||||
public SettingsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public SettingsView(SettingsViewModel viewModel) : this()
|
||||
{
|
||||
DataContext = viewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Window x:Class="ThreadPilot.Views.SettingsWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:ThreadPilot.Views"
|
||||
mc:Ignorable="d"
|
||||
Title="ThreadPilot Settings"
|
||||
Height="700" Width="900"
|
||||
MinHeight="600" MinWidth="800"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False"
|
||||
Icon="/Resources/icon.ico">
|
||||
|
||||
<Window.Resources>
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="Background" Value="#FFFFFF"/>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Grid>
|
||||
<local:SettingsView x:Name="SettingsViewControl"/>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot.Views
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for SettingsWindow.xaml
|
||||
/// </summary>
|
||||
public partial class SettingsWindow : Window
|
||||
{
|
||||
private readonly SettingsViewModel _viewModel;
|
||||
|
||||
public SettingsWindow(SettingsViewModel viewModel)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
|
||||
SettingsViewControl.DataContext = _viewModel;
|
||||
}
|
||||
|
||||
protected override void OnClosing(CancelEventArgs e)
|
||||
{
|
||||
// Check for unsaved changes
|
||||
if (!_viewModel.CanClose())
|
||||
{
|
||||
var result = System.Windows.MessageBox.Show(
|
||||
"You have unsaved changes. Do you want to save them before closing?",
|
||||
"Unsaved Changes",
|
||||
System.Windows.MessageBoxButton.YesNoCancel,
|
||||
System.Windows.MessageBoxImage.Question);
|
||||
|
||||
switch (result)
|
||||
{
|
||||
case System.Windows.MessageBoxResult.Yes:
|
||||
// Save and close
|
||||
if (_viewModel.SaveSettingsCommand.CanExecute(null))
|
||||
{
|
||||
_viewModel.SaveSettingsCommand.Execute(null);
|
||||
}
|
||||
break;
|
||||
case System.Windows.MessageBoxResult.No:
|
||||
// Close without saving
|
||||
break;
|
||||
case System.Windows.MessageBoxResult.Cancel:
|
||||
// Cancel closing
|
||||
e.Cancel = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
base.OnClosing(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"defaultPowerPlanGuid": "",
|
||||
"defaultPowerPlanName": "",
|
||||
"isEventBasedMonitoringEnabled": true,
|
||||
"isFallbackPollingEnabled": true,
|
||||
"pollingIntervalSeconds": 5,
|
||||
"preventDuplicatePowerPlanChanges": true,
|
||||
"powerPlanChangeDelayMs": 1000,
|
||||
"enableLogging": true,
|
||||
"associations": [],
|
||||
"lastSavedDate": "2025-07-29T00:12:48.6077094+02:00",
|
||||
"configurationVersion": "1.0"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user