15 KiB
Core APIs
**Referenced Files in This Document** - [Engine.cs](file://ClassicAssist.Avalonia/Engine.cs) - [App.axaml.cs](file://ClassicAssist.Avalonia/App.axaml.cs) - [Program.cs](file://ClassicAssist.Avalonia/Program.cs) - [AvaloniaDispatcher.cs](file://ClassicAssist.Avalonia/AvaloniaDispatcher.cs) - [AvaloniaUIInvoker.cs](file://ClassicAssist.Avalonia/AvaloniaUIInvoker.cs) - [CommandsManager.cs](file://ClassicAssist.Shared/Data/Commands/CommandsManager.cs) - [BaseViewModel.cs](file://ClassicAssist.Shared/UI/ViewModels/BaseViewModel.cs) - [ExtensionMethods.cs](file://ClassicAssist/Misc/ExtensionMethods.cs) - [ExtensionMethods.cs](file://ClassicAssist.Shared/Misc/ExtensionMethods.cs)Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
Introduction
This document provides comprehensive API documentation for ClassicAssist.Avalonia’s core application interfaces, focusing on:
- Engine class for application lifecycle management, initialization, and shutdown procedures
- Commands API for game command execution and routing
- BaseViewModel for property binding, event handling, and MVVM pattern implementation
- ExtensionMethods utility classes with helper functions and common operations
The goal is to help developers integrate and consume these APIs safely, understand thread-safety considerations, performance implications, and best practices.
Project Structure
At a high level, the Avalonia-based application entry points initialize the UI framework and start the Engine. Shared components (commands, view models, utilities) live in ClassicAssist.Shared and are consumed by both WPF and Avalonia implementations. The following diagram shows the key files involved in startup and core APIs.
graph TB
Program["Program.cs"] --> App["App.axaml.cs"]
App --> EngineAvalonia["Engine.cs (Avalonia)"]
EngineAvalonia --> Dispatcher["AvaloniaDispatcher.cs"]
EngineAvalonia --> UIInvoker["AvaloniaUIInvoker.cs"]
EngineAvalonia --> CommandsShared["CommandsManager.cs (Shared)"]
EngineAvalonia --> BaseVM["BaseViewModel.cs (Shared)"]
EngineAvalonia --> ExtWPF["ExtensionMethods.cs (WPF)"]
EngineAvalonia --> ExtShared["ExtensionMethods.cs (Shared)"]
Diagram sources
- Program.cs
- App.axaml.cs
- Engine.cs
- AvaloniaDispatcher.cs
- AvaloniaUIInvoker.cs
- CommandsManager.cs
- BaseViewModel.cs
- ExtensionMethods.cs
- ExtensionMethods.cs
Section sources
Core Components
- Engine (Avalonia): Orchestrates application lifecycle, initializes subsystems, manages dispatching to UI threads, and coordinates shutdown.
- Commands API (Shared): Centralized command registration, discovery, parsing, and execution pipeline.
- BaseViewModel (Shared): MVVM base class providing property change notification, safe UI-thread updates, and common helpers.
- ExtensionMethods (WPF and Shared): Utility extensions for common operations used across the codebase.
Key responsibilities:
- Engine: bootstrap, configuration, service resolution, dispatcher integration, graceful shutdown
- Commands: attribute-driven or programmatic command registration, parameter parsing, invocation
- BaseViewModel: INotifyPropertyChanged-like behavior, thread-safe property updates, convenience methods
- Extensions: string, collection, object, and UI-related helpers
Section sources
Architecture Overview
The Avalonia application starts via Program, which bootstraps App. App initializes the Engine, which sets up the dispatcher and UI invoker, registers commands, and prepares the UI. ViewModels inherit from BaseViewModel to bind properties and handle events. Utilities in ExtensionMethods support common tasks throughout the app.
sequenceDiagram
participant OS as "Operating System"
participant Program as "Program.cs"
participant App as "App.axaml.cs"
participant Engine as "Engine.cs (Avalonia)"
participant Dispatcher as "AvaloniaDispatcher.cs"
participant UIInvoker as "AvaloniaUIInvoker.cs"
participant Commands as "CommandsManager.cs"
participant VM as "BaseViewModel.cs"
OS->>Program : Launch process
Program->>App : Create and configure App
App->>Engine : Initialize()
Engine->>Dispatcher : Set up dispatcher
Engine->>UIInvoker : Configure UI invoker
Engine->>Commands : Register commands
Engine-->>App : Ready
App-->>OS : Run message loop
VM->>VM : Property changes notify UI
Commands->>Commands : Parse and execute commands
Diagram sources
- Program.cs
- App.axaml.cs
- Engine.cs
- AvaloniaDispatcher.cs
- AvaloniaUIInvoker.cs
- CommandsManager.cs
- BaseViewModel.cs
Detailed Component Analysis
Engine (Avalonia)
Responsibilities:
- Application lifecycle: initialization, readiness signaling, shutdown
- Dispatcher integration: ensures UI updates occur on the correct thread
- UI invoker: abstracts UI-specific invoke semantics
- Command system integration: registers and exposes command execution facilities
- Resource and subsystem coordination: optional services and managers
Typical usage patterns:
- Call initialization during app startup
- Use provided dispatcher/invoker to marshal work to UI thread
- Invoke commands through the centralized manager
- Perform cleanup on shutdown
Thread safety:
- All UI-bound operations should be dispatched via the configured dispatcher/invoker
- Avoid direct cross-thread UI access; rely on Engine-provided abstractions
Error handling:
- Initialization failures should be surfaced early to allow graceful degradation
- Shutdown should release resources and stop background work
Best practices:
- Keep initialization lightweight; defer heavy work until needed
- Centralize error logging and user-facing messages via shared providers
- Ensure deterministic shutdown order to avoid race conditions
Section sources
Commands API (CommandsManager)
Responsibilities:
- Command registration (attribute-driven or programmatic)
- Command discovery and metadata storage
- Parameter parsing and validation
- Execution pipeline with context and result handling
- Routing to appropriate handlers
Method categories:
- Registration: add commands, aliases, and metadata
- Resolution: find commands by name or alias
- Invocation: parse input and execute target handler
- Enumeration: list available commands and help info
Usage examples:
- Register a command once during engine initialization
- Execute commands from macros, hotkeys, or UI actions
- Provide help text and parameter descriptions for discoverability
Exception handling:
- Validate parameters before execution
- Wrap handler exceptions to prevent crashes and provide meaningful errors
- Return structured results for callers to interpret
Thread safety:
- Command registration typically occurs on the main thread
- Execution may be invoked from various threads; ensure handlers use dispatcher when touching UI state
Performance:
- Cache resolved command references where possible
- Minimize allocations in hot paths (parsing, argument splitting)
Section sources
BaseViewModel
Responsibilities:
- Property change notification for data binding
- Safe UI-thread updates for bound properties
- Event handling helpers and subscription management
- Common MVVM utilities (e.g., can-execute flags, command wrappers)
Property binding:
- Implement change notifications consistently
- Prefer computed properties for derived values
- Avoid heavy logic in property getters/setters
Event handling:
- Subscribe/unsubscribe events safely
- Use weak references or explicit unsubscription to prevent leaks
MVVM pattern:
- Keep UI logic out of views; encapsulate in ViewModels
- Expose commands and observable collections for binding
Thread safety:
- Always update bound properties on the UI thread using the provided dispatcher/invoker
- Guard against concurrent modifications to collections exposed to UI
Best practices:
- Keep ViewModels lightweight and testable
- Use dependency injection for services
- Avoid direct UI framework dependencies in shared ViewModels
Section sources
ExtensionMethods (Utilities)
Two primary locations:
- WPF-specific extensions (ClassicAssist/Misc/ExtensionMethods.cs)
- Shared extensions (ClassicAssist.Shared/Misc/ExtensionMethods.cs)
Common categories:
- String utilities: trimming, formatting, null-safe operations
- Collection helpers: filtering, mapping, batching
- Object utilities: casting, null checks, defaulting
- UI helpers: dispatcher calls, resource lookups (platform-specific)
Usage guidance:
- Prefer shared extensions for cross-platform compatibility
- Use WPF-specific extensions only within WPF projects
- Keep extension methods small and focused
Performance:
- Avoid unnecessary allocations in frequently called helpers
- Be mindful of LINQ overhead in tight loops
Section sources
Dependency Analysis
The following diagram highlights key dependencies among core components.
classDiagram
class Program {
+Main()
}
class App {
+Initialize()
+Run()
}
class Engine {
+Initialize()
+Shutdown()
+DispatchToUI(action)
+InvokeUI(action)
}
class AvaloniaDispatcher {
+BeginInvoke(action)
+Invoke(action)
}
class AvaloniaUIInvoker {
+Invoke(action)
}
class CommandsManager {
+Register(command)
+Execute(input)
+Resolve(name)
}
class BaseViewModel {
+NotifyPropertyChanged(propertyName)
+UpdateOnUIThread(action)
}
class ExtensionMethods_WPF
class ExtensionMethods_Shared
Program --> App : "creates"
App --> Engine : "initializes"
Engine --> AvaloniaDispatcher : "uses"
Engine --> AvaloniaUIInvoker : "uses"
Engine --> CommandsManager : "registers/executes"
Engine --> BaseViewModel : "consumes"
Engine --> ExtensionMethods_Shared : "uses"
Engine --> ExtensionMethods_WPF : "uses (WPF project)"
Diagram sources
- Program.cs
- App.axaml.cs
- Engine.cs
- AvaloniaDispatcher.cs
- AvaloniaUIInvoker.cs
- CommandsManager.cs
- BaseViewModel.cs
- ExtensionMethods.cs
- ExtensionMethods.cs
Section sources
Performance Considerations
- Minimize UI thread work: offload heavy computations to background threads and marshal results back to UI via dispatcher/invoker
- Batch UI updates: coalesce multiple property changes to reduce layout passes
- Avoid excessive allocations: reuse buffers and objects in hot paths
- Lazy initialization: defer expensive setup until first use
- Efficient command parsing: cache parsed structures when inputs repeat
- Careful event subscription: unsubscribe promptly to prevent memory leaks
[No sources needed since this section provides general guidance]
Troubleshooting Guide
Common issues and resolutions:
- Cross-thread UI access: always use dispatcher/invoker to update UI-bound properties
- Command not found: verify registration order and ensure names/aliases match exactly
- Exceptions in command handlers: wrap handler calls and log detailed context
- Memory leaks: ensure event subscriptions are disposed and long-lived references are released
- Startup failures: check initialization sequence and external dependencies availability
Operational tips:
- Enable verbose logging during development
- Add unit tests for command handlers and ViewModel logic
- Use profiling tools to identify bottlenecks in UI updates and command execution
Section sources
Conclusion
The core APIs of ClassicAssist.Avalonia center around a robust Engine that orchestrates lifecycle and threading, a flexible Commands API for extensible command execution, a solid BaseViewModel foundation for MVVM, and practical ExtensionMethods utilities. By adhering to thread-safety guidelines, leveraging dispatcher/invoker abstractions, and following best practices for performance and error handling, developers can build reliable and responsive features atop these interfaces.
[No sources needed since this section summarizes without analyzing specific files]