Debian Codegraph @

src/app_model/backends/qt/_qmenu.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 from collections.abc import Collection, Iterable, Mapping, Sequence
5 from typing import TYPE_CHECKING, cast
6
7 from qtpy.QtWidgets import QApplication, QMenu, QMenuBar, QToolBar
8
9 from app_model import Application
10 from app_model.types import SubmenuItem
11
12 from ._qaction import QCommandRuleAction, QMenuItemAction
13 from ._util import to_qicon
14
15 try:
16 from qtpy import QT6
17 except ImportError:
18 QT6 = False
19
20 if TYPE_CHECKING:
21 from qtpy.QtWidgets import QAction, QWidget
22
23
24 class QModelMenu(QMenu):
25 """QMenu for a menu_id in an `app_model` MenusRegistry.
26
27 Parameters
28 ----------
29 menu_id : str
30 Menu ID to look up in the registry.
31 app : Application | str
32 Application instance or name of application instance.
33 title : str | None
34 Optional title for the menu, by default None
35 parent : QWidget | None
36 Optional parent widget, by default None
37 """
38
39 def __init__(
40 self,
41 menu_id: str,
42 app: Application | str,
43 title: str | None = None,
44 parent: QWidget | None = None,
45 ) -> None:
46 QMenu.__init__(self, parent)
47
48 # NOTE: code duplication with QModelToolBar, but Qt mixins and multiple
49 # inheritance are problematic for some versions of Qt, and for typing
50 assert isinstance(menu_id, str), f"Expected str, got {type(menu_id)!r}"
51 self._menu_id = menu_id
52 self._app = Application.get_or_create(app) if isinstance(app, str) else app
53 self.setObjectName(menu_id)
54 self.rebuild()
55 self._app.menus.menus_changed.connect(self._on_registry_changed)
56 self.destroyed.connect(self._disconnect)
57 # ----------------------
58
59 if title is not None:
60 self.setTitle(title)
61 self.aboutToShow.connect(self._on_about_to_show)
62
63 def findAction(self, object_name: str) -> QAction | QModelMenu | None:
64 """Find an action by its ObjectName.
65
66 Parameters
67 ----------
68 object_name : str
69 Action ID to find. Note that `QCommandAction` have `ObjectName` set
70 to their `command.id`
71 """
72 return _find_action(self.actions(), object_name)
73
74 def update_from_context(self, ctx: Mapping[str, object]) -> None:
75 """Update the enabled/visible state of each menu item with `ctx`.
76
77 See `app_model.expressions` for details on expressions.
78
79 Parameters
80 ----------
81 ctx : Mapping
82 A namespace that will be used to `eval()` the `'enablement'` and
83 `'when'` expressions provided for each action in the menu.
84 *ALL variables used in these expressions must either be present in
85 the `ctx` dict, or be builtins*.
86 """
87 _update_from_context(self.actions(), ctx)
88
89 def rebuild(
90 self, include_submenus: bool = True, exclude: Collection[str] | None = None
91 ) -> None:
92 """Rebuild menu by looking up self._menu_id in menu_registry."""
93 _rebuild(
94 menu=self,
95 app=self._app,
96 menu_id=self._menu_id,
97 include_submenus=include_submenus,
98 exclude=exclude,
99 )
100
101 def _on_about_to_show(self) -> None:
102 for action in self.actions():
103 if isinstance(action, QCommandRuleAction):
104 action._refresh()
105
106 def _disconnect(self) -> None:
107 self._app.menus.menus_changed.disconnect(self._on_registry_changed)
108
109 def _on_registry_changed(self, changed_ids: set[str]) -> None:
110 if self._menu_id in changed_ids:
111 # if this (sub)menu has been removed from the registry,
112 # we may hit a RuntimeError when trying to rebuild it.
113 with contextlib.suppress(RuntimeError):
114 self.rebuild()
115
116
117 class QModelSubmenu(QModelMenu):
118 """QMenu for a menu_id in an `app_model` MenusRegistry.
119
120 Parameters
121 ----------
122 submenu : SubmenuItem
123 SubmenuItem for which to create a QMenu.
124 app : Application | str
125 Application instance or name of application instance.
126 parent : QWidget | None
127 Optional parent widget, by default None
128 """
129
130 def __init__(
131 self,
132 submenu: SubmenuItem,
133 app: Application | str,
134 parent: QWidget | None = None,
135 ) -> None:
136 assert isinstance(submenu, SubmenuItem), f"Expected str, got {type(submenu)!r}"
137 self._submenu = submenu
138 super().__init__(
139 menu_id=submenu.submenu, app=app, title=submenu.title, parent=parent
140 )
141 if submenu.icon:
142 self.setIcon(to_qicon(submenu.icon))
143
144 def update_from_context(self, ctx: Mapping[str, object]) -> None:
145 """Update the enabled state of this menu item from `ctx`."""
146 super().update_from_context(ctx)
147 self.setEnabled(expr.eval(ctx) if (expr := self._submenu.enablement) else True)
148 # TODO: ... visibility needs to be controlled at the level of placement
149 # in the submenu. consider only using the `when` expression
150 # self.setVisible(expr.eval(ctx) if (expr := self._submenu.when) else True)
151
152
153 class QModelToolBar(QToolBar):
154 """QToolBar that is built from a list of model menu ids.
155
156 Parameters
157 ----------
158 menu_id : str
159 Menu ID to look up in the registry.
160 app : Application | str
161 Application instance or name of application instance.
162 exclude : Collection[str] | None
163 Optional list of menu ids to exclude from the toolbar, by default None
164 title : str | None
165 Optional title for the menu, by default None
166 parent : QWidget | None
167 Optional parent widget, by default None
168 """
169
170 def __init__(
171 self,
172 menu_id: str,
173 app: Application | str,
174 *,
175 exclude: Collection[str] | None = None,
176 title: str | None = None,
177 parent: QWidget | None = None,
178 ) -> None:
179 self._exclude = exclude
180 QToolBar.__init__(self, parent)
181
182 # NOTE: code duplication with QModelMenu, but Qt mixins and multiple
183 # inheritance are problematic for some versions of Qt, and for typing
184 assert isinstance(menu_id, str), f"Expected str, got {type(menu_id)!r}"
185 self._menu_id = menu_id
186 self._app = Application.get_or_create(app) if isinstance(app, str) else app
187 self.setObjectName(menu_id)
188 self.rebuild()
189 self._app.menus.menus_changed.connect(self._on_registry_changed)
190 self.destroyed.connect(self._disconnect)
191 # ----------------------
192
193 if title is not None:
194 self.setWindowTitle(title)
195
196 def addMenu(self, menu: QMenu) -> None:
197 """No-op for toolbar."""
198
199 def findAction(self, object_name: str) -> QAction | QModelMenu | None:
200 """Find an action by its ObjectName.
201
202 Parameters
203 ----------
204 object_name : str
205 Action ID to find. Note that `QCommandAction` have `ObjectName` set
206 to their `command.id`
207 """
208 return _find_action(self.actions(), object_name)
209
210 def update_from_context(self, ctx: Mapping[str, object]) -> None:
211 """Update the enabled/visible state of each menu item with `ctx`.
212
213 See `app_model.expressions` for details on expressions.
214
215 Parameters
216 ----------
217 ctx : Mapping
218 A namespace that will be used to `eval()` the `'enablement'` and
219 `'when'` expressions provided for each action in the menu.
220 *ALL variables used in these expressions must either be present in
221 the `ctx` dict, or be builtins*.
222 """
223 _update_from_context(self.actions(), ctx)
224
225 def rebuild(
226 self, include_submenus: bool = True, exclude: Collection[str] | None = None
227 ) -> None:
228 """Rebuild toolbar by looking up self._menu_id in menu_registry."""
229 _rebuild(
230 menu=self,
231 app=self._app,
232 menu_id=self._menu_id,
233 include_submenus=include_submenus,
234 exclude=self._exclude if exclude is None else exclude,
235 )
236
237 def _disconnect(self) -> None:
238 self._app.menus.menus_changed.disconnect(self._on_registry_changed)
239
240 def _on_registry_changed(self, changed_ids: set[str]) -> None:
241 if self._menu_id in changed_ids:
242 self.rebuild()
243
244
245 class QModelMenuBar(QMenuBar):
246 """QMenuBar that is built from a list of model menu ids.
247
248 Parameters
249 ----------
250 menus : Mapping[str, str] | Sequence[str | tuple[str, str]]
251 A mapping of menu ids to menu titles or a sequence of menu ids.
252 app : Application | str
253 Application instance or name of application instance.
254 parent : QWidget | None
255 Optional parent widget, by default None
256 """
257
258 def __init__(
259 self,
260 menus: Mapping[str, str] | Sequence[str | tuple[str, str]],
261 app: Application | str,
262 parent: QWidget | None = None,
263 ) -> None:
264 super().__init__(parent)
265
266 menu_items = menus.items() if isinstance(menus, Mapping) else menus
267 for item in menu_items:
268 id_, title = item if isinstance(item, tuple) else (item, item.title())
269 self.addMenu(QModelMenu(id_, app, title, self))
270
271 def update_from_context(self, ctx: Mapping[str, object]) -> None:
272 """Update the enabled/visible state of each menu item with `ctx`.
273
274 See `app_model.expressions` for details on expressions.
275
276 Parameters
277 ----------
278 ctx : Mapping
279 A namespace that will be used to `eval()` the `'enablement'` and
280 `'when'` expressions provided for each action in the menu.
281 *ALL variables used in these expressions must either be present in
282 the `ctx` dict, or be builtins*.
283 """
284 _update_from_context(self.actions(), ctx)
285
286
287 def _rebuild(
288 menu: QMenu | QToolBar,
289 app: Application,
290 menu_id: str,
291 include_submenus: bool = True,
292 exclude: Collection[str] | None = None,
293 ) -> None:
294 """Rebuild menu by looking up `menu` in `Application`'s menu_registry."""
295 actions = menu.actions()
296 for action in actions:
297 menu.removeAction(action)
298
299 _exclude = exclude or set()
300
301 groups = list(app.menus.iter_menu_groups(menu_id))
302 n_groups = len(groups)
303 qapp = QApplication.instance()
304 for n, group in enumerate(groups):
305 for item in group:
306 if isinstance(item, SubmenuItem):
307 if include_submenus:
308 submenu = QModelSubmenu(item, app, parent=menu)
309 cast("QMenu", menu).addMenu(submenu)
310 elif item.command.id not in _exclude:
311 # use QApplication instance as parent for actions
312 # because we use action singleton, and actions
313 # are not related to any window.
314 action = QMenuItemAction.create(item, app=app, parent=qapp)
315 menu.addAction(action)
316 if n < n_groups - 1:
317 menu.addSeparator()
318
319
320 def _update_from_context(actions: Iterable[QAction], ctx: Mapping[str, object]) -> None:
321 """Update the enabled/visible state of each menu item with `ctx`.
322
323 See `app_model.expressions` for details on expressions.
324
325 Parameters
326 ----------
327 actions : Iterable[QAction]
328 Actions to update.
329 ctx : Mapping
330 A namespace that will be used to `eval()` the `'enablement'` and
331 `'when'` expressions provided for each action in the menu.
332 *ALL variables used in these expressions must either be present in
333 the `ctx` dict, or be builtins*.
334 """
335 try:
336 for action in actions:
337 if isinstance(action, QMenuItemAction):
338 action.update_from_context(ctx)
339 elif isinstance(menu := action.menu(), QModelMenu):
340 menu.update_from_context(ctx)
341 except AttributeError as e: # pragma: no cover
342 raise AttributeError(f"This version of Qt is not supported: {e}") from e
343
344
345 def _find_action(actions: Iterable[QAction], object_name: str) -> QAction | None:
346 return next((a for a in actions if a.objectName() == object_name), None)