| 1 |
from typing import TYPE_CHECKING, Callable, Generic, Optional, TypeVar, Union |
| 2 |
|
| 3 |
from pydantic import Field, field_validator |
| 4 |
|
| 5 |
from ._command_rule import CommandRule |
| 6 |
from ._keybinding_rule import KeyBindingRule |
| 7 |
from ._menu_rule import MenuRule |
| 8 |
from ._utils import _validate_python_name |
| 9 |
|
| 10 |
# maintain runtime compatibility with older typing_extensions |
| 11 |
if TYPE_CHECKING: |
| 12 |
from typing_extensions import ParamSpec |
| 13 |
|
| 14 |
P = ParamSpec("P") |
| 15 |
else: |
| 16 |
try: |
| 17 |
from typing_extensions import ParamSpec |
| 18 |
|
| 19 |
P = ParamSpec("P") |
| 20 |
except ImportError: |
| 21 |
P = TypeVar("P") |
| 22 |
R = TypeVar("R") |
| 23 |
|
| 24 |
|
| 25 |
class Action(CommandRule, Generic[P, R]): |
| 26 |
"""An Action is a callable object with menu placement, keybindings, and metadata. |
| 27 |
|
| 28 |
This is the "complete" representation of a command. Including a pointer to the |
| 29 |
actual callable object, as well as any additional menu and keybinding rules. |
| 30 |
Most commands and menu items will be represented by Actions, and registered using |
| 31 |
`register_action`. |
| 32 |
""" |
| 33 |
|
| 34 |
callback: Union[Callable[P, R], str] = Field( |
| 35 |
..., |
| 36 |
description="A function to call when the associated command id is executed. " |
| 37 |
"If a string is provided, it must be a fully qualified name to a callable " |
| 38 |
"python object. This usually takes the form of " |
| 39 |
"`{obj.__module__}:{obj.__qualname__}` " |
| 40 |
"(e.g. `my_package.a_module:some_function`)", |
| 41 |
) |
| 42 |
menus: Optional[list[MenuRule]] = Field( |
| 43 |
default=None, |
| 44 |
description="(Optional) Menus to which this action should be added. Note that " |
| 45 |
"menu items in the sequence may be supplied as a plain string, which will " |
| 46 |
"be converted to a `MenuRule` with the string as the `id` field.", |
| 47 |
) |
| 48 |
keybindings: Optional[list[KeyBindingRule]] = Field( |
| 49 |
default=None, |
| 50 |
description="(Optional) Default keybinding(s) that will trigger this command.", |
| 51 |
) |
| 52 |
palette: bool = Field( |
| 53 |
default=True, |
| 54 |
description="Whether to add this command to the global Command Palette " |
| 55 |
"during registration.", |
| 56 |
) |
| 57 |
|
| 58 |
@field_validator("callback") |
| 59 |
def _validate_callback(callback: object) -> Union[Callable, str]: |
| 60 |
"""Assert that `callback` is a callable or valid fully qualified name.""" |
| 61 |
if callable(callback): |
| 62 |
return callback |
| 63 |
elif isinstance(callback, str): |
| 64 |
return _validate_python_name(str(callback)) |
| 65 |
raise TypeError("callback must be a callable or a string") # pragma: no cover |