diff --git a/pyproject.toml b/pyproject.toml index b94d0e5da8..1170ae5750 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,6 +53,7 @@ rich = ">=14.2.0" typing-extensions = "^4.4.0" platformdirs = ">=3.6.0,<5" metaclass-registry = { git = "https://github.com/OpenHCSDev/metaclass-registry", branch = "main" } +formbridge = { git = "https://github.com/OpenHCSDev/formbridge.git", branch = "main" } # start of [syntax] extras # Require tree-sitter >= 0.25.0 and python >= 3.10 diff --git a/src/textual/binding.py b/src/textual/binding.py index d98a56609b..613471c615 100644 --- a/src/textual/binding.py +++ b/src/textual/binding.py @@ -8,6 +8,7 @@ from __future__ import annotations import dataclasses +from abc import abstractmethod from dataclasses import dataclass, field from inspect import iscoroutinefunction from types import FunctionType @@ -29,9 +30,9 @@ from textual._callback import invoke, invoke_sync from textual.actions import SkipAction -from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation +from formbridge.key_declarations import DeclaredKey, KeyDeclaration, KeyInvocation, UndecodedKey -from textual.keys import DeclaredKey, UndecodedKey, _character_to_key +from textual.keys import _character_to_key if TYPE_CHECKING: from textual.document._editing import EditingMode @@ -434,6 +435,17 @@ def key_identity(self) -> str: NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True) +class BindingDeclaration(KeyDeclaration[NodeT]): + """A key declaration whose class projects its own Textual bindings, as a DOM node's + key families ask it to.""" + + @classmethod + @abstractmethod + def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: + """The declaration's defaults in one active editing mode.""" + raise NotImplementedError + + @dataclass(frozen=True, kw_only=True) class CommandBinding(ModeBinding, Generic[NodeT]): """The callable is the command itself, including its invocation identity.""" diff --git a/src/textual/document/_editing.py b/src/textual/document/_editing.py index d1acc77638..caf659cd7a 100644 --- a/src/textual/document/_editing.py +++ b/src/textual/document/_editing.py @@ -4,7 +4,7 @@ from abc import ABC, abstractmethod from typing import TYPE_CHECKING -from metaclass_registry.key_declarations import InputMode, ModalInputMode +from formbridge.key_declarations import InputMode, ModalInputMode from textual.binding import Binding, MethodBinding from textual.cursor_shape import CursorShape, SteadyBlock, TextEntryCursor @@ -13,7 +13,6 @@ if TYPE_CHECKING: from textual.events import Key - from textual.keys import NavigationKey from textual.widgets import TextArea @@ -24,10 +23,6 @@ class EditingFailure(RuntimeError): class EditingMode(InputMode): """Native text entry, with overridable document and input ownership.""" - @classmethod - def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]: - return (key.key.value,) - @property def accepts_text(self) -> bool: return True @@ -167,10 +162,6 @@ def allows_application_commands(self) -> bool: class VimMode(EditingMode, ModalInputMode, ABC): """Modal binding capability, not a second implementation of Vim.""" - @classmethod - def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]: - return (*super().navigation_spellings(key), key.modal) - @property def cursor_shape(self) -> CursorShape: return SteadyBlock() diff --git a/src/textual/dom.py b/src/textual/dom.py index 0c97fd15bb..14a935e50e 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -52,7 +52,7 @@ from textual.geometry import Size from textual.css.tokenize import IDENTIFIER from textual.message_pump import MessagePump -from textual.keys import BindingDeclaration +from textual.binding import BindingDeclaration from textual.reactive import Reactive, ReactiveError, _Mutated, _StoredReactiveAccess, _watch from textual.timer import Timer from textual.walk import walk_breadth_first, walk_breadth_search_id, walk_depth_first diff --git a/src/textual/keys.py b/src/textual/keys.py index f2bc05d014..09c7f17acb 100644 --- a/src/textual/keys.py +++ b/src/textual/keys.py @@ -1,33 +1,9 @@ from __future__ import annotations import unicodedata -from abc import abstractmethod -from typing import TYPE_CHECKING, ClassVar, TypeVar from enum import Enum -from dataclasses import dataclass from functools import lru_cache -if TYPE_CHECKING: - from textual.binding import Binding - from textual.document._editing import EditingMode - from textual.dom import DOMNode - from textual.events import Key - -from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation - -NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True) - - -class BindingDeclaration(KeyDeclaration[NodeT]): - """A key declaration whose class projects its own Textual bindings, as a DOM node's - key families ask it to.""" - - @classmethod - @abstractmethod - def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: - """The declaration's defaults in one active editing mode.""" - raise NotImplementedError - # Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py class Keys(str, Enum): # type: ignore[no-redef] @@ -224,107 +200,6 @@ def value(self) -> str: ShiftControlEnd = ControlShiftEnd -@dataclass(frozen=True) -class DeclaredKey: - """A decoded native input identity, distinct from its configured spelling.""" - - def decoded(self, key: str) -> DeclaredKey: - return self - - def spellings(self, mode: type[EditingMode], spelling: str) -> tuple[str, ...]: - return (spelling,) - - def invocations(self, defaults: tuple[KeyInvocation, ...]) -> tuple[KeyInvocation, ...]: - return defaults - - def preempts(self, event: Key, target: DOMNode) -> bool: - return False - - def input_bindings(self, spelling: str) -> tuple[tuple[str, str], ...]: - """Native input aliases for an external editing engine.""" - return () - - -class UndecodedKey(DeclaredKey): - """Only Binding.make_bindings sees an external declaration's key spelling.""" - - def decoded(self, key: str) -> DeclaredKey: - return NavigationKey.from_key(key) - - -class NavigationKey(DeclaredKey, KeyInvocation): - """One preference for an arrow, independent of the focused control's effect. - - Bindings keep their native callable, availability and order. Only the saved - input identity is shared: configuring Up must not mean configuring TextArea, - a table, a tree and every future arrow control separately. - """ - - key: ClassVar[Keys] - modal: ClassVar[str] - _by_key: ClassVar[dict[str, type[NavigationKey]]] = {} - - def __init_subclass__(cls, *, key: Keys, modal: str, **kwargs: object) -> None: - super().__init_subclass__(**kwargs) - cls.key = key - cls.modal = modal - cls._by_key[key.value] = cls - - @classmethod - def from_key(cls, key: str) -> DeclaredKey: - """Decode a declared native key once, before any preference changes it.""" - try: - declaration = cls._by_key[key] - except KeyError: - return DeclaredKey() - return declaration() - - def invocations(self, defaults: tuple[KeyInvocation, ...]) -> tuple[KeyInvocation, ...]: - return (self,) - - def spellings(self, mode: type[EditingMode], spelling: str) -> tuple[str, ...]: - return mode.navigation_spellings(type(self)) - - def preempts(self, event: Key, target: DOMNode) -> bool: - """Arrow aliases precede search, never the target's literal text input.""" - return event.is_printable and not target.takes_typed_text - - def key_identity(self) -> str: - return self.qualified(type(self)) - - def input_bindings(self, spelling: str) -> tuple[tuple[str, str], ...]: - return ((spelling, self.key.value),) - - def key_title(self) -> str: - return f"Cursor {self.key.value}" - - def key_summary(self) -> str: - return f"Use these keys wherever the focused control handles {self.key.value}." - - def key_system(self) -> bool: - return False - - def visible_for_focus(self, focused: bool) -> bool: - """Global arrow preferences remain editable even from a non-arrow focus.""" - return True - - -class UpKey(NavigationKey, key=Keys.Up, modal="k"): - pass - - -class DownKey(NavigationKey, key=Keys.Down, modal="j"): - pass - - -class LeftKey(NavigationKey, key=Keys.Left, modal="h"): - pass - - -class RightKey(NavigationKey, key=Keys.Right, modal="l"): - pass - - # Unicode db contains some obscure names # This mapping replaces them with more common terms KEY_NAME_REPLACEMENTS = { diff --git a/src/textual/navigation.py b/src/textual/navigation.py index 4fe42b6cac..e4047187da 100644 --- a/src/textual/navigation.py +++ b/src/textual/navigation.py @@ -5,10 +5,11 @@ from typing import ClassVar from textual.actions import SkipAction -from textual.binding import Binding, CommandBinding +from formbridge.key_declarations import DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey + +from textual.binding import Binding, BindingDeclaration, CommandBinding from textual.document._editing import EditingMode from textual.dom import DOMNode -from textual.keys import BindingDeclaration, DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey class NavigationCommand(BindingDeclaration["Navigation"]): diff --git a/src/textual/screen.py b/src/textual/screen.py index 064188fb09..1aeedb3140 100644 --- a/src/textual/screen.py +++ b/src/textual/screen.py @@ -545,9 +545,10 @@ async def dispatch_remapped_key(self, event: events.Key, target: Widget) -> bool second delivery. Native editor bindings forward it to their mode owner; ordinary controls execute their own declared action. """ + printable_outside_text = event.is_printable and not target.takes_typed_text for node, bindings in self._modal_binding_chain: for binding in bindings.key_to_bindings.get(event.key, ()): - if binding.declared_key.preempts(event, target): + if binding.declared_key.preempts(printable_outside_text): if await binding.run_before_text(self.app, node, event, target): return True return False diff --git a/tests/input/test_input_key_movement_actions.py b/tests/input/test_input_key_movement_actions.py index 74c6e4d8eb..8e03ee7bfd 100644 --- a/tests/input/test_input_key_movement_actions.py +++ b/tests/input/test_input_key_movement_actions.py @@ -4,8 +4,7 @@ from textual.app import App, ComposeResult from textual.document._editing import EditingMode -from metaclass_registry.key_declarations import KeyInvocation -from textual.keys import LeftKey, RightKey +from formbridge.key_declarations import KeyInvocation, LeftKey, RightKey from textual.widgets import Input diff --git a/tests/test_navigation_spellings.py b/tests/test_navigation_spellings.py index 5684c3081d..a677fd3938 100644 --- a/tests/test_navigation_spellings.py +++ b/tests/test_navigation_spellings.py @@ -1,11 +1,11 @@ """Arrow identities supply modal spellings, including controls not hand-patched.""" +from formbridge.key_declarations import DownKey, NavigationKey from textual import widgets from textual.app import App, ComposeResult from textual.containers import VerticalScroll from textual.document._editing import EditingMode, VimMode from textual.dom import DOMNode from textual.events import Key -from textual.keys import DownKey, NavigationKey from textual.screen import Screen from textual.widgets import Input, TextArea, Tree @@ -20,11 +20,11 @@ def test_navigation_spellings_follow_every_declared_context() -> None: modal = owner.binding_defaults(VimMode) for direction in NavigationKey.__subclasses__(): arrows = tuple( - binding for binding in modal.key_to_bindings.get(direction.key.value, ()) + binding for binding in modal.key_to_bindings.get(direction.key, ()) if binding.declared_key == direction() ) if any(binding.declared_key == direction() - for binding in standard.key_to_bindings.get(direction.key.value, ())): + for binding in standard.key_to_bindings.get(direction.key, ())): assert arrows, (owner, direction) for arrow in arrows: assert arrow.with_key(direction.modal) in modal.key_to_bindings.get(direction.modal, ()), (owner, direction) diff --git a/tests/text_area/test_edit_via_bindings.py b/tests/text_area/test_edit_via_bindings.py index 004c405cf2..8f23834c72 100644 --- a/tests/text_area/test_edit_via_bindings.py +++ b/tests/text_area/test_edit_via_bindings.py @@ -12,8 +12,7 @@ from textual.app import App, ComposeResult from textual.document._editing import EditingMode from textual.events import Paste -from metaclass_registry.key_declarations import KeyInvocation -from textual.keys import LeftKey +from formbridge.key_declarations import KeyInvocation, LeftKey from textual.widgets import TextArea from textual.widgets.text_area import Selection