14 KiB
Hotkey Management
**Referenced Files in This Document** - [HotkeyManager.cs](file://ClassicAssist.Shared/Data/Hotkeys/HotkeyManager.cs) - [HotkeyEntry.cs](file://ClassicAssist.Shared/Data/Hotkeys/HotkeyEntry.cs) - [ShortcutKeys.cs](file://ClassicAssist.Shared/Data/Hotkeys/ShortcutKeys.cs) - [HotkeyChangedEventArgs.cs](file://ClassicAssist.Shared/Data/Hotkeys/HotkeyChangedEventArgs.cs) - [HotkeyCommand.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/HotkeyCommand.cs) - [HotkeyCommandAttribute.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/HotkeyCommandAttribute.cs) - [HotkeysTabControl.xaml.cs](file://ClassicAssist.Avalonia/Views/HotkeysTabControl.xaml.cs) - [HotkeysTabControl.xaml](file://ClassicAssist.Avalonia/Views/HotkeysTabControl.xaml) - [HotkeyEntryViewModel.cs](file://ClassicAssist.Shared/UI/ViewModels/HotkeyEntryViewModel.cs) - [HotkeysTabViewModel.cs](file://ClassicAssist.Shared/UI/ViewModels/HotkeysTabViewModel.cs) - [TextBoxKey.axaml.cs](file://ClassicAssist.Avalonia/Controls/TextBoxKey.axaml.cs) - [ToggleHotkeys.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/ToggleHotkeys.cs)Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
Introduction
The ClassicAssist.Avalonia hotkey management system provides a comprehensive framework for handling keyboard shortcuts and global hotkeys across the application. This system supports both local key bindings within the application context and global hotkeys that work even when the application is not focused. The architecture follows MVVM patterns and integrates seamlessly with Avalonia UI framework while maintaining cross-platform compatibility.
The hotkey system is designed to be extensible, allowing developers to register custom commands, handle conflicts between different components, and persist user preferences across application sessions. It supports modifier keys (Ctrl, Alt, Shift), function keys, and complex key combinations.
Project Structure
The hotkey management system is organized into several key components:
graph TB
subgraph "Core Hotkey System"
HM[HotkeyManager]
HE[HotkeyEntry]
SK[ShortcutKeys]
HCA[HotkeyChangedEventArgs]
end
subgraph "Command Framework"
HC[HotkeyCommand]
HCAtr[HotkeyCommandAttribute]
TH[ToggleHotkeys]
end
subgraph "UI Layer"
HTV[HotkeysTabViewModel]
HEV[HotkeyEntryViewModel]
TK[TextBoxKey Control]
HTC[HotkeysTabControl]
end
HM --> HE
HM --> SK
HM --> HCA
HE --> HC
HC --> HCAtr
HTV --> HEV
HTC --> HTV
TK --> HEV
Diagram sources
Section sources
Core Components
HotkeyManager Class Architecture
The HotkeyManager serves as the central coordinator for all hotkey operations in the application. It manages the lifecycle of hotkey registrations, handles conflict resolution, and coordinates between the UI layer and the underlying platform-specific implementations.
Key responsibilities include:
- Global hotkey registration and unregistration
- Conflict detection and resolution
- Event dispatching to registered handlers
- Configuration persistence and loading
- Cross-platform abstraction layer
HotkeyEntry Data Structure
The HotkeyEntry class represents individual hotkey configurations, containing:
- Key combination definition (modifier keys + primary key)
- Associated command or action reference
- Priority level for conflict resolution
- Description and metadata
- Enabled/disabled state
ShortcutKeys Utility
The ShortcutKeys class provides utility methods for parsing, validating, and manipulating key combinations. It handles:
- String-to-key conversion
- Key combination validation
- Platform-specific key code mapping
- Modifier key normalization
Section sources
Architecture Overview
The hotkey system follows a layered architecture pattern with clear separation of concerns:
sequenceDiagram
participant User as "User"
participant UI as "UI Layer"
participant VM as "ViewModel Layer"
participant HM as "HotkeyManager"
participant CMD as "Command Handler"
participant OS as "Operating System"
User->>UI : Presses key combination
UI->>VM : TextBoxKey captures input
VM->>HM : RegisterHotkey(keyCombination, command)
HM->>OS : Register global hotkey
OS-->>HM : Hotkey event
HM->>CMD : Execute command
CMD-->>VM : Update UI state
VM-->>UI : Refresh display
Note over HM,CMD : Command execution flow
HM->>HM : Check for conflicts
HM->>HM : Dispatch to appropriate handler
Diagram sources
Detailed Component Analysis
HotkeyManager Implementation
The HotkeyManager implements a singleton pattern to ensure centralized hotkey management throughout the application lifecycle.
Key Registration Process
flowchart TD
Start([RegisterHotkey Request]) --> Validate["Validate Key Combination"]
Validate --> Valid{"Valid Combination?"}
Valid --> |No| ReturnError["Return Validation Error"]
Valid --> |Yes| CheckConflict["Check for Conflicts"]
CheckConflict --> ConflictFound{"Conflict Found?"}
ConflictFound --> |Yes| ResolveConflict["Resolve Based on Priority"]
ConflictFound --> |No| RegisterGlobal["Register Global Hotkey"]
ResolveConflict --> RegisterGlobal
RegisterGlobal --> StoreEntry["Store HotkeyEntry"]
StoreEntry --> NotifyUI["Notify UI Updates"]
NotifyUI --> End([Registration Complete])
ReturnError --> End
Diagram sources
Conflict Resolution Mechanism
The system employs a priority-based conflict resolution strategy:
- Priority Levels: Each hotkey entry has an associated priority value
- Component Ownership: Built-in commands have higher priority than user-defined ones
- Last-Write-Wins: When priorities are equal, the last registration takes precedence
- Graceful Degradation: Lower priority hotkeys remain functional but may be disabled
Command Framework
The hotkey command framework provides a flexible mechanism for associating actions with key combinations.
HotkeyCommand Base Class
The HotkeyCommand class serves as the base for all hotkey-executable commands:
classDiagram
class HotkeyCommand {
+string Name
+string Description
+bool CanExecute()
+void Execute(object parameter)
+event EventHandler Executed
+event EventHandler CanExecuteChanged
}
class ToggleHotkeys {
+bool IsEnabled
+void Execute(object parameter)
-void ToggleHotkeyState()
}
class BandageSelf {
+void Execute(object parameter)
-void PerformBandageAction()
}
HotkeyCommand <|-- ToggleHotkeys
HotkeyCommand <|-- BandageSelf
Diagram sources
Custom Command Registration
Developers can create custom hotkey commands by extending the base HotkeyCommand class and registering them through the command manager.
UI Integration
The UI layer provides intuitive interfaces for hotkey configuration and management.
TextBoxKey Control
The TextBoxKey control offers a specialized input field for capturing key combinations:
- Real-time key capture and display
- Visual feedback for pressed keys
- Support for modifier key combinations
- Input validation and error handling
Hotkeys Tab Interface
The HotkeysTabControl provides a comprehensive interface for managing all hotkey configurations:
- Grid view of all registered hotkeys
- Inline editing capabilities
- Search and filtering functionality
- Import/export configuration support
Section sources
Dependency Analysis
The hotkey system maintains loose coupling between components through well-defined interfaces:
graph LR
subgraph "External Dependencies"
Avalonia[Avalonia UI]
Platform[Platform Abstraction]
Config[Configuration Manager]
end
subgraph "Internal Dependencies"
HM[HotkeyManager]
VM[ViewModels]
UI[UI Controls]
Commands[Command Handlers]
end
Avalonia --> UI
Platform --> HM
Config --> HM
HM --> VM
VM --> UI
HM --> Commands
Commands --> Platform
Diagram sources
Cross-Platform Considerations
The system abstracts platform-specific differences through the following mechanisms:
- Key Code Mapping: Unified key codes across Windows, macOS, and Linux
- Modifier Key Normalization: Consistent handling of Ctrl/Cmd, Alt/Option, Shift keys
- Global Hotkey APIs: Platform-specific global hotkey registration
- Event Handling: Abstracted event dispatching mechanism
Section sources
Performance Considerations
The hotkey system is optimized for minimal performance impact:
- Lazy Loading: Hotkey entries are loaded on-demand rather than at startup
- Efficient Lookup: Hash-based key combination lookup for O(1) performance
- Memory Management: Automatic cleanup of unused hotkey entries
- Threading: Asynchronous hotkey processing to prevent UI blocking
Troubleshooting Guide
Common Issues and Solutions
Hotkey Not Responding
Symptoms: Pressing a configured hotkey produces no response
Possible Causes:
- Hotkey conflict with another component
- Application focus issues
- Platform-specific limitations
Resolution Steps:
- Check for conflicting hotkeys in the Hotkeys tab
- Verify the hotkey is enabled and properly registered
- Test with a simple command first
- Review platform-specific restrictions
Global Hotkey Not Working
Symptoms: Global hotkeys don't work when application is not focused
Possible Causes:
- Insufficient permissions (especially on macOS)
- Antivirus software interference
- Platform-specific limitations
Resolution Steps:
- Run application with elevated privileges if required
- Check system settings for accessibility permissions
- Temporarily disable security software for testing
- Verify platform support for global hotkeys
Configuration Persistence Issues
Symptoms: Hotkey settings don't save between sessions
Possible Causes:
- File permission problems
- Corrupted configuration file
- Serialization errors
Resolution Steps:
- Check application data directory permissions
- Backup and reset configuration file
- Review error logs for serialization issues
- Verify configuration file format
Debugging Tools
The system includes built-in debugging capabilities:
- Hotkey Event Logging: Detailed logging of all hotkey events
- Conflict Detection: Real-time conflict monitoring and reporting
- Performance Metrics: Hotkey registration and execution timing
- Configuration Validation: Pre-save validation of hotkey configurations
Section sources
Conclusion
The ClassicAssist.Avalonia hotkey management system provides a robust, extensible, and user-friendly framework for handling keyboard shortcuts. Its modular architecture ensures maintainability while supporting complex use cases through its command framework and conflict resolution mechanisms. The system's cross-platform design and comprehensive UI integration make it suitable for diverse deployment scenarios.
Key strengths include:
- Comprehensive conflict resolution strategies
- Extensible command framework
- Intuitive user interface for configuration
- Cross-platform compatibility
- Robust error handling and debugging support
Future enhancements could include advanced macro recording, hotkey profiles, and cloud synchronization of configurations.
Appendices
Example: Implementing Custom Hotkey Handlers
To implement a custom hotkey handler:
- Create a new class extending
HotkeyCommand - Override the
Executemethod with your logic - Register the command through the command manager
- Bind a key combination in the UI or configuration
Configuration File Format
Hotkey configurations are stored in JSON format with the following structure:
{
"hotkeys": [
{
"id": "unique_identifier",
"key_combination": "Ctrl+Alt+A",
"command_name": "YourCommandName",
"priority": 1,
"enabled": true,
"description": "Optional description"
}
]
}
Testing Best Practices
- Use unit tests for command logic
- Implement integration tests for hotkey registration
- Test cross-platform compatibility
- Validate conflict resolution scenarios
- Monitor performance under load