|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +from streamdeck.event_handlers.actions import Action |
| 6 | + |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from collections.abc import Generator |
| 10 | + |
| 11 | + from streamdeck.event_handlers.protocol import EventHandlerFunc, SupportsEventHandlers |
| 12 | + from streamdeck.types import ActionUUIDStr, EventNameStr |
| 13 | + |
| 14 | + |
| 15 | +class HandlersRegistry: |
| 16 | + """Manages the registration and retrieval of actions and their event handlers.""" |
| 17 | + _plugin_actions: list[SupportsEventHandlers] |
| 18 | + """List of registered actions.""" |
| 19 | + |
| 20 | + def __init__(self) -> None: |
| 21 | + """Initialize an HandlersRegistry instance.""" |
| 22 | + self._plugin_actions = [] |
| 23 | + |
| 24 | + def register(self, action: SupportsEventHandlers) -> None: |
| 25 | + """Register an action with the registry. |
| 26 | +
|
| 27 | + Args: |
| 28 | + action (Action): The action to register. |
| 29 | + """ |
| 30 | + self._plugin_actions.append(action) |
| 31 | + |
| 32 | + def get_event_handlers(self, event_name: EventNameStr, event_action_uuid: ActionUUIDStr | None = None) -> Generator[EventHandlerFunc, None, None]: |
| 33 | + """Get all event handlers for a specific event from all registered actions. |
| 34 | +
|
| 35 | + Args: |
| 36 | + event_name (EventName): The name of the event to retrieve handlers for. |
| 37 | + event_action_uuid (str | None): The action UUID to get handlers for. |
| 38 | + If None (i.e., the event is not action-specific), get all handlers for the event. |
| 39 | +
|
| 40 | + Yields: |
| 41 | + EventHandlerFunc: The event handler functions for the specified event. |
| 42 | + """ |
| 43 | + for action in self._plugin_actions: |
| 44 | + # If the event is action-specific (i.e is not a GlobalAction and has a UUID attribute), |
| 45 | + # only get handlers for that action, as we don't want to trigger |
| 46 | + # and pass this event to handlers for other actions. |
| 47 | + if event_action_uuid is not None and (isinstance(action, Action) and action.uuid != event_action_uuid): |
| 48 | + continue |
| 49 | + |
| 50 | + yield from action.get_event_handlers(event_name) |
0 commit comments