| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from bisect import insort_left |
| 4 |
from collections import defaultdict |
| 5 |
from typing import TYPE_CHECKING, Callable, NamedTuple |
| 6 |
|
| 7 |
from psygnal import Signal |
| 8 |
|
| 9 |
from app_model.types import KeyBinding |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from collections.abc import Iterable, Iterator, Mapping |
| 13 |
from typing import TypeVar |
| 14 |
|
| 15 |
from app_model import expressions |
| 16 |
from app_model.types import ( |
| 17 |
Action, |
| 18 |
DisposeCallable, |
| 19 |
KeyBindingRule, |
| 20 |
KeyBindingSource, |
| 21 |
) |
| 22 |
|
| 23 |
CommandDecorator = Callable[[Callable], Callable] |
| 24 |
CommandCallable = TypeVar("CommandCallable", bound=Callable) |
| 25 |
|
| 26 |
|
| 27 |
class _RegisteredKeyBinding(NamedTuple): |
| 28 |
"""Internal object representing a fully registered keybinding.""" |
| 29 |
|
| 30 |
keybinding: KeyBinding # the keycode to bind to |
| 31 |
command_id: str # the command to run |
| 32 |
weight: int # the weight of the binding, for prioritization |
| 33 |
source: KeyBindingSource # who defined the binding, for prioritization |
| 34 |
when: expressions.Expr | None = None # condition to enable keybinding |
| 35 |
|
| 36 |
def __gt__(self, other: object) -> bool: |
| 37 |
if not isinstance(other, _RegisteredKeyBinding): |
| 38 |
return NotImplemented |
| 39 |
return (self.source, self.weight) > (other.source, other.weight) |
| 40 |
|
| 41 |
def __lt__(self, other: object) -> bool: |
| 42 |
if not isinstance(other, _RegisteredKeyBinding): |
| 43 |
return NotImplemented |
| 44 |
return (self.source, self.weight) < (other.source, other.weight) |
| 45 |
|
| 46 |
def __eq__(self, other: object) -> bool: |
| 47 |
if not isinstance(other, _RegisteredKeyBinding): |
| 48 |
return NotImplemented |
| 49 |
return (self.source, self.weight) == (other.source, other.weight) |
| 50 |
|
| 51 |
|
| 52 |
class KeyBindingsRegistry: |
| 53 |
"""Registry for keybindings. |
| 54 |
|
| 55 |
Attributes |
| 56 |
---------- |
| 57 |
filter_keybinding : Callable[[KeyBinding], str] | None |
| 58 |
Optional function for applying additional `KeyBinding` filtering. |
| 59 |
Callable should accept a `KeyBinding` object and return an error message |
| 60 |
(`str`) if `KeyBinding` is rejected, or empty string otherwise. |
| 61 |
""" |
| 62 |
|
| 63 |
registered = Signal() |
| 64 |
unregistered = Signal() |
| 65 |
|
| 66 |
def __init__(self) -> None: |
| 67 |
self._keymap = defaultdict[int, list[_RegisteredKeyBinding]](list) |
| 68 |
self._filter_keybinding: Callable[[KeyBinding], str] | None = None |
| 69 |
|
| 70 |
@property |
| 71 |
def _keybindings(self) -> Iterable[_RegisteredKeyBinding]: |
| 72 |
return (entry for entries in self._keymap.values() for entry in entries) |
| 73 |
|
| 74 |
@property |
| 75 |
def filter_keybinding(self) -> Callable[[KeyBinding], str] | None: |
| 76 |
"""Return the `filter_keybinding`.""" |
| 77 |
return self._filter_keybinding |
| 78 |
|
| 79 |
@filter_keybinding.setter |
| 80 |
def filter_keybinding(self, value: Callable[[KeyBinding], str] | None) -> None: |
| 81 |
if callable(value) or value is None: |
| 82 |
self._filter_keybinding = value |
| 83 |
else: |
| 84 |
raise TypeError("'filter_keybinding' must be a callable or None") |
| 85 |
|
| 86 |
def register_action_keybindings(self, action: Action) -> DisposeCallable | None: |
| 87 |
"""Register all keybindings declared in `action.keybindings`. |
| 88 |
|
| 89 |
Parameters |
| 90 |
---------- |
| 91 |
action : Action |
| 92 |
The action to register keybindings for. |
| 93 |
|
| 94 |
Returns |
| 95 |
------- |
| 96 |
DisposeCallable | None |
| 97 |
A function that can be called to unregister the keybindings. If no |
| 98 |
keybindings were registered, returns None. |
| 99 |
""" |
| 100 |
if not (keybindings := action.keybindings): |
| 101 |
return None |
| 102 |
|
| 103 |
disposers: list[Callable[[], None]] = [] |
| 104 |
msg: list[str] = [] |
| 105 |
for keyb in keybindings: |
| 106 |
if action.enablement is not None: |
| 107 |
kwargs = keyb.model_dump() |
| 108 |
kwargs["when"] = ( |
| 109 |
action.enablement |
| 110 |
if keyb.when is None |
| 111 |
else action.enablement | keyb.when |
| 112 |
) |
| 113 |
_keyb = type(keyb)(**kwargs) |
| 114 |
else: |
| 115 |
_keyb = keyb |
| 116 |
|
| 117 |
try: |
| 118 |
if d := self.register_keybinding_rule(action.id, _keyb): |
| 119 |
disposers.append(d) |
| 120 |
except ValueError as e: |
| 121 |
msg.append(str(e)) |
| 122 |
if msg: |
| 123 |
raise ValueError( |
| 124 |
"The following keybindings were not valid:\n" + "\n".join(msg) |
| 125 |
) |
| 126 |
|
| 127 |
if not disposers: # pragma: no cover |
| 128 |
return None |
| 129 |
|
| 130 |
def _dispose() -> None: |
| 131 |
for disposer in disposers: |
| 132 |
disposer() |
| 133 |
|
| 134 |
return _dispose |
| 135 |
|
| 136 |
def register_keybinding_rule( |
| 137 |
self, id: str, rule: KeyBindingRule |
| 138 |
) -> DisposeCallable | None: |
| 139 |
"""Register a new keybinding rule. |
| 140 |
|
| 141 |
Parameters |
| 142 |
---------- |
| 143 |
id : str |
| 144 |
Command identifier that should be run when the keybinding is triggered |
| 145 |
rule : KeyBindingRule |
| 146 |
KeyBinding information |
| 147 |
|
| 148 |
Returns |
| 149 |
------- |
| 150 |
Optional[DisposeCallable] |
| 151 |
A callable that can be used to unregister the keybinding |
| 152 |
""" |
| 153 |
if plat_keybinding := rule._bind_to_current_platform(): |
| 154 |
# list registry |
| 155 |
keybinding = KeyBinding.validate(plat_keybinding) |
| 156 |
if self._filter_keybinding: |
| 157 |
msg = self._filter_keybinding(keybinding) |
| 158 |
if msg: |
| 159 |
raise ValueError(f"{keybinding}: {msg}") |
| 160 |
entry = _RegisteredKeyBinding( |
| 161 |
keybinding=keybinding, |
| 162 |
command_id=id, |
| 163 |
weight=rule.weight, |
| 164 |
when=rule.when, |
| 165 |
source=rule.source, |
| 166 |
) |
| 167 |
|
| 168 |
# inverse map registry |
| 169 |
entries = self._keymap[keybinding.to_int()] |
| 170 |
insort_left(entries, entry) |
| 171 |
|
| 172 |
self.registered.emit() |
| 173 |
|
| 174 |
def _dispose() -> None: |
| 175 |
# inverse map registry remove |
| 176 |
entries.remove(entry) |
| 177 |
self.unregistered.emit() |
| 178 |
if len(entries) == 0: |
| 179 |
del self._keymap[keybinding.to_int()] |
| 180 |
|
| 181 |
return _dispose |
| 182 |
return None # pragma: no cover |
| 183 |
|
| 184 |
def __iter__(self) -> Iterator[_RegisteredKeyBinding]: |
| 185 |
yield from self._keybindings |
| 186 |
|
| 187 |
def __len__(self) -> int: |
| 188 |
return sum(len(entries) for entries in self._keymap.values()) |
| 189 |
|
| 190 |
def __repr__(self) -> str: |
| 191 |
name = self.__class__.__name__ |
| 192 |
return f"<{name} at {hex(id(self))} ({len(self)} bindings)>" |
| 193 |
|
| 194 |
def get_keybinding(self, command_id: str) -> _RegisteredKeyBinding | None: |
| 195 |
"""Return the first keybinding that matches the given command ID.""" |
| 196 |
# TODO: improve me. |
| 197 |
matches = (kb for kb in self._keybindings if kb.command_id == command_id) |
| 198 |
sorted_matches = sorted(matches, key=lambda x: x.source, reverse=True) |
| 199 |
return next(iter(sorted_matches), None) |
| 200 |
|
| 201 |
def get_context_prioritized_keybinding( |
| 202 |
self, key: int, context: Mapping[str, object] |
| 203 |
) -> _RegisteredKeyBinding | None: |
| 204 |
""" |
| 205 |
Return the first keybinding that matches the given key sequence. |
| 206 |
|
| 207 |
The keybinding should be enabled given the context to be returned. |
| 208 |
|
| 209 |
Parameters |
| 210 |
---------- |
| 211 |
key : int |
| 212 |
The key sequence that represent the keybinding. |
| 213 |
context : Mapping[str, object] |
| 214 |
Variable context to parse the `when` expression to determine if the |
| 215 |
keybinding is enabled or not. |
| 216 |
|
| 217 |
Returns |
| 218 |
------- |
| 219 |
_RegisteredKeyBinding | None |
| 220 |
The keybinding found or None otherwise. |
| 221 |
|
| 222 |
""" |
| 223 |
if key in self._keymap: |
| 224 |
for entry in reversed(self._keymap[key]): |
| 225 |
if entry.when is None or entry.when.eval(context): |
| 226 |
return entry |
| 227 |
return None |