Debian Codegraph @

src/app_model/backends/qt/_qaction.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 from typing import TYPE_CHECKING, ClassVar
5 from weakref import WeakValueDictionary
6
7 from qtpy.QtGui import QKeySequence
8
9 from app_model import Application
10 from app_model.expressions import Expr
11 from app_model.types import ToggleRule
12
13 from ._qkeymap import QKeyBindingSequence
14 from ._util import to_qicon
15
16 if TYPE_CHECKING:
17 from collections.abc import Mapping
18
19 from PyQt6.QtGui import QAction
20 from qtpy.QtCore import QObject
21 from typing_extensions import Self
22
23 from app_model.types import CommandRule, MenuItem
24 else:
25 from qtpy.QtWidgets import QAction
26
27
28 class QCommandAction(QAction):
29 """Base QAction for a command id. Can execute the command.
30
31 Parameters
32 ----------
33 command_id : str
34 Command ID.
35 app : Application | str
36 Application instance or name of application instance.
37 parent : QObject | None
38 Optional parent widget, by default None
39 """
40
41 def __init__(
42 self,
43 command_id: str,
44 app: Application | str,
45 parent: QObject | None = None,
46 ) -> None:
47 super().__init__(parent)
48 self._app = Application.get_or_create(app) if isinstance(app, str) else app
49 self._command_id = command_id
50 self.setObjectName(command_id)
51 self._keybinding_tooltip = ""
52 if kb := self._app.keybindings.get_keybinding(command_id):
53 self.setShortcut(QKeyBindingSequence(kb.keybinding))
54 self._keybinding_tooltip = f"({kb.keybinding.to_text()})"
55 self.triggered.connect(self._on_triggered)
56
57 def _update_keybinding(self) -> None:
58 shortcut = self.shortcut()
59 if kb := self._app.keybindings.get_keybinding(self._command_id):
60 self.setShortcut(QKeyBindingSequence(kb.keybinding))
61 self._keybinding_tooltip = f"({kb.keybinding.to_text()})"
62 elif not shortcut.isEmpty():
63 self.setShortcut(QKeySequence())
64 self._keybinding_tooltip = ""
65
66 def _on_triggered(self, checked: bool) -> None:
67 # execute_command returns a Future, for the sake of eventually being
68 # asynchronous without breaking the API. For now, we call result()
69 # to raise any exceptions.
70 self._app.commands.execute_command(self._command_id).result()
71
72
73 class QCommandRuleAction(QCommandAction):
74 """QAction for a CommandRule.
75
76 Parameters
77 ----------
78 command_rule : CommandRule
79 `CommandRule` instance to create an action for.
80 app : Application | str
81 Application instance or name of application instance.
82 parent : QObject | None
83 Optional parent widget, by default None
84 use_short_title : bool
85 If True, use the `short_title` of the command rule, if it exists.
86 """
87
88 def __init__(
89 self,
90 command_rule: CommandRule,
91 app: Application | str,
92 parent: QObject | None = None,
93 *,
94 use_short_title: bool = False,
95 ) -> None:
96 super().__init__(command_rule.id, app, parent)
97 self._cmd_rule = command_rule
98 self._tooltip = command_rule.tooltip or ""
99 if use_short_title and command_rule.short_title:
100 self.setText(command_rule.short_title) # pragma: no cover
101 else:
102 self.setText(command_rule.title)
103 if command_rule.icon:
104 self.setIcon(to_qicon(command_rule.icon))
105 self.setIconVisibleInMenu(command_rule.icon_visible_in_menu)
106 if command_rule.status_tip:
107 self.setStatusTip(command_rule.status_tip)
108 if command_rule.toggled is not None:
109 self.setCheckable(True)
110 self._refresh()
111 tooltip_with_keybinding = f"{self._tooltip} {self._keybinding_tooltip}".rstrip()
112 self.setToolTip(tooltip_with_keybinding)
113
114 def setText(self, text: str | None) -> None:
115 super().setText(text)
116 self._tooltip = self._tooltip or text or ""
117
118 def _update_keybinding(self) -> None:
119 super()._update_keybinding()
120 tooltip_with_keybinding = f"{self._tooltip} {self._keybinding_tooltip}".rstrip()
121 self.setToolTip(tooltip_with_keybinding)
122
123 def update_from_context(self, ctx: Mapping[str, object]) -> None:
124 """Update the enabled state of this menu item from `ctx`."""
125 self.setEnabled(expr.eval(ctx) if (expr := self._cmd_rule.enablement) else True)
126 if expr2 := self._cmd_rule.toggled:
127 if isinstance(expr2, Expr) or (
128 isinstance(expr2, ToggleRule) and (expr2 := expr2.condition)
129 ):
130 self.setChecked(expr2.eval(ctx))
131
132 def _refresh(self) -> None:
133 if isinstance(self._cmd_rule.toggled, ToggleRule):
134 if get_current := self._cmd_rule.toggled.get_current:
135 _current = self._app.injection_store.inject(
136 get_current, on_unresolved_required_args="ignore"
137 )
138 self.setChecked(_current())
139
140
141 class QMenuItemAction(QCommandRuleAction):
142 """QAction for a MenuItem.
143
144 Mostly the same as a `CommandRuleAction`, but aware of the `menu_item.when` clause
145 to toggle visibility.
146
147 Parameters
148 ----------
149 menu_item : MenuItem
150 `MenuItem` instance to create an action for.
151 app : Application | str
152 Application instance or name of application instance.
153 parent : QObject | None
154 Optional parent widget, by default None
155 """
156
157 _cache: ClassVar[WeakValueDictionary[tuple[int, int], Self]] = WeakValueDictionary()
158
159 def __init__(
160 self,
161 menu_item: MenuItem,
162 app: Application | str,
163 parent: QObject | None = None,
164 ) -> None:
165 super().__init__(menu_item.command, app, parent)
166 self._menu_item = menu_item
167 with contextlib.suppress(NameError):
168 self.update_from_context(self._app.context)
169
170 @staticmethod
171 def _cache_key(app: Application, menu_item: MenuItem) -> tuple[int, int]:
172 return (id(app), hash(menu_item))
173
174 @classmethod
175 def create(
176 cls,
177 menu_item: MenuItem,
178 app: Application | str,
179 parent: QObject | None = None,
180 ) -> Self:
181 """Create a new QMenuItemAction for the given menu item.
182
183 Prefer this method over `__init__` to ensure that the cache is used,
184 so that:
185
186 ```python
187 a1 = QMenuItemAction.create(action, full_app)
188 a2 = QMenuItemAction.create(action, full_app)
189 a1 is a2 # True
190 ```
191 """
192 app = Application.get_or_create(app) if isinstance(app, str) else app
193 cache_key = QMenuItemAction._cache_key(app, menu_item)
194 if cache_key in cls._cache:
195 res = cls._cache[cache_key]
196 res._update_keybinding()
197 res.setParent(parent)
198 return res
199
200 cls._cache[cache_key] = obj = cls(menu_item, app, parent)
201 return obj
202
203 def update_from_context(self, ctx: Mapping[str, object]) -> None:
204 """Update the enabled/visible state of this menu item from `ctx`."""
205 super().update_from_context(ctx)
206 self.setVisible(expr.eval(ctx) if (expr := self._menu_item.when) else True)
207
208 def __repr__(self) -> str:
209 name = self.__class__.__name__
210 return f"{name}({self._menu_item!r}, app={self._app.name!r})"