Debian Codegraph @

src/app_model/registries/_commands_reg.py

raw
1 from __future__ import annotations
2
3 from concurrent.futures import Future, ThreadPoolExecutor
4 from typing import TYPE_CHECKING, Any, Callable, Generic, TypeVar, cast
5
6 from in_n_out import Store
7 from psygnal import Signal
8
9 # maintain runtime compatibility with older typing_extensions
10 if TYPE_CHECKING:
11 from collections.abc import Iterator
12
13 from typing_extensions import ParamSpec
14
15 from app_model.types import Action, DisposeCallable
16
17 P = ParamSpec("P")
18 else:
19 try:
20 from typing_extensions import ParamSpec
21
22 P = ParamSpec("P")
23 except ImportError:
24 P = TypeVar("P")
25
26
27 R = TypeVar("R")
28
29
30 class RegisteredCommand(Generic[P, R]):
31 """Small object to represent a command in the CommandsRegistry.
32
33 Used internally by the CommandsRegistry.
34
35 This helper class allows us to cache the dependency-injected variant of the
36 command, so that type resolution and dependency injection is performed only
37 once.
38 """
39
40 __slots__ = (
41 "_initialized",
42 "_injected_callback",
43 "_injection_store",
44 "_resolved_callback",
45 "callback",
46 "id",
47 "title",
48 )
49
50 def __init__(
51 self,
52 id: str,
53 callback: Callable[P, R] | str,
54 title: str,
55 store: Store | None = None,
56 ) -> None:
57 self.id = id
58 self.callback = callback
59 self.title = title
60 self._injection_store: Store = store or Store.get_store()
61 self._resolved_callback = callback if callable(callback) else None
62 self._injected_callback: Callable[P, R] | None = None
63 self._initialized = True
64
65 def __setattr__(self, name: str, value: Any) -> None:
66 """Object is immutable after initialization."""
67 if getattr(self, "_initialized", False):
68 raise AttributeError("RegisteredCommand object is immutable.")
69 super().__setattr__(name, value)
70
71 @property
72 def resolved_callback(self) -> Callable[P, R]:
73 """Return the resolved command callback.
74
75 This property is cached, so the callback types are only resolved once.
76 """
77 if self._resolved_callback is None:
78 from app_model.types._utils import import_python_name
79
80 try:
81 cb = import_python_name(str(self.callback))
82 except ImportError as e:
83 object.__setattr__(self, "_resolved_callback", lambda *a, **k: None)
84 raise type(e)(
85 f"Command pointer {self.callback!r} registered for Command "
86 f"{self.id!r} was not importable: {e}"
87 ) from e
88
89 if not callable(cb):
90 # don't try to import again, just create a no-op
91 object.__setattr__(self, "_resolved_callback", lambda *a, **k: None)
92 raise TypeError(
93 f"Command pointer {self.callback!r} registered for Command "
94 f"{self.id!r} did not resolve to a callble object."
95 )
96 object.__setattr__(self, "_resolved_callback", cb)
97 return cast("Callable[P, R]", self._resolved_callback)
98
99 @property
100 def run_injected(self) -> Callable[P, R]:
101 """Return the command callback with dependencies injected.
102
103 This property is cached, so the injected version is only created once.
104 """
105 if self._injected_callback is None:
106 cb = self._injection_store.inject(self.resolved_callback, processors=True)
107 object.__setattr__(self, "_injected_callback", cb)
108 return cast("Callable[P, R]", self._injected_callback)
109
110
111 class CommandsRegistry:
112 """Registry for commands (callable objects)."""
113
114 registered = Signal(str)
115
116 def __init__(
117 self,
118 injection_store: Store | None = None,
119 raise_synchronous_exceptions: bool = False,
120 ) -> None:
121 self._commands: dict[str, RegisteredCommand] = {}
122 self._injection_store = injection_store
123 self._raise_synchronous_exceptions = raise_synchronous_exceptions
124
125 def register_action(self, action: Action) -> DisposeCallable:
126 """Register an Action object.
127
128 This is a convenience method that registers the action's callback
129 with the action's ID and title using `register_command`.
130
131 Parameters
132 ----------
133 action: Action
134 Action to register
135
136 Returns
137 -------
138 DisposeCallable
139 A function that can be called to unregister the action.
140 """
141 return self.register_command(action.id, action.callback, action.title)
142
143 def register_command(
144 self, id: str, callback: Callable[P, R] | str, title: str
145 ) -> DisposeCallable:
146 """Register a callable as the handler for command `id`.
147
148 Parameters
149 ----------
150 id : CommandId
151 Command identifier
152 callback : Callable
153 Callable to be called when the command is executed
154 title : str
155 Title for the command.
156
157 Returns
158 -------
159 DisposeCallable
160 A function that can be called to unregister the command.
161 """
162 if id in self._commands:
163 raise ValueError(
164 f"Command {id!r} already registered with callback "
165 f"{self._commands[id].callback!r} (new callback: {callback!r})"
166 )
167
168 cmd = RegisteredCommand(id, callback, title, self._injection_store)
169 self._commands[id] = cmd
170
171 def _dispose() -> None:
172 self._commands.pop(id, None)
173
174 self.registered.emit(id)
175 return _dispose
176
177 def __iter__(self) -> Iterator[tuple[str, RegisteredCommand]]:
178 yield from self._commands.items()
179
180 def __len__(self) -> int:
181 return len(self._commands)
182
183 def __contains__(self, id: str) -> bool:
184 return id in self._commands
185
186 def __repr__(self) -> str:
187 name = self.__class__.__name__
188 return f"<{name} at {hex(id(self))} ({len(self._commands)} commands)>"
189
190 def __getitem__(self, id: str) -> RegisteredCommand:
191 """Retrieve commands registered under a given ID."""
192 if id not in self._commands:
193 raise KeyError(f"Command {id!r} not registered")
194 return self._commands[id]
195
196 def execute_command(
197 self,
198 id: str,
199 *args: Any,
200 execute_asynchronously: bool = False,
201 **kwargs: Any,
202 ) -> Future:
203 """Execute a registered command.
204
205 Parameters
206 ----------
207 id : CommandId
208 ID of the command to execute
209 *args: Any
210 Positional arguments to pass to the command
211 execute_asynchronously : bool
212 Whether to execute the command asynchronously in a thread,
213 by default `False`. Note that *regardless* of this setting,
214 the return value will implement the `Future` API (so it's necessary)
215 to call `result()` on the returned object. Eventually, this will
216 default to True, but we need to solve `ensure_main_thread` Qt threading
217 issues first
218 **kwargs: Any
219 Keyword arguments to pass to the command
220
221 Returns
222 -------
223 Future: concurrent.futures.Future
224 Future object containing the result of the command
225
226 Raises
227 ------
228 KeyError
229 If the command is not registered or has no callbacks.
230 """
231 try:
232 cmd = self[id].run_injected
233 except KeyError as e:
234 raise KeyError(f"Command {id!r} not registered") from e # pragma: no cover
235
236 if execute_asynchronously:
237 with ThreadPoolExecutor() as executor:
238 return executor.submit(cmd, *args, **kwargs)
239
240 future: Future = Future()
241 try:
242 future.set_result(cmd(*args, **kwargs))
243 except Exception as e:
244 if self._raise_synchronous_exceptions:
245 # note, the caller of this function can also achieve this by
246 # calling `future.result()` on the returned future object.
247 raise e
248 future.set_exception(e)
249
250 return future
251
252 def __str__(self) -> str:
253 lines = [f"{id_!r:<32} -> {cmd.title!r}" for id_, cmd in self]
254 return "\n".join(lines)