Debian Codegraph @

envisage/ui/action/abstract_action_manager_builder.py

raw
1 # (C) Copyright 2007-2025 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10 """ Builds menus, menu bars and tool bars from action sets. """
11
12
13 # Enthought library imports.
14 from pyface.action.api import ActionManager, MenuManager
15 from traits.api import HasTraits, Instance, List, observe, provides
16
17 # Local imports.
18 from .action_set import ActionSet
19 from .action_set_manager import ActionSetManager
20 from .group import Group
21 from .i_action_manager_builder import IActionManagerBuilder
22
23
24 @provides(IActionManagerBuilder)
25 class AbstractActionManagerBuilder(HasTraits):
26 """Builds menus, menu bars and tool bars from action sets.
27
28 This class *must* be subclassed, and the following methods implemented::
29
30 _create_action
31 _create_group
32 _create_menu_manager
33
34 """
35
36 #### 'IActionManagerBuilder' interface ####################################
37
38 # The action sets used by the builder.
39 action_sets = List(ActionSet)
40
41 #### Private interface ####################################################
42
43 _action_set_manager = Instance(ActionSetManager, ())
44
45 ###########################################################################
46 # 'IActionManagerBuilder' interface.
47 ###########################################################################
48
49 def create_menu_bar_manager(self, root):
50 """Create a menu bar manager from the builder's action sets."""
51
52 menu_bar_manager = self._create_menu_bar_manager()
53
54 self.initialize_action_manager(menu_bar_manager, root)
55
56 return menu_bar_manager
57
58 # fixme: V3 refactor loooong (and confusing) method!
59 def create_tool_bar_managers(self, root):
60 """Creates all tool bar managers from the builder's action sets."""
61
62 ########################################
63 # New style (i.e multi) tool bars.
64 ########################################
65
66 tool_bar_managers = []
67 for tool_bar in self._action_set_manager.get_tool_bars(root):
68 # Get all of the groups for the tool bar.
69 groups = []
70 for group in self._action_set_manager.get_groups(root):
71 if group.path.startswith("%s/%s" % (root, tool_bar.name)):
72 group.path = "/".join(group.path.split("/")[1:])
73 groups.append(group)
74
75 # Get all of the actions for the tool bar.
76 actions = []
77 for action in self._action_set_manager.get_actions(root):
78 if action.path.startswith("%s/%s" % (root, tool_bar.name)):
79 action.path = "/".join(action.path.split("/")[1:])
80 actions.append(action)
81
82 # We don't add the tool bar if it is empty!
83 if len(groups) + len(actions) > 0:
84 tool_bar_manager = self._create_tool_bar_manager(tool_bar)
85
86 # Add all groups and menus.
87 self._add_groups_and_menus(tool_bar_manager, groups)
88
89 # Add all of the actions ot the menu manager.
90 self._add_actions(tool_bar_manager, actions)
91
92 # Include the tool bar!
93 tool_bar_managers.append(tool_bar_manager)
94
95 ######################################################################
96 # Scoop up old groups and actions for the old style (single) tool bar.
97 ######################################################################
98
99 # Get all of the groups for the tool bar.
100 groups = []
101 for group in self._action_set_manager.get_groups(root):
102 if group.path == root:
103 groups.append(group)
104
105 # Get all of the actions for the tool bar.
106 actions = []
107 for action in self._action_set_manager.get_actions(root):
108 if action.path == root:
109 actions.append(action)
110
111 # We don't add the tool bar if it is empty!
112 if len(groups) + len(actions) > 0:
113 from .tool_bar import ToolBar
114
115 tool_bar_manager = self._create_tool_bar_manager(
116 ToolBar(name="Tool Bar", path=root, _action_set_=None)
117 )
118
119 # Add all groups and menus.
120 self._add_groups_and_menus(tool_bar_manager, groups)
121
122 # Add all of the actions ot the menu manager.
123 self._add_actions(tool_bar_manager, actions)
124
125 # Include the tool bar!
126 tool_bar_managers.insert(0, tool_bar_manager)
127
128 return tool_bar_managers
129
130 def initialize_action_manager(self, action_manager, root):
131 """Initialize an action manager from the builder's action sets."""
132
133 # Get all of the groups and menus for the specified root (for toolbars
134 # there will **only** be groups).
135 groups_and_menus = self._action_set_manager.get_groups(root)
136 groups_and_menus.extend(self._action_set_manager.get_menus(root))
137
138 # Add all groups and menus.
139 self._add_groups_and_menus(action_manager, groups_and_menus)
140
141 # Get all actions for the specified root.
142 actions = self._action_set_manager.get_actions(root)
143
144 # Add all of the actions ot the menu manager.
145 self._add_actions(action_manager, actions)
146
147 ###########################################################################
148 # Protected 'AbstractActionManagerBuilder' interface.
149 ###########################################################################
150
151 def _create_action(self, action_definition):
152 """Creates an action implementation from a definition."""
153
154 raise NotImplementedError
155
156 def _create_group(self, group_definition):
157 """Creates a group implementation from a definition."""
158
159 raise NotImplementedError
160
161 def _create_menu_manager(self, menu_manager_definition):
162 """Creates a menu manager implementation from a definition."""
163
164 raise NotImplementedError
165
166 def _create_menu_bar_manager(self):
167 """Creates a menu bar manager implementation."""
168
169 raise NotImplementedError
170
171 def _create_tool_bar_manager(self, tool_bar_definition):
172 """Creates a tool bar manager implementation from a definition."""
173
174 raise NotImplementedError
175
176 ###########################################################################
177 # Private interface.
178 ###########################################################################
179
180 #### Trait change handler #################################################
181
182 @observe("action_sets")
183 def _update_action_sets_on_manager(self, event):
184 """Static trait change handler."""
185 new = event.new
186 self._action_set_manager.action_sets = new
187
188 #### Methods ##############################################################
189
190 def _add_actions(self, action_manager, actions):
191 """Add the specified actions to an action manager."""
192
193 while len(actions) > 0:
194 start = len(actions)
195
196 for action in actions[:]:
197 # Resolve the action's path to find the action manager that it
198 # should be added to.
199 #
200 # If any of the menus in path are missing then this creates
201 # them automatically (think 'mkdirs'!).
202 target = self._make_submenus(action_manager, action.path)
203
204 # Attempt to place the action.
205 #
206 # If the action needs to be placed 'before' or 'after' some
207 # other action, but the other action has not yet been added
208 # then we will try again later!
209 if self._add_action(target, action):
210 actions.remove(action)
211
212 end = len(actions)
213
214 # If we didn't succeed in placing *any* actions then we must have a
215 # problem!
216 if start == end:
217 raise ValueError("Could not place %s" % actions)
218
219 def _add_action(self, action_manager, action):
220 """Add an action to an action manager.
221
222 Return True if the action was added successfully.
223
224 Return False if the action needs to be placed 'before' or 'after' some
225 other action, but the other action has not yet been added.
226
227 """
228
229 group = self._find_group(action_manager, action.group)
230 if group is None:
231 msg = "No such group (%s) for %s" % (action.group, action)
232 raise ValueError(msg)
233
234 if len(action.before) > 0:
235 item = group.find(action.before)
236 if item is None:
237 return False
238
239 index = group.items.index(item)
240
241 elif len(action.after) > 0:
242 item = group.find(action.after)
243 if item is None:
244 return False
245
246 index = group.items.index(item) + 1
247
248 else:
249 index = len(group.items)
250
251 group.insert(index, self._create_action(action))
252
253 return True
254
255 def _add_groups_and_menus(self, action_manager, groups_and_menus):
256 """Add the specified groups and menus to an action manager."""
257
258 # The reason we put the groups and menus together is that as we iterate
259 # over the list trying to add them, we might need to add a group before
260 # we can add a menu and we might need to add a menu before we can add a
261 # group! Hence, we take multiple passes over the list and we only barf
262 # if, in any single iteration, we cannot add anything.
263 while len(groups_and_menus) > 0:
264 start = len(groups_and_menus)
265
266 for item in groups_and_menus[:]:
267 # Resolve the path to find the menu manager that we are about
268 # to add the sub-menu or group to.
269 target = self._find_action_manager(action_manager, item.path)
270 if target is not None:
271 # Attempt to place a group.
272 if isinstance(item, Group):
273 if self._add_group(target, item):
274 groups_and_menus.remove(item)
275
276 # Attempt to place a menu.
277 elif self._add_menu(target, item):
278 groups_and_menus.remove(item)
279
280 end = len(groups_and_menus)
281
282 # If we didn't succeed in adding *any* menus or groups then we
283 # must have a problem!
284 if start == end:
285 raise ValueError("Could not place %s" % groups_and_menus)
286
287 def _add_group(self, action_manager, group):
288 """Add a group to an action manager.
289
290 Return True if the group was added successfully.
291
292 Return False if the group needs to be placed 'before' or 'after' some
293 other group, but the other group has not yet been added.
294
295 """
296
297 # Does the group already exist in the menu? If not then add it,
298 # otherwise do nothing.
299 if action_manager.find_group(group.id) is None:
300 if len(group.before) > 0:
301 item = action_manager.find_group(group.before)
302 if item is None:
303 return False
304
305 index = action_manager.groups.index(item)
306
307 elif len(group.after) > 0:
308 item = action_manager.find_group(group.after)
309 if item is None:
310 return False
311
312 index = action_manager.groups.index(item) + 1
313
314 else:
315 # If the menu manager has an 'additions' group then make sure
316 # that it is always the last one! In Pyface, the 'additions'
317 # groups is created by default, so unless someone has
318 # explicitly removed it, it *will* be there!
319 additions = action_manager.find_group("additions")
320 if additions is not None:
321 index = action_manager.groups.index(additions)
322
323 else:
324 index = len(action_manager.groups)
325
326 action_manager.insert(index, self._create_group(group))
327
328 return True
329
330 def _add_menu(self, menu_manager, menu):
331 """Add a menu manager to a errr, menu manager.
332
333 Return True if the menu was added successfully.
334
335 Return False if the menu needs to be placed 'before' or 'after' some
336 other item, but the other item has not yet been added.
337
338 """
339
340 group = self._find_group(menu_manager, menu.group)
341 if group is None:
342 return False
343
344 if len(menu.before) > 0:
345 item = group.find(menu.before)
346 if item is None:
347 return False
348
349 index = group.items.index(item)
350
351 elif len(menu.after) > 0:
352 item = group.find(menu.after)
353 if item is None:
354 return False
355
356 index = group.items.index(item) + 1
357
358 else:
359 index = len(group.items)
360
361 # If the menu does *not* already exist in the group then add it.
362 menu_item = group.find(menu.id)
363 if menu_item is None:
364 group.insert(index, self._create_menu_manager(menu))
365
366 # Otherwise, add all of the new menu's groups to the existing one.
367 else:
368 for group in menu.groups:
369 self._add_group(menu_item, group)
370
371 return True
372
373 def _find_group(self, action_manager, id):
374 """Find the group with the specified ID."""
375
376 if len(id) > 0:
377 group = action_manager.find_group(id)
378
379 else:
380 group = action_manager.find_group("additions")
381
382 return group
383
384 def _find_action_manager(self, action_manager, path):
385 """Return the action manager at the specified path.
386
387 Returns None if the action manager cannot be found.
388
389 """
390
391 components = path.split("/")
392 if len(components) == 1:
393 action_manager = action_manager
394
395 else:
396 action_manager = action_manager.find_item("/".join(components[1:]))
397
398 return action_manager
399
400 def _make_submenus(self, menu_manager, path):
401 """Retutn the menu manager identified by the path.
402
403 Make any intermediate menu-managers that are missing.
404
405 """
406
407 components = path.split("/")
408
409 # We skip the first component, because if the path is of length 1, then
410 # the target menu manager is the menu manager passed in.
411 for component in components[1:]:
412 item = menu_manager.find_item(component)
413
414 # If the menu manager does *not* contain an item with this ID then
415 # create a sub-menu automatically.
416 if item is None:
417 item = MenuManager(id=component, name=component)
418 menu_manager.append(item)
419
420 # If the menu manager *does* already contain an item with this ID
421 # then make sure it is a menu and not an action!
422 elif not isinstance(item, ActionManager):
423 msg = "%s is not a menu in path %s" % (item, path)
424 raise ValueError(msg)
425
426 menu_manager = item
427
428 return menu_manager