Skip to content

TriggerManager

Assembly: TriggerManager

Namespace: TriggerManager

ActionDispatcher

Central action routing engine for SmrtHub's TriggerManager hotkey and context menu command dispatching.

Remarks

ActionDispatcher implements the HTTP routing tier that forwards hotkey-triggered commands to their downstream services. It is intentionally small: a immutable route table determines the destination, JSON payloads are posted asynchronously, and the results are captured through SmrtHub.Logging.Logger so telemetry lands in the unified trigger-manager log set. All endpoints are localhost-only to preserve the SmrtHub security posture. - Routing: Sends trigger commands to the Python trigger service over loopback (where applicable). - Asynchronous Dispatch: Uses async execution to avoid blocking the WinForms message pump. - Unified Logging: Emits successes and failures through SmrtHub.Logging instead of ad-hoc files. - Error Resilience: Captures network exceptions without crashing the hotkey loop. - Stable Hotkey IDs: Uses stable internal identifiers independent of UI button naming.

Default Routing Map: • Most shipped hotkeys → http://127.0.0.1:5001/trigger • Clipboard OCR hotkeys → local execution (no UI wiring)

Security Considerations: All traffic stays on loopback, payloads carry no PII, and downstream services inherit the SmrtHub logging + redaction policies.

Fields

routeMap

Immutable route mapping dictionary defining command-to-action relationships.

Remarks

Configured during construction to provide predictable routing behavior throughout dispatcher lifetime. Maps hotkey command names to lambda expressions that handle specific dispatch logic.

Methods

ActionDispatcher()

Initializes a new ActionDispatcher instance with predefined routing configuration.

Remarks

Constructor wires the built-in routing table used by SmrtHub desktop hotkeys. The map is immutable by design so the downstream integrations remain predictable and auditable. Adjustments are made in source control alongside accompanying documentation updates.

Dispatch(string hotkey)

Executes the appropriate action for a given hotkey command using the configured routing table.

Parameters

  • hotkey — The hotkey command name to dispatch (e.g., "HOTKEY_SMRTSAVE").

Remarks

Primary dispatch entry point that performs route lookup and executes the associated action. Unknown hotkey commands are logged as errors but do not throw exceptions, ensuring system stability during unexpected input scenarios.

Dispatch Process: 1. Lookup hotkey in route mapping dictionary 2. Log dispatch attempt for audit trail 3. Execute associated action (HTTP request to C# or Python endpoint) 4. Log error if hotkey not found in routing table

Method is thread-safe and non-blocking, with actual HTTP communication handled asynchronously by individual action implementations.

SendToPythonAsync(string hotkeyName)

Sends HTTP POST request to the Python Flask backend with JSON-formatted hotkey command.

Parameters

  • hotkeyName — The hotkey command name to include in the JSON payload.

Remarks

Asynchronous method for communicating with Python Flask backend services running on localhost:5001. Handles the majority of hotkey commands that require Python processing such as file operations, web scraping, and content management tasks.

Python Backend Communication: • Endpoint: http://127.0.0.1:5001/trigger • Protocol: HTTP POST with JSON payload • Expected Response: JSON status information • Timeout: Default HttpClient timeout behavior

Error Recovery: • Network failures captured through SmrtHub.Logging without crashing the message loop • HTTP errors recorded with status codes for downstream diagnostics

Method assumes Python backend is running and listening on the specified port. If backend is unavailable, operations fail gracefully with error logging.

HotkeyManager

Windows API integration manager for global hotkey registration, event processing, and configuration management.

Remarks

HotkeyManager provides comprehensive global hotkey functionality through direct Windows API integration, enabling system-wide keyboard shortcut registration that works regardless of application focus. The class implements IMessageFilter to intercept and process WM_HOTKEY messages from the Windows message pump, providing reliable hotkey event handling with automatic cleanup. - Global Hotkey Registration: System-wide keyboard shortcuts using Windows API - Configuration Management: JSON-based hotkey configuration with automatic file creation - Message Loop Integration: IMessageFilter implementation for reliable event processing - Resource Management: Automatic cleanup of hotkey registrations on application exit - Error Handling: Graceful handling of registration failures and invalid configurations

Windows API Integration: • RegisterHotKey: Registers global keyboard shortcuts with Windows • UnregisterHotKey: Removes hotkey registrations during cleanup • WM_HOTKEY (0x0312): Windows message for hotkey event notification • Message filtering: Intercepts and processes hotkey messages from Windows message pump

Configuration System: • Location: %AppData%/SmrtHub/Config/trigger-manager/hotkeys-settings.json resolved through TriggerManager.HotkeysConfig / SmrtHub.Config.ConfigPathResolver • Format: JSON dictionary mapping command names to hotkey strings (validated against the shipped schema) • Auto-creation: Bundled defaults copied on first run when no user file exists • Runtime loading: Configuration hydrated via TriggerManager.HotkeysConfig.LoadOrSeed during manager initialization

Hotkey Format Support: • Modifiers: Ctrl, Alt, Shift, Win (case-insensitive) • Keys: All standard Windows virtual key codes • Syntax: "Modifier+Modifier+Key" (e.g., "Ctrl+Shift+S") • Multiple modifiers: Supported with plus separator

Default Hotkey Configuration: • HOTKEY_SMRTSAVE: Ctrl+Shift+S • HOTKEY_SMRTSEARCH: Ctrl+Shift+C • HUBWINDOW_TOGGLE: Ctrl+Shift+H

Threading and Message Processing: • Message filter registration: Added to application message loop during construction • Thread safety: All operations performed on main UI thread • Event handling: Synchronous processing of hotkey events • Action delegation: Executes registered actions via provided dictionary

Updates: • 2025-07-13: Added comprehensive XML documentation and standalone positioning • 2025-06-27: Enhanced with HubWindow toggle support and improved configuration management

Fields

WM_HOTKEY

Windows message constant for hotkey event notifications.

Remarks

WM_HOTKEY (0x0312) is sent to the registered window when a global hotkey is pressed. Used for message filtering and event identification.

currentId

Auto-incrementing unique identifier for hotkey registrations to prevent ID conflicts.

Remarks

Ensures each hotkey registration receives a unique ID for Windows API registration and subsequent event identification during message processing.

hotkeyActions

Dictionary mapping command names to executable Action delegates for hotkey event handling.

Remarks

Provided during construction from TriggerDispatcher, contains all available hotkey actions that can be executed when corresponding hotkeys are pressed.

hotkeyIdToName

Mapping dictionary from hotkey registration IDs to command names for event routing.

Remarks

Populated during hotkey registration to enable reverse lookup from Windows-provided hotkey ID back to the original command name for action execution.

windowHandle

Window handle used for hotkey registration and message reception.

Remarks

Provided during construction from the invisible form, required by Windows API for hotkey registration and message delivery.

Methods

HotkeyManager(IntPtr hwnd, Collections.Generic.Dictionary actions)

Initializes a new HotkeyManager instance with the specified window handle and action mappings.

Parameters

  • hwnd — Window handle for hotkey registration and message reception.
  • actions — Dictionary mapping command names to executable Action delegates.

Remarks

Constructor establishes the fundamental components required for global hotkey processing: window handle for Windows API interaction and action mappings for command execution. Automatically registers this instance as a message filter to intercept WM_HOTKEY messages.

Initialization Process: 1. Store window handle for Windows API hotkey registration 2. Store action mappings for hotkey event execution 3. Register as Windows Forms message filter for hotkey message interception 4. Prepare for hotkey registration and event processing

The window handle typically comes from an invisible form that provides the necessary Windows API integration point without visible UI components.

PreFilterMessage(Windows.Forms.Message@ m)

IMessageFilter implementation that intercepts WM_HOTKEY messages and executes corresponding actions.

Parameters

  • m — Windows message structure containing message type and parameters.

Returns: True if the message was handled (WM_HOTKEY), false to continue normal processing.

Remarks

Core message processing method that intercepts WM_HOTKEY messages from the Windows message pump and routes them to the appropriate action handlers. Implements the IMessageFilter interface to participate in the Windows Forms message preprocessing pipeline.

Message Processing Flow: 1. Check if message is WM_HOTKEY (0x0312) 2. Extract hotkey ID from message wParam 3. Lookup command name using hotkey ID mapping 4. Lookup and execute action using command name 5. Log execution attempt and results 6. Return true to indicate message was handled

Error Resilience: • Unknown hotkey IDs logged but don't cause exceptions • Missing action mappings logged with warning messages • Action execution exceptions are contained within the action itself

This method is called automatically by the Windows Forms message loop and should not be invoked directly. Return value of true prevents further message processing for handled hotkey events.

RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk)

Windows API function to register a global hotkey with the specified window handle, modifiers, and virtual key code.

Parameters

  • hWnd — Handle to the window that will receive hotkey messages.
  • id — Unique identifier for the hotkey registration.
  • fsModifiers — Modifier key combination (Ctrl, Alt, Shift, Win).
  • vk — Virtual key code for the main key.

Returns: True if the hotkey was successfully registered, false otherwise.

Remarks

Direct P/Invoke declaration for user32.dll RegisterHotKey function. Enables global hotkey registration that works system-wide regardless of application focus.

RegisterHotkeys()

Registers all configured hotkeys with Windows using the current configuration file settings.

Remarks

Primary registration method that loads hotkey configuration from JSON file and registers each hotkey with the Windows API. Handles configuration parsing, hotkey validation, and registration success/failure logging for comprehensive setup feedback.

Registration Process: 1. Load hotkey configuration from JSON file (auto-create if missing) 2. Parse each hotkey string into modifiers and key components 3. Register hotkey with Windows API using unique ID 4. Map successful registrations to command names for event routing 5. Log registration results for debugging and user feedback

Error Handling: • Registration failures logged but don't prevent other hotkeys from registering • Invalid hotkey formats logged with descriptive error messages • Conflicting hotkeys (already registered by other applications) handled gracefully

Hotkey IDs are automatically assigned using incremental counter to ensure uniqueness across all registrations within this manager instance.

TryParseHotkey(string hotkey, UInt32@ modifiers, UInt32@ key)

Parses a hotkey string into Windows API modifier and virtual key code components.

Parameters

  • hotkey — Hotkey string in format "Modifier+Modifier+Key" (e.g., "Ctrl+Shift+S").
  • modifiers — Output parameter containing combined modifier flags for Windows API.
  • key — Output parameter containing virtual key code for the main key.

Returns: True if parsing succeeded and key code was resolved, false otherwise.

Remarks

Hotkey parsing utility that converts human-readable hotkey strings into the numeric modifier and key code values required by the Windows RegisterHotKey API. Supports multiple modifiers and case-insensitive parsing for user convenience.

Supported Modifiers: • CTRL: 0x0002 (Control key) • ALT: 0x0001 (Alt key) • SHIFT: 0x0004 (Shift key) • WIN: 0x0008 (Windows key)

Key Code Resolution: Main key component is parsed using Enum.TryParse with the System.Windows.Forms.Keys enumeration, supporting all standard Windows virtual key codes including letters, numbers, function keys, and special keys.

Input Format: • Components separated by plus (+) character • Case-insensitive modifier names • Standard key names (A-Z, F1-F12, Esc, Space, etc.) • Multiple modifiers supported in any order

Parsing failures return false with zero values for both output parameters, allowing calling code to handle invalid configurations gracefully.

UnregisterAll()

Unregisters all previously registered hotkeys and clears internal tracking structures.

Remarks

Cleanup method that ensures proper resource disposal by unregistering all hotkeys with the Windows API and clearing internal tracking data structures. Essential for preventing resource leaks and ensuring hotkeys become available to other applications.

Cleanup Process: 1. Iterate through all registered hotkey IDs 2. Call Windows API UnregisterHotKey for each registration 3. Clear hotkey ID to name mapping dictionary 4. Log completion status for verification

Should be called during application shutdown or when hotkey manager is no longer needed. Failure to call this method may result in hotkeys remaining registered after application exit.

UnregisterHotKey(IntPtr hWnd, int id)

Windows API function to remove a previously registered global hotkey.

Parameters

  • hWnd — Handle to the window that owns the hotkey registration.
  • id — Unique identifier of the hotkey to unregister.

Returns: True if the hotkey was successfully unregistered, false otherwise.

Remarks

Direct P/Invoke declaration for user32.dll UnregisterHotKey function. Essential for proper resource cleanup during application shutdown.

HotkeysConfig

User-configurable hotkey mappings for TriggerManager with schema validation and atomic persistence.

Remarks

Centralizes access to the roaming configuration file that describes global hotkeys for TriggerManager. The helpers in this type resolve canonical Smrt.Config paths, hydrate defaults bundled with the app, validate payloads against the JSON schema, and persist updates atomically so the runtime never observes partially written configuration.

The configuration contract is consumed by TriggerManager.HotkeyManager to register Windows hotkeys and by pipeline tooling to hydrate default layouts during packaging.

Methods

LoadOrSeed()

Loads the hotkey mapping from disk, seeding defaults if missing.

Returns: User hotkey mapping dictionary.

Remarks

Ensures the caller always receives a valid configuration by creating directories, seeding bundled defaults when the user file is absent, and validating the resulting document against config/schema/hotkeys.schema.json. The method logs and falls back to the packaged defaults in-memory if any read or validation failure occurs.

Save(Collections.Generic.Dictionary map)

Saves the provided hotkey mapping to disk.

Parameters

  • map — The hotkey mapping dictionary to save.

Remarks

Validates the supplied map against the JSON schema before performing an atomic write with .tmp and .bak staging.

TryLoadDefaults()

Loads default hotkey mappings from disk or returns built-in defaults.

Returns: Default hotkey mapping dictionary.

Propertys

FilePath

Path to the user hotkeys config file (unified location).

Remarks

Resolved through SmrtHub.Config.ConfigPathResolver so all consumers share the same Operational Data Policy slug.

Program

Main entry point and application lifecycle manager for SmrtHub's TriggerManager desktop automation component.

Remarks

Program class orchestrates the initialization and execution of SmrtHub's TriggerManager core components: global hotkey registration, and action dispatching. The application runs as a background service with minimal UI footprint, using an invisible form to maintain the Windows message loop required for hotkey processing within the SmrtHub ecosystem. - Headless Operation: Runs entirely in background without visible interface - Global Hotkey Support: Registers system-wide keyboard shortcuts - Message Loop Management: Maintains Windows message processing for hotkey events - Resource Cleanup: Proper disposal of hotkey registrations on application exit

Application Architecture: • InvisibleForm: Hidden WinForms container for message loop and window handle • TriggerDispatcher: Central command routing and HTTP communication manager • HotkeyManager: Windows API integration for global hotkey registration

Execution Flow: 1. Enable Windows visual styles for consistent appearance 2. Create invisible form to provide window handle for hotkey registration 3. Initialize dispatcher and hotkey manager components 4. Register all configured global hotkeys with Windows 5. Start application message loop (blocks until termination) 6. Clean up hotkey registrations on exit

Threading Model: • Single-threaded apartment (STA) for Windows Forms compatibility • Main thread dedicated to message loop processing • Asynchronous HTTP operations handle action dispatching without blocking

Updates: • 2025-07-13: Added comprehensive XML documentation and standalone positioning • 2025-06-27: Initial implementation with headless operation design

Methods

Main()

Application entry point that initializes TriggerManager components and starts the message loop.

Remarks

Main method configures Single-Threaded Apartment (STA) mode required for Windows Forms and hotkey processing, then orchestrates the initialization sequence for all TriggerManager components. The method blocks on Application.Run() until the application is terminated.

Initialization Sequence: 1. Enable Windows visual styles for consistent UI rendering 2. Configure text rendering compatibility settings 3. Create invisible form container for Windows API interactions 4. Initialize dispatcher and hotkey manager with action mappings 5. Register all configured global hotkeys with Windows 6. Start Windows message loop (blocking operation) 7. Clean up hotkey registrations on application termination

The invisible form provides the necessary window handle for hotkey registration while maintaining completely headless operation from the user perspective.

TriggerDispatcher

Primary command coordination hub for SmrtHub's TriggerManager that manages hotkey action mappings and delegates execution to ActionDispatcher.

Remarks

TriggerDispatcher is the bridge between the WinForms hotkey loop and the HTTP dispatch layer. It exposes the authoritative hotkey-to-action map used by TriggerManager.HotkeyManager, and each action simply delegates to TriggerManager.ActionDispatcher so routing logic stays isolated. By keeping the responsibilities narrow the component remains easy to audit and aligns with SmrtHub's documentation and logging policies. - Command Registry: Maintains the canonical list of shipped hotkey identifiers. - Delegation Pattern: Wraps each identifier with a lambda that forwards to ActionDispatcher. - Unified Telemetry: Relies on SmrtHub.Logging (via the dispatcher) instead of creating directories or custom files. - Extensibility: Adds new routes by updating a single dictionary, keeping code+docs in sync.

Architectural Placement: TriggerManager's stack is HotkeyManagerTriggerDispatcherActionDispatcher, giving the WinForms surface a simple action dictionary while centralizing HTTP coordination and diagnostics.

Fields

dispatcher

ActionDispatcher instance responsible for HTTP communication and routing logic.

Remarks

Initialized during construction and used for all command execution delegation. Encapsulates HTTP communication details and routing decisions.

Methods

GetHotkeyActions()

Provides a dictionary mapping hotkey command names to executable actions for hotkey registration.

Returns: Dictionary where keys are hotkey command names and values are parameterless Action delegates.

Remarks

Factory method that creates the complete action mapping dictionary required by HotkeyManager for global hotkey registration. Each dictionary entry associates a string command name with a lambda expression that delegates to the ActionDispatcher.

Supported Commands: • HOTKEY_SMRTSAVE: File and content persistence operations • HOTKEY_SMRTSEARCH: Intelligent web content processing and extraction • HUBWINDOW_TOGGLE: Cycle HubWindow top-panel state (local IPC) • HOTKEY_EXTRACT_TEXT: UI-free local OCR (clipboard → text) • HOTKEY_EXTRACT_STRUCTURED_TEXT: UI-free local OCR (clipboard → structured JSON) • HOTKEY_EXTRACT_STRUCTURED_TEXT_FROM_DOCUMENTS: UI-light local structured OCR (file picker → JSON)

Delegation Pattern: Each action is implemented as a lambda that calls dispatcher.Dispatch() with the appropriate command name, providing clean separation between command mapping and execution.

The returned dictionary is used directly by HotkeyManager for Windows API hotkey registration, creating the link between keyboard events and command execution.

TriggerDispatcher()

Initializes a new TriggerDispatcher instance with logging infrastructure and action dispatcher.

Remarks

Constructor currently just instantiates the underlying TriggerManager.ActionDispatcher. Historical ad-hoc log directory creation was removed in favor of SmrtHub.Logging's centralized sinks, so no filesystem mutations occur here.

Namespace: TriggerManager.Program

InvisibleForm

Invisible Windows Forms container that provides window handle for hotkey registration while maintaining headless operation.

Remarks

InvisibleForm serves as a lightweight Windows Forms host that enables TriggerManager to register global hotkeys through the Windows API while maintaining completely invisible operation. The form is configured to never appear in the taskbar or user interface. - Invisible Operation: Hidden immediately on load with no taskbar presence - Minimal UI Footprint: Borderless, minimized form with no visual elements - Windows API Host: Provides necessary window handle for hotkey registration - Event Processing: Maintains message loop for hotkey event reception

Form Configuration: • ShowInTaskbar: false (no taskbar button) • WindowState: Minimized (not visible on desktop) • FormBorderStyle: None (no window frame) • Load Event: Immediately hides form after initialization

This approach enables global hotkey functionality without requiring a visible application window, allowing TriggerManager to operate as a true background service.

Methods

InvisibleForm()

Initializes a new InvisibleForm instance with configuration for completely hidden operation.

Remarks

Constructor configures the form to operate invisibly while providing the necessary Windows API integration points for global hotkey registration. The form is designed to have zero visual impact on the user experience.

Configuration Details: • ShowInTaskbar = false: Prevents taskbar button creation • WindowState = Minimized: Ensures form starts in hidden state • FormBorderStyle = None: Removes all window decorations • Load Event Handler: Immediately hides form after Windows creation

The Load event handler ensures the form is hidden even if Windows attempts to display it during the initialization process.