| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import os |
| 5 |
import sys |
| 6 |
from collections.abc import Iterable, MutableMapping |
| 7 |
from types import MappingProxyType |
| 8 |
from typing import ( |
| 9 |
TYPE_CHECKING, |
| 10 |
Any, |
| 11 |
ClassVar, |
| 12 |
Literal, |
| 13 |
Optional, |
| 14 |
overload, |
| 15 |
) |
| 16 |
|
| 17 |
import in_n_out as ino |
| 18 |
from psygnal import Signal |
| 19 |
|
| 20 |
from .expressions import Context, app_model_context |
| 21 |
from .registries import ( |
| 22 |
CommandsRegistry, |
| 23 |
KeyBindingsRegistry, |
| 24 |
MenusRegistry, |
| 25 |
register_action, |
| 26 |
) |
| 27 |
from .types import ( |
| 28 |
Action, |
| 29 |
) |
| 30 |
|
| 31 |
if TYPE_CHECKING: |
| 32 |
from typing import Callable |
| 33 |
|
| 34 |
from .expressions import Expr |
| 35 |
from .registries._register import CommandDecorator |
| 36 |
from .types import ( |
| 37 |
DisposeCallable, |
| 38 |
IconOrDict, |
| 39 |
KeyBindingRuleOrDict, |
| 40 |
MenuRuleOrDict, |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
class Application: |
| 45 |
"""Full application model. |
| 46 |
|
| 47 |
This is the top level object that comprises all of the registries, and other |
| 48 |
app-namespace specific objects. |
| 49 |
|
| 50 |
Parameters |
| 51 |
---------- |
| 52 |
name : str |
| 53 |
A name for this application. |
| 54 |
raise_synchronous_exceptions : bool |
| 55 |
Whether to raise exceptions that occur while executing commands synchronously, |
| 56 |
by default False. This is settable after instantiation, and can also be |
| 57 |
controlled per execution by calling `result.result()` on the future object |
| 58 |
returned from the `execute_command` method. |
| 59 |
commands_reg_class : Type[CommandsRegistry] |
| 60 |
(Optionally) override the class to use when creating the CommandsRegistry |
| 61 |
menus_reg_class : Type[MenusRegistry] |
| 62 |
(Optionally) override the class to use when creating the MenusRegistry |
| 63 |
keybindings_reg_class : Type[KeyBindingsRegistry] |
| 64 |
(Optionally) override the class to use when creating the KeyBindingsRegistry |
| 65 |
injection_store_class : Type[ino.Store] |
| 66 |
(Optionally) override the class to use when creating the injection Store |
| 67 |
context : Context | MutableMapping | None |
| 68 |
(Optionally) provide a context to use for this application. If a |
| 69 |
`MutableMapping` is provided, it will be used to create a `Context` instance. |
| 70 |
If `None` (the default), a new `Context` instance will be created. |
| 71 |
|
| 72 |
Attributes |
| 73 |
---------- |
| 74 |
commands : CommandsRegistry |
| 75 |
The Commands Registry for this application. |
| 76 |
menus : MenusRegistry |
| 77 |
The Menus Registry for this application. |
| 78 |
keybindings : KeyBindingsRegistry |
| 79 |
The KeyBindings Registry for this application. |
| 80 |
injection_store : in_n_out.Store |
| 81 |
The Injection Store for this application. |
| 82 |
context : Context |
| 83 |
The Context for this application. |
| 84 |
""" |
| 85 |
|
| 86 |
destroyed = Signal(str) |
| 87 |
_instances: ClassVar[dict[str, Application]] = {} |
| 88 |
|
| 89 |
def __init__( |
| 90 |
self, |
| 91 |
name: str, |
| 92 |
*, |
| 93 |
raise_synchronous_exceptions: bool = False, |
| 94 |
commands_reg_class: type[CommandsRegistry] = CommandsRegistry, |
| 95 |
menus_reg_class: type[MenusRegistry] = MenusRegistry, |
| 96 |
keybindings_reg_class: type[KeyBindingsRegistry] = KeyBindingsRegistry, |
| 97 |
injection_store_class: type[ino.Store] = ino.Store, |
| 98 |
context: Context | MutableMapping | None = None, |
| 99 |
) -> None: |
| 100 |
self._name = name |
| 101 |
if name in Application._instances: |
| 102 |
raise ValueError( |
| 103 |
f"Application {name!r} already exists. Retrieve it with " |
| 104 |
f"`Application.get_or_create({name!r})`." |
| 105 |
) |
| 106 |
Application._instances[name] = self |
| 107 |
|
| 108 |
if context is None: |
| 109 |
context = Context() |
| 110 |
elif isinstance(context, MutableMapping): |
| 111 |
context = Context(context) |
| 112 |
if not isinstance(context, Context): |
| 113 |
raise TypeError( |
| 114 |
f"context must be a Context or MutableMapping, got {type(context)}" |
| 115 |
) |
| 116 |
self._context = context |
| 117 |
self._context.update(app_model_context()) |
| 118 |
|
| 119 |
self._context["is_linux"] = sys.platform.startswith("linux") |
| 120 |
self._context["is_mac"] = sys.platform == "darwin" |
| 121 |
self._context["is_windows"] = os.name == "nt" |
| 122 |
|
| 123 |
self._injection_store = injection_store_class.create(name) |
| 124 |
self._commands = commands_reg_class( |
| 125 |
self.injection_store, |
| 126 |
raise_synchronous_exceptions=raise_synchronous_exceptions, |
| 127 |
) |
| 128 |
self._menus = menus_reg_class() |
| 129 |
self._keybindings = keybindings_reg_class() |
| 130 |
|
| 131 |
self.injection_store.on_unannotated_required_args = "ignore" |
| 132 |
|
| 133 |
self._registered_actions: dict[str, Action] = {} |
| 134 |
self._disposers: list[tuple[str, DisposeCallable]] = [] |
| 135 |
|
| 136 |
@property |
| 137 |
def raise_synchronous_exceptions(self) -> bool: |
| 138 |
"""Whether to raise synchronous exceptions.""" |
| 139 |
return self._commands._raise_synchronous_exceptions |
| 140 |
|
| 141 |
@raise_synchronous_exceptions.setter |
| 142 |
def raise_synchronous_exceptions(self, value: bool) -> None: |
| 143 |
self._commands._raise_synchronous_exceptions = value |
| 144 |
|
| 145 |
@property |
| 146 |
def commands(self) -> CommandsRegistry: |
| 147 |
"""Return the [`CommandsRegistry`][app_model.registries.CommandsRegistry].""" |
| 148 |
return self._commands |
| 149 |
|
| 150 |
@property |
| 151 |
def menus(self) -> MenusRegistry: |
| 152 |
"""Return the [`MenusRegistry`][app_model.registries.MenusRegistry].""" |
| 153 |
return self._menus |
| 154 |
|
| 155 |
@property |
| 156 |
def keybindings(self) -> KeyBindingsRegistry: |
| 157 |
"""Return the [`KeyBindingsRegistry`][app_model.registries.KeyBindingsRegistry].""" # noqa E501 |
| 158 |
return self._keybindings |
| 159 |
|
| 160 |
@property |
| 161 |
def injection_store(self) -> ino.Store: |
| 162 |
"""Return the `in_n_out.Store` instance associated with this `Application`.""" |
| 163 |
return self._injection_store |
| 164 |
|
| 165 |
@property |
| 166 |
def context(self) -> Context: |
| 167 |
"""Return the [`Context`][app_model.expressions.Context] for this application.""" # noqa E501 |
| 168 |
return self._context |
| 169 |
|
| 170 |
@classmethod |
| 171 |
def get_or_create(cls, name: str) -> Application: |
| 172 |
"""Get app named `name` or create and return a new one if it doesn't exist.""" |
| 173 |
return cls._instances[name] if name in cls._instances else cls(name) |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def get_app(cls, name: str) -> Optional[Application]: |
| 177 |
"""Return app named `name` or None if it doesn't exist.""" |
| 178 |
return cls._instances.get(name) |
| 179 |
|
| 180 |
@classmethod |
| 181 |
def destroy(cls, name: str) -> None: |
| 182 |
"""Destroy the `Application` named `name`. |
| 183 |
|
| 184 |
This will call [`dispose()`][app_model.Application.dispose], destroy the |
| 185 |
injection store, and remove the application from the list of stored |
| 186 |
application names (allowing the name to be reused). |
| 187 |
""" |
| 188 |
if name not in cls._instances: |
| 189 |
return # pragma: no cover |
| 190 |
app = cls._instances.pop(name) |
| 191 |
app.dispose() |
| 192 |
app.injection_store.destroy(name) |
| 193 |
app.destroyed.emit(app.name) |
| 194 |
|
| 195 |
@property |
| 196 |
def name(self) -> str: |
| 197 |
"""Return the name of this `Application`.""" |
| 198 |
return self._name |
| 199 |
|
| 200 |
def __repr__(self) -> str: |
| 201 |
return f"Application({self.name!r})" |
| 202 |
|
| 203 |
def dispose(self) -> None: |
| 204 |
"""Dispose this `Application`. |
| 205 |
|
| 206 |
This calls all disposers functions (clearing all registries). |
| 207 |
""" |
| 208 |
while self._disposers: |
| 209 |
with contextlib.suppress(Exception): |
| 210 |
self._disposers.pop()[1]() |
| 211 |
|
| 212 |
@overload |
| 213 |
def register_action(self, action: Action) -> DisposeCallable: ... |
| 214 |
|
| 215 |
@overload |
| 216 |
def register_action( |
| 217 |
self, |
| 218 |
action: str, |
| 219 |
title: str, |
| 220 |
*, |
| 221 |
callback: Literal[None] = ..., |
| 222 |
category: str | None = ..., |
| 223 |
tooltip: str | None = ..., |
| 224 |
icon: IconOrDict | None = ..., |
| 225 |
enablement: Expr | None = ..., |
| 226 |
menus: list[MenuRuleOrDict] | None = ..., |
| 227 |
keybindings: list[KeyBindingRuleOrDict] | None = ..., |
| 228 |
palette: bool = True, |
| 229 |
) -> CommandDecorator: ... |
| 230 |
|
| 231 |
@overload |
| 232 |
def register_action( |
| 233 |
self, |
| 234 |
action: str, |
| 235 |
title: str, |
| 236 |
*, |
| 237 |
callback: Callable[..., Any], |
| 238 |
category: str | None = ..., |
| 239 |
tooltip: str | None = ..., |
| 240 |
icon: IconOrDict | None = ..., |
| 241 |
enablement: Expr | None = ..., |
| 242 |
menus: list[MenuRuleOrDict] | None = ..., |
| 243 |
keybindings: list[KeyBindingRuleOrDict] | None = ..., |
| 244 |
palette: bool = True, |
| 245 |
) -> DisposeCallable: ... |
| 246 |
|
| 247 |
def register_action( |
| 248 |
self, |
| 249 |
action: str | Action, |
| 250 |
title: str | None = None, |
| 251 |
*, |
| 252 |
callback: Callable[..., Any] | None = None, |
| 253 |
category: str | None = None, |
| 254 |
tooltip: str | None = None, |
| 255 |
icon: IconOrDict | None = None, |
| 256 |
enablement: Expr | None = None, |
| 257 |
menus: list[MenuRuleOrDict] | None = None, |
| 258 |
keybindings: list[KeyBindingRuleOrDict] | None = None, |
| 259 |
palette: bool = True, |
| 260 |
) -> CommandDecorator | DisposeCallable: |
| 261 |
"""Register [`Action`][app_model.Action] instance with this application. |
| 262 |
|
| 263 |
An [`Action`][app_model.Action] is the complete representation of a command, |
| 264 |
including information about where and whether it appears in menus and optional |
| 265 |
keybinding rules. |
| 266 |
|
| 267 |
See [`register_action`][app_model.register_action] for complete |
| 268 |
details on this function. |
| 269 |
""" |
| 270 |
if isinstance(action, Action): |
| 271 |
return register_action(self, action) |
| 272 |
|
| 273 |
return register_action( |
| 274 |
self, |
| 275 |
id_or_action=action, |
| 276 |
title=title, # type: ignore |
| 277 |
callback=callback, # type: ignore |
| 278 |
category=category, |
| 279 |
tooltip=tooltip, |
| 280 |
icon=icon, |
| 281 |
enablement=enablement, |
| 282 |
menus=menus, |
| 283 |
keybindings=keybindings, |
| 284 |
palette=palette, |
| 285 |
) |
| 286 |
|
| 287 |
def register_actions(self, actions: Iterable[Action]) -> DisposeCallable: |
| 288 |
"""Register multiple [`Action`][app_model.Action] instances with this app. |
| 289 |
|
| 290 |
Returns a function that may be called to undo the registration of `actions`. |
| 291 |
""" |
| 292 |
d = [self.register_action(action) for action in actions] |
| 293 |
|
| 294 |
def _dispose() -> None: |
| 295 |
while d: |
| 296 |
d.pop()() |
| 297 |
|
| 298 |
return _dispose |
| 299 |
|
| 300 |
@property |
| 301 |
def registered_actions(self) -> MappingProxyType[str, Action]: |
| 302 |
"""Return a Mapping of id->Action object for all registered actions. |
| 303 |
|
| 304 |
Note that this only includes actions that were registered using |
| 305 |
`register_action`. Commands registered directly via |
| 306 |
`Application.commands.register_action` will not be included in this mapping. |
| 307 |
""" |
| 308 |
return MappingProxyType(self._registered_actions) |
| 309 |
|
| 310 |
def _register_action_obj(self, action: Action) -> DisposeCallable: |
| 311 |
"""Register an Action object. Return a function that unregisters the action. |
| 312 |
|
| 313 |
Helper for `register_action()`. |
| 314 |
""" |
| 315 |
# register commands |
| 316 |
disposers = [self.commands.register_action(action)] |
| 317 |
# register keybindings |
| 318 |
if dk := self.keybindings.register_action_keybindings(action): |
| 319 |
disposers.append(dk) |
| 320 |
# register menus |
| 321 |
if dm := self.menus.append_action_menus(action): |
| 322 |
disposers.append(dm) |
| 323 |
|
| 324 |
# remember the action object as a whole. |
| 325 |
# note that commands.register_action will have raised an exception |
| 326 |
# if the action.id is already registered, so we can assume that |
| 327 |
# the keys are unique. |
| 328 |
self._registered_actions[action.id] = action |
| 329 |
|
| 330 |
# create a function that will dispose of all the disposers |
| 331 |
def _dispose() -> None: |
| 332 |
self._registered_actions.pop(action.id, None) |
| 333 |
for d in disposers: |
| 334 |
d() |
| 335 |
|
| 336 |
self._disposers.append((action.id, _dispose)) |
| 337 |
return _dispose |