From b58269e04c649b4be8c964ce56aa02ad557bb28e Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 16 Nov 2026 14:45:47 -0500 Subject: [PATCH] Application actions import without Textual, so Qt lists the same menu The action family root (DeclaredAction: keys, title, summary, availability, menu offering, apply) and ApplicationAction with its menu move to toad.client.application_actions, built on metaclass_registry's key declarations. New thread, Channels, Direct messages and Quit live there too: their bodies only need the shared client and host. Channels runs its reveal as a ChannelsReveal operation instead of a Textual worker. The members that push Textual screens or use Textual widgets stay in toad.application_actions, still in the same family, so the Textual menu, palette and keys list the whole family and Qt lists whatever its process imported. Turning a declaration's keys into Textual bindings moves from the action classes to DeclaredWidgetActions (key_bindings, mode_bindings, exclusive_bindings, configured_bindings, active_declared_bindings). Widget Action adds its footer group and engine key through refine_binding. ToadApp's bindings are the same set before and after. System, YieldingKey and ReplacesFrameworkAction move with the family. Every importer is repointed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLdupVQyBzHTmHBC9Cyn --- src/toad/app.py | 3 +- src/toad/application_actions.py | 44 +-- src/toad/client/application_actions.py | 202 ++++++++++++++ src/toad/conversation_actions.py | 2 +- src/toad/keymap.py | 7 +- src/toad/menus.py | 4 +- src/toad/session_navigation.py | 4 + src/toad/widget_actions.py | 259 +++++------------- src/toad/widgets/comms_sidebar.py | 2 +- src/toad/widgets/question.py | 3 +- src/toad/widgets/side_bar.py | 4 +- tests/guards/test_keymap_owner.py | 5 +- ..._application_actions_in_the_running_app.py | 2 +- tests/textual/test_bus_choice.py | 2 +- tests/textual/test_main_menu_transfer.py | 3 +- 15 files changed, 296 insertions(+), 250 deletions(-) create mode 100644 src/toad/client/application_actions.py diff --git a/src/toad/app.py b/src/toad/app.py index 5f81615ccb..cceef7e859 100644 --- a/src/toad/app.py +++ b/src/toad/app.py @@ -71,7 +71,8 @@ from toad.widgets.comms_command_dialog import ScreenCommandOrigin from toad.widgets.comms_sidebar import CommsSidebar from toad.widgets.side_bar import SideBar, SideBarCollapsible -from toad.widget_actions import ApplicationAction, DeclaredWidgetActions +from toad.client.application_actions import ApplicationAction +from toad.widget_actions import DeclaredWidgetActions from toad.widgets import tool_call # noqa: F401 - register widget classes from toad.widgets.comms_transfer import Transfers from toad.work_preparation import PreparationRuntime diff --git a/src/toad/application_actions.py b/src/toad/application_actions.py index 3cc8c8c8d2..4df335de3c 100644 --- a/src/toad/application_actions.py +++ b/src/toad/application_actions.py @@ -1,4 +1,5 @@ -"""Textual actions, bindings and palette entries share their declarations.""" +"""The application actions whose bodies need Textual, declared after the shared ones in +`toad.client.application_actions`, and the palette that offers the whole family.""" from __future__ import annotations @@ -12,13 +13,13 @@ from toad.preferences import SETTINGS from toad.screens.keymap import KeymapScreen from toad.keymap import KeyInvocationId -from toad.widget_actions import ( +from toad.client.application_actions import ( ApplicationAction, ReplacesFrameworkAction, System, - VimWorkspaceAction, YieldingKey, ) +from toad.widget_actions import VimWorkspaceAction from toad.widgets.comms_transfer import Transfer, Transfers from toad.core.session_requests import SessionNavigate from toad.sidebar_placement import LeftSidebarEdge, RightSidebarEdge, SidebarEdge @@ -27,15 +28,6 @@ from toad.app import ToadApp -# Declaration order is the order of the menu and the palette. -class NewThreadAction(ApplicationAction): - """Start a thread in the selected project.""" - - async def apply(self, app: ToadApp) -> None: - navigation = app.session_navigation - navigation.open_thread_form(navigation.selected_project()) - - class OpenBusAction(ApplicationAction): """Connect to this machine's bus or choose another machine.""" @@ -177,25 +169,6 @@ async def apply(self, app: ToadApp) -> None: app.push_screen(KeymapScreen(focused)) -class ChannelsAction(ApplicationAction): - """Reveal channels and focus the selected session.""" - - keys = {EditingMode: ("ctrl+s",)} - show = True - - async def apply(self, app: ToadApp) -> None: - app.run_worker(app.session_navigation.reveal) - - -class DirectMessagesAction(ApplicationAction): - """Open the most recently selected direct conversation.""" - - keys = {EditingMode: ("ctrl+shift+d",)} - - async def apply(self, app: ToadApp) -> None: - app.session_navigation.direct_messages() - - class VimCycleTabAction(VimWorkspaceAction, declared_name=None): direction: Literal[-1, 1] @@ -276,15 +249,6 @@ class VimMoveTabRightAction(VimMoveTabAction): direction = +1 -class QuitAction(ReplacesFrameworkAction, ApplicationAction): - """Save preferences and quit the application.""" - - keys = {EditingMode: ("ctrl+q",)} - - async def apply(self, app: ToadApp) -> None: - app.application.quit() - - class ApplicationCommands(Provider): """Discovery and search derive the same capability view; no command roster.""" diff --git a/src/toad/client/application_actions.py b/src/toad/client/application_actions.py new file mode 100644 index 0000000000..393213f49c --- /dev/null +++ b/src/toad/client/application_actions.py @@ -0,0 +1,202 @@ +"""The action family every client offers: what each action is called, when it is offered, +the keys it declares and what it does through the shared host. A client projects the +declared keys into its own bindings; members whose bodies need one toolkit are declared +in that toolkit's modules, as members of this same family.""" + +from __future__ import annotations + +import inspect +from abc import abstractmethod +from collections.abc import Iterator, Mapping +from types import MappingProxyType +from typing import ClassVar, Generic, Self, TypeVar, cast + +from agent_comms.nominal.declared_family import ( + DeclaredFamily, + FamilyMeta, + declared_words, +) +from agent_comms.planning.command import Command +from metaclass_registry.key_declarations import InputMode, KeyDeclaration, KeyDeclarationType + +from toad.client.application import ClientApplication +from toad.session_navigation import ChannelsReveal + + +Context = TypeVar("Context") + + +class KeyFamilyMeta(FamilyMeta, KeyDeclarationType): + """A named command family whose classes declare native key overlap.""" + + +class DeclaredAction(KeyDeclaration[Context], Command, DeclaredFamily, Generic[Context], + metaclass=KeyFamilyMeta, affix="Action"): + """Only a client's boundary decodes an external action name. A member declares its + keys, and its title and docstring are the only text any view shows for it.""" + + keys: ClassVar[Mapping[type[InputMode], tuple[str, ...]]] = MappingProxyType({}) + show: ClassVar[bool] = False + priority: ClassVar[bool] = False + key_display: ClassVar[str | None] = None + binding_prefix: ClassVar[str] = "" + + @classmethod + def default_title(cls) -> str: + """The class's own derived name, never its declared_name: views show what a member does.""" + return declared_words(cls.__name__.removesuffix(cls._family_affix)).replace("_", " ").capitalize() + + @classmethod + def declarations(cls) -> Iterator[type[Self]]: + """The native registry filters by this class, so each member is one of its own.""" + return cast("Iterator[type[Self]]", super().declarations()) + + @classmethod + def summary(cls) -> str: + """The nearest docstring a member declares; the family roots document code, not keys.""" + root = cls.family_root + return next((inspect.cleandoc(base.__doc__) for base in cls.__mro__ + if issubclass(base, root) and base is not root and base.__doc__), "") + + @classmethod + def binding_name(cls) -> str: + return cls.binding_prefix + cls.declared_name + + @classmethod + def command_for_key(cls, mode: type[InputMode], key: str) -> Self: + return cls() + + @classmethod + def refine_binding[Binding](cls, binding: Binding) -> Binding: + """A family whose bindings carry more of its declaration completes them here.""" + return binding + + @classmethod + def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]: + """The keys this member claims against every other scope's: none unless it says so.""" + return () + + def __call__(self, context: Context) -> object: + return self.apply(context) + + @classmethod + def parse(cls, parameters: tuple[object, ...]): + if parameters: + raise ValueError(f"{cls.declared_name} takes no parameters") + return cls() + + @classmethod + def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None: + """A generated dispatcher may not replace an action a class wrote: a member whose apply + calls that action would then call itself.""" + if writers: + raise TypeError(f"{cls.__qualname__} would replace {writers[0].__qualname__}.{name}") + + @classmethod + def offered(cls, context: Context) -> Iterator[Self]: + """What the menu and the palette offer for this member: itself, where it is available.""" + command = cls() + if command.available(context): + yield command + + def label(self, context: Context) -> str: + """A state-dependent title overrides this; every other member shows its title.""" + return self.title + + def available(self, context: Context) -> bool | None: + return True + + def engine_boundary(self, editor: object) -> bool: + """An external engine offers this action at its key; only an EngineKey member is asked.""" + return False + + def key_available(self, context: Context) -> bool | None: + """Keyboard scope may be narrower than menu/palette command availability.""" + return self.available(context) + + @abstractmethod + def apply(self, context: Context) -> object: ... + + +class System: + """Only its key reaches the action: no menu, palette or key panel shows it.""" + + system: ClassVar[bool] = True + + @classmethod + def offered(cls, context: object) -> Iterator[Self]: + return iter(()) + + +class YieldingKey: + """An application key that any binding closer to the focus replaces: it answers only + where nothing local claims the key, so the claim is no conflict.""" + + priority = False + + @classmethod + def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]: + return () + + +class ReplacesFrameworkAction: + """A member declared to stand in for one of the toolkit's own actions (Screen.action_dismiss, + App.action_quit): replacing that written action is its purpose.""" + + @classmethod + def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None: + pass + + +class ApplicationAction(DeclaredAction[ClientApplication], affix="Action"): + """Declared application shortcuts resolve before an editor takes the key.""" + + binding_prefix = "app." + priority = True + + @classmethod + def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]: + return bindings + + @classmethod + def menu(cls, app: ClientApplication) -> tuple[tuple[ApplicationAction, str], ...]: + """Every offered member under its label, in declaration order.""" + return tuple((command, command.label(app)) + for member in cls.members_with(cls) for command in member.offered(app)) + + +# Declaration order is the order of the menu and the palette. +class NewThreadAction(ApplicationAction): + """Start a thread in the selected project.""" + + async def apply(self, app: ClientApplication) -> None: + navigation = app.session_navigation + navigation.open_thread_form(navigation.selected_project()) + + +class ChannelsAction(ApplicationAction): + """Reveal channels and focus the selected session.""" + + keys = {InputMode: ("ctrl+s",)} + show = True + + async def apply(self, app: ClientApplication) -> None: + app.run_operation(ChannelsReveal, app.session_navigation.reveal) + + +class DirectMessagesAction(ApplicationAction): + """Open the most recently selected direct conversation.""" + + keys = {InputMode: ("ctrl+shift+d",)} + + async def apply(self, app: ClientApplication) -> None: + app.session_navigation.direct_messages() + + +class QuitAction(ReplacesFrameworkAction, ApplicationAction): + """Save preferences and quit the application.""" + + keys = {InputMode: ("ctrl+q",)} + + async def apply(self, app: ClientApplication) -> None: + app.application.quit() diff --git a/src/toad/conversation_actions.py b/src/toad/conversation_actions.py index eb41345a1d..3cdff96de5 100644 --- a/src/toad/conversation_actions.py +++ b/src/toad/conversation_actions.py @@ -101,7 +101,7 @@ def available(self, conversation): return True if conversation.agent_binding.cancel_allowed(conversation.turns.owner) else None async def apply(self, conversation): - conversation.cancel_turn(conversation.app.get_key_display(*self.active_bindings(conversation))) + conversation.cancel_turn(conversation.app.get_key_display(*conversation.active_declared_bindings(type(self)))) class PageFractionAction(ConversationAction): diff --git a/src/toad/keymap.py b/src/toad/keymap.py index af1dd94c5c..b1829db9e7 100644 --- a/src/toad/keymap.py +++ b/src/toad/keymap.py @@ -15,14 +15,15 @@ from objectstate import mark_ui_hidden_config from textual.binding import KeymapClaim from textual.dom import DOMNode -from textual.keys import KeyInvocation +from metaclass_registry.key_declarations import KeyInvocation from textual.screen import ModalScreen import toad from toad.key_modes import KeyMode from toad.menus import MenuCommand from toad.setting_declarations import Effect, FamilyChoices -from toad.widget_actions import ApplicationAction +from toad.client.application_actions import ApplicationAction +from toad.widget_actions import DeclaredWidgetActions if TYPE_CHECKING: from formbridge.forms.declared_fields import DeclaredField @@ -160,7 +161,7 @@ def declared( native_mode = mode.binding_mode() application = tuple(KeymapClaim.from_bindings( binding for declaration in actions - for binding in declaration.exclusive_bindings(native_mode) + for binding in DeclaredWidgetActions.exclusive_bindings(declaration, native_mode) )) owned = [application] for owner in contexts: diff --git a/src/toad/menus.py b/src/toad/menus.py index 56dc7408cb..2e2217c0b8 100644 --- a/src/toad/menus.py +++ b/src/toad/menus.py @@ -11,12 +11,12 @@ from textual._callback import invoke from textual.binding import ModeBinding from textual.document._editing import EditingMode -from textual.keys import KeyDeclarationType, KeyInvocation +from metaclass_registry.key_declarations import KeyDeclarationType, KeyInvocation from textual.widget import Widget from toad.client.line_blocks import LineLink from toad.message_rows import MessageRow -from toad.widget_actions import KeyFamilyMeta +from toad.client.application_actions import KeyFamilyMeta class MenuConversation: diff --git a/src/toad/session_navigation.py b/src/toad/session_navigation.py index a47b900b0d..68cdb79ba3 100644 --- a/src/toad/session_navigation.py +++ b/src/toad/session_navigation.py @@ -54,6 +54,10 @@ class DirectMessagesOpen(OperationKind): """Opens a direct-message conversation through the navigating view.""" +class ChannelsReveal(OperationKind): + """Shows the channels sidebar, opening the newest session first when none is selected.""" + + class NewThreadForm(OperationKind, ExclusiveKind): """Prepares and opens the new-thread form; a newer request supersedes one running.""" diff --git a/src/toad/widget_actions.py b/src/toad/widget_actions.py index d019f176ba..c200e3b98c 100644 --- a/src/toad/widget_actions.py +++ b/src/toad/widget_actions.py @@ -1,44 +1,36 @@ -"""The Action family and its Textual dispatch projection.""" +"""Textual's actions on widgets, and the Textual projection of every declared action's keys.""" from __future__ import annotations import inspect from abc import abstractmethod -from collections.abc import Callable, Iterator, Mapping +from collections.abc import Callable, Mapping from copy import replace from dataclasses import dataclass from functools import lru_cache, partialmethod from operator import or_ from types import MappingProxyType -from typing import ClassVar, Generic, Literal, Self, TypeVar, cast +from typing import ClassVar, Literal, TypeVar -from agent_comms.nominal.declared_family import ( - DeclaredFamily, - FamilyMeta, - declared_words, -) from agent_comms.nominal.field_codec import FieldCodec, FieldPlan -from agent_comms.planning.command import Command +from metaclass_registry.key_declarations import InputMode, KeyDeclaration, KeyDeclarationType from textual import events, on from textual._activation import PrimaryActivation from textual._callback import invoke from textual.binding import Binding, BindingsMap, CommandBinding, ModeBinding from textual.dom import DOMNode from textual.hint_labels import HintLabelStyle -from textual.keys import DeclaredKey, KeyDeclaration, KeyDeclarationType, UndecodedKey +from textual.keys import DeclaredKey, UndecodedKey from textual.navigation import MovesCursor, MovesHorizontalCursor, SelectCursor from textual.widgets import TextArea from textual.widgets.text_area import EditingMode from toad.app_node import ToadNode +from toad.client.application_actions import ApplicationAction, DeclaredAction, ReplacesFrameworkAction Context = TypeVar("Context", bound=DOMNode) -class KeyFamilyMeta(FamilyMeta, KeyDeclarationType): - """A named command family whose classes declare native key overlap.""" - - class EngineKey(DeclaredKey): """A key an external editing engine receives first and offers back at its own boundary. @@ -57,154 +49,15 @@ def engine_boundary(self, editor: TextArea) -> bool: return self.action.engine_boundary(editor) -class Action(KeyDeclaration[Context], Command, DeclaredFamily, Generic[Context], - metaclass=KeyFamilyMeta, affix="Action"): - """Only the Textual boundary decodes an external action name. A member declares its - keys, and its title and docstring are the only text any view shows for it.""" +class Action(DeclaredAction[Context], affix="Action"): + """An action on a Textual widget: its key may join a footer group and an engine's input.""" - keys: ClassVar[Mapping[type[EditingMode], tuple[str, ...]]] = MappingProxyType({}) - show: ClassVar[bool] = False - priority: ClassVar[bool] = False group: ClassVar[Binding.Group | None] = None - key_display: ClassVar[str | None] = None - binding_prefix: ClassVar[str] = "" declared_key: ClassVar[DeclaredKey] = UndecodedKey() @classmethod - def default_title(cls) -> str: - """The class's own derived name, never its declared_name: views show what a member does.""" - return declared_words(cls.__name__.removesuffix(cls._family_affix)).replace("_", " ").capitalize() - - @classmethod - def declarations(cls) -> Iterator[type[Self]]: - """The native registry filters by this class, so each member is one of its own.""" - return cast("Iterator[type[Self]]", super().declarations()) - - @classmethod - def summary(cls) -> str: - """The nearest docstring a member declares; the family roots document code, not keys.""" - root = cls.family_root - return next((inspect.cleandoc(base.__doc__) for base in cls.__mro__ - if issubclass(base, root) and base is not root and base.__doc__), "") - - @classmethod - def binding_name(cls) -> str: - return cls.binding_prefix + cls.declared_name - - @classmethod - def bindings(cls) -> tuple[Binding, ...]: - return tuple(cls.mode_binding(mode, key) - for mode, keys in cls.keys.items() for key in keys) - - @classmethod - def mode_binding(cls, mode: type[EditingMode], key: str) -> ModeBinding: - command = cls.command_for_key(mode, key) - return cls.command_binding(mode, key, command) - - @classmethod - def command_binding(cls, capability: type[EditingMode], key: str, command: Self) -> ModeBinding: - return ActionBinding( - key=key, action=command, description=cls.title, - available=command.key_available, mode=capability, - tooltip=cls.summary(), show=cls.show, priority=cls.priority, - system=cls.system, group=cls.group, key_display=cls.key_display, - declared_key=cls.declared_key, - ) - - @classmethod - def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: - """The nearest declared capability supplies defaults; identity follows active mode.""" - for capability in mode.__mro__: - if capability in cls.keys: - return tuple(binding for _, binding in BindingsMap( - cls.command_binding(capability, key, - cls.command_for_key(capability, key)) - for key in cls.keys[capability] - ).project(mode)) - return () - - @classmethod - def command_for_key(cls, mode: type[EditingMode], key: str) -> Self: - return cls() - - def __call__(self, context: Context) -> object: - return self.apply(context) - - @classmethod - def configured_bindings(cls, context: Context) -> tuple[Binding, ...]: - """Declared keys after remapping, also when this control is not focused.""" - mode = context.binding_mode - identities = {binding.id for binding in cls.bindings_for(mode)} - bindings = context.binding_map(mode) - bindings.apply_keymap(context.app._keymap) - return tuple(binding for _, binding in bindings if binding.id in identities - and binding.state(context.app, context)) - - @classmethod - def active_bindings(cls, context: Context) -> tuple[Binding, ...]: - identities = {binding.id for binding in cls.bindings_for(context.binding_mode)} - return tuple(binding for node, bindings in context.screen._binding_chain if node is context - for _, binding in bindings if binding.id in identities - and binding.state(context.app, context)) - - @classmethod - def parse(cls, parameters: tuple[object, ...]): - if parameters: - raise ValueError(f"{cls.declared_name} takes no parameters") - return cls() - - @classmethod - def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None: - """A generated dispatcher may not replace an action a class wrote: a member whose apply - calls that action would then call itself.""" - if writers: - raise TypeError(f"{cls.__qualname__} would replace {writers[0].__qualname__}.{name}") - - @classmethod - def offered(cls, context: Context) -> Iterator[Self]: - """What the menu and the palette offer for this member: itself, where it is available.""" - command = cls() - if command.available(context): - yield command - - def label(self, context: Context) -> str: - """A state-dependent title overrides this; every other member shows its title.""" - return self.title - - def available(self, context: Context) -> bool | None: - return True - - def engine_boundary(self, editor: TextArea) -> bool: - """An external engine offers this action at its key; only an EngineKey member is asked.""" - return False - - def key_available(self, context: Context) -> bool | None: - """Keyboard scope may be narrower than menu/palette command availability.""" - return self.available(context) - - @abstractmethod - def apply(self, context: Context) -> object: ... - - -class System: - """Only its key reaches the action: no menu, palette or key panel shows it.""" - - system: ClassVar[bool] = True - - @classmethod - def offered(cls, context: DOMNode) -> Iterator[Self]: - return iter(()) - - -class YieldingKey: - """An application key that any binding closer to the focus replaces: it answers only - where nothing local claims the key, so the claim is no conflict.""" - - priority = False - - @classmethod - def exclusive_bindings(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: - return () + def refine_binding(cls, binding: ActionBinding) -> ActionBinding: + return replace(binding, group=cls.group, declared_key=cls.declared_key) class ExclusiveKeys: @@ -216,23 +69,6 @@ def permits_key_overlap(cls, other: KeyDeclarationType) -> bool: return issubclass(other, family) -class ApplicationAction(Action, affix="Action"): - """Declared application shortcuts resolve before an editor takes the key.""" - - binding_prefix = "app." - priority = True - - @classmethod - def exclusive_bindings(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: - return cls.bindings_for(mode) - - @classmethod - def menu(cls, app) -> tuple[tuple[ApplicationAction, str], ...]: - """Every offered member under its label, in declaration order.""" - return tuple((command, command.label(app)) - for member in cls.members_with(cls) for command in member.offered(app)) - - class VimWorkspaceAction(ApplicationAction, declared_name=None): """Workspace commands precede editor bindings only in idle modal command entry.""" @@ -246,10 +82,10 @@ def key_available(self, app) -> bool: class DeclaredWidgetActions(ToadNode): """One family supplies both native dispatch and dynamic availability.""" - own_actions: ClassVar[tuple[type[Action], ...]] = () + own_actions: ClassVar[tuple[type[DeclaredAction], ...]] = () @classmethod - def declared_actions(cls) -> tuple[type[Action], ...]: + def declared_actions(cls) -> tuple[type[DeclaredAction], ...]: """Capabilities and the widget's own family compose through its MRO.""" return tuple(dict.fromkeys( member for base in cls.__mro__ @@ -257,9 +93,57 @@ def declared_actions(cls) -> tuple[type[Action], ...]: for member in family.members_with(family) )) + @staticmethod + def key_bindings(declaration: type[DeclaredAction]) -> tuple[Binding, ...]: + """A declaration's default bindings in every mode it declares keys for.""" + return tuple(DeclaredWidgetActions.command_binding( + declaration, mode, key, declaration.command_for_key(mode, key)) + for mode, keys in declaration.keys.items() for key in keys) + + @staticmethod + def command_binding(declaration: type[DeclaredAction], capability: type[InputMode], key: str, + command: DeclaredAction) -> ModeBinding: + return declaration.refine_binding(ActionBinding( + key=key, action=command, description=declaration.title, + available=command.key_available, mode=capability, + tooltip=declaration.summary(), show=declaration.show, priority=declaration.priority, + system=declaration.system, key_display=declaration.key_display, + )) + + @staticmethod + def mode_bindings(declaration: type[DeclaredAction], mode: type[EditingMode]) -> tuple[Binding, ...]: + """The nearest declared capability supplies defaults; identity follows active mode.""" + for capability in mode.__mro__: + if capability in declaration.keys: + return tuple(binding for _, binding in BindingsMap( + DeclaredWidgetActions.command_binding( + declaration, capability, key, declaration.command_for_key(capability, key)) + for key in declaration.keys[capability] + ).project(mode)) + return () + + @staticmethod + def exclusive_bindings(declaration: type[DeclaredAction], mode: type[EditingMode]) -> tuple[Binding, ...]: + return declaration.exclusive_claims(DeclaredWidgetActions.mode_bindings(declaration, mode)) + + def configured_bindings(self, declaration: type[DeclaredAction]) -> tuple[Binding, ...]: + """Declared keys after remapping, also when this control is not focused.""" + mode = self.binding_mode + identities = {binding.id for binding in self.mode_bindings(declaration, mode)} + bindings = self.binding_map(mode) + bindings.apply_keymap(self.app._keymap) + return tuple(binding for _, binding in bindings if binding.id in identities + and binding.state(self.app, self)) + + def active_declared_bindings(self, declaration: type[DeclaredAction]) -> tuple[Binding, ...]: + identities = {binding.id for binding in self.mode_bindings(declaration, self.binding_mode)} + return tuple(binding for node, bindings in self.screen._binding_chain if node is self + for _, binding in bindings if binding.id in identities + and binding.state(self.app, self)) + @classmethod - def declaration_bindings(cls, declaration: type[Action], mode: type[EditingMode]) -> tuple[Binding, ...]: - return declaration.bindings_for(mode) + def declaration_bindings(cls, declaration: type[DeclaredAction], mode: type[EditingMode]) -> tuple[Binding, ...]: + return cls.mode_bindings(declaration, mode) @classmethod def declared_bindings(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: @@ -278,7 +162,7 @@ def scope_bindings(self) -> BindingsMap: """A fresh map over this scope's frozen bindings for the current mode.""" return BindingsMap(self._scope_bindings(self.binding_mode)) - def __init_subclass__(cls, actions: tuple[type[Action], ...] = (), **kwargs): + def __init_subclass__(cls, actions: tuple[type[DeclaredAction], ...] = (), **kwargs): cls.own_actions = actions declarations = cls.declared_actions() for declaration in declarations: @@ -297,13 +181,13 @@ def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | No return declaration.parse(parameters).key_available(self) return super().check_action(action, parameters) - def _run_declared_action(self, declaration: type[Action], *parameters: object) -> object: + def _run_declared_action(self, declaration: type[DeclaredAction], *parameters: object) -> object: command = declaration.parse(parameters) if command.available(self): return command.apply(self) return None - async def _run_declared_async_action(self, declaration: type[Action], *parameters: object) -> None: + async def _run_declared_async_action(self, declaration: type[DeclaredAction], *parameters: object) -> None: await invoke(self._run_declared_action, declaration, *parameters) @@ -347,15 +231,6 @@ class VisibleAction(WidgetAction): show = True -class ReplacesFrameworkAction: - """A member declared to stand in for one of Textual's own actions (Screen.action_dismiss, - App.action_quit): replacing that written action is its purpose.""" - - @classmethod - def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None: - pass - - class DismissAction(ReplacesFrameworkAction, VisibleAction): """Close the current control.""" keys = {EditingMode: ("escape",)} @@ -573,7 +448,7 @@ class ActionPresentation(DeclaredWidgetActions): def __init_subclass__( cls, fields: tuple[FieldPlan, ...] = (), combine: Combiner = or_, scopes: PresentationScopes = MappingProxyType({}), - actions: tuple[type[Action], ...] = (), **kwargs: object, + actions: tuple[type[DeclaredAction], ...] = (), **kwargs: object, ) -> None: cls.binding_styles = tuple(BindingStyle(field, combine) for field in fields) cls.scopes = scopes @@ -592,7 +467,7 @@ def present_binding(cls, declaration: type[KeyDeclaration], binding: Binding) -> return binding @classmethod - def declaration_bindings(cls, declaration: type[Action], mode: type[EditingMode]) -> tuple[Binding, ...]: + def declaration_bindings(cls, declaration: type[DeclaredAction], mode: type[EditingMode]) -> tuple[Binding, ...]: return tuple(cls.present_binding(declaration, binding) for binding in super().declaration_bindings(declaration, mode)) diff --git a/src/toad/widgets/comms_sidebar.py b/src/toad/widgets/comms_sidebar.py index 1d163ee3a5..37ab3b478d 100644 --- a/src/toad/widgets/comms_sidebar.py +++ b/src/toad/widgets/comms_sidebar.py @@ -40,7 +40,7 @@ ) from toad.client.session_tracker import SidebarSelection from toad.widgets.selection import HoverSelection -from toad.application_actions import NewThreadAction +from toad.client.application_actions import NewThreadAction from toad.widget_actions import OpensSelected from toad.widgets.session_sort import ChannelListSort, CommsSortChoice, ThreadSortForm from toad.widgets.sidebar_tree import ( diff --git a/src/toad/widgets/question.py b/src/toad/widgets/question.py index 775557753c..bd94a9d769 100644 --- a/src/toad/widgets/question.py +++ b/src/toad/widgets/question.py @@ -33,7 +33,6 @@ from toad.question_actions import QuestionAction, QuestionContext, SelectKindAction from toad.question_presentation import QuestionPresentation from toad.widget_actions import StepsVerticalCursor, VisibleActions -from textual import on type Options = list[Answer] @@ -308,7 +307,7 @@ def option_keys(self) -> Iterator[tuple[str, ...]]: are never built, so a question with nothing to answer pays nothing on a binding change.""" candidates = tuple((declaration.kind, binding.key) for declaration in SelectKindAction.members_with(SelectKindAction) - for binding in declaration.configured_bindings(self)) + for binding in self.configured_bindings(declaration)) seen: set[str] = set() for answer in self.options: yield tuple(key for kind, key in candidates if kind == answer.kind and kind not in seen) diff --git a/src/toad/widgets/side_bar.py b/src/toad/widgets/side_bar.py index da07cae6ac..2794e36b2f 100644 --- a/src/toad/widgets/side_bar.py +++ b/src/toad/widgets/side_bar.py @@ -12,7 +12,8 @@ from toad.worker_group import WorkerGroup from toad.core import events as core_events from textual.content import Content -from toad.widget_actions import ApplicationAction, ActivationKeys, Activates, DismissibleControl, WidgetAction, DeclaredWidgetActions, StepsHorizontalCursor, StepsVerticalCursor, VisibleActions +from toad.client.application_actions import ApplicationAction +from toad.widget_actions import ActivationKeys, Activates, DismissibleControl, WidgetAction, DeclaredWidgetActions, StepsHorizontalCursor, StepsVerticalCursor, VisibleActions from textual.document._editing import EditingMode from toad.widgets.comms_menu import ContextMenu from toad.core.preference_events import PreferenceChanged @@ -65,7 +66,6 @@ from toad.sidebar_placement import HeightSidebarEdge, SidebarEdge, SidebarPlacement, ThreadSidebarPlacement from toad.widgets.sidebar_viewport import SidebarViewport, ViewportHeader from toad.app_node import ToadNode -from textual import on if TYPE_CHECKING: from toad.client.tab_order import TabOrder diff --git a/tests/guards/test_keymap_owner.py b/tests/guards/test_keymap_owner.py index 2f219f28a4..9ba0cb9175 100644 --- a/tests/guards/test_keymap_owner.py +++ b/tests/guards/test_keymap_owner.py @@ -205,9 +205,10 @@ def keys(binding: Binding) -> list[str]: def test_no_app_key_is_claimed_twice_without_a_declaration(): from toad.app import ToadApp - from toad.widget_actions import ApplicationAction, YieldingKey + from toad.client.application_actions import ApplicationAction, YieldingKey + from toad.widget_actions import DeclaredWidgetActions app = {key: action for action in ApplicationAction.members_with(ApplicationAction) - if not issubclass(action, YieldingKey) for binding in action.bindings() for key in keys(binding)} + if not issubclass(action, YieldingKey) for binding in DeclaredWidgetActions.key_bindings(action) for key in keys(binding)} conflicts = [(key, app[key].__name__, f'{owner.__module__}.{owner.__qualname__}', str(binding.action)) for owner in declared_nodes() if owner is not ToadApp and not issubclass(owner, ModalScreen) for binding in Binding.make_bindings(owner.__dict__['BINDINGS']) diff --git a/tests/textual/test_application_actions_in_the_running_app.py b/tests/textual/test_application_actions_in_the_running_app.py index 6aafecb7da..f81630ce33 100644 --- a/tests/textual/test_application_actions_in_the_running_app.py +++ b/tests/textual/test_application_actions_in_the_running_app.py @@ -13,7 +13,7 @@ from support.applications import record_notifications from support.agents import peer from support.completion_record import completion_prompts -from toad.application_actions import ApplicationAction +from toad.client.application_actions import ApplicationAction from toad.preferences import SETTINGS from toad.screens.keymap import KeymapScreen from toad.screens.settings import SettingsScreen diff --git a/tests/textual/test_bus_choice.py b/tests/textual/test_bus_choice.py index 9432bbcb1b..dcf0e7346f 100644 --- a/tests/textual/test_bus_choice.py +++ b/tests/textual/test_bus_choice.py @@ -41,7 +41,7 @@ from toad.client.connection import LocalCoreConnection, RemoteCoreConnection from toad.launch_binding import NoAgent from toad.screens.bus_choice import BusAddress, BusChoices, BusPanel, BusRows -from toad.widget_actions import ApplicationAction +from toad.client.application_actions import ApplicationAction def openable(path: Path) -> OpenableProfile: diff --git a/tests/textual/test_main_menu_transfer.py b/tests/textual/test_main_menu_transfer.py index f5b285810f..11bf1033ed 100644 --- a/tests/textual/test_main_menu_transfer.py +++ b/tests/textual/test_main_menu_transfer.py @@ -15,10 +15,9 @@ from agent_comms.transport.progress import WireExportCancelled, WireExportProgress from support.applications import record_notifications from support.workspace import Workspace -from textual.widgets import Button, Input, Select from toad.screens.bus_choice import BusChoices -from toad.widget_actions import ApplicationAction +from toad.client.application_actions import ApplicationAction from toad.widgets.comms_menu import ContextMenu from toad.widgets.comms_transfer import ( CancelExportButton,