Debian Codegraph @

envisage/ui/tasks/tasks_application.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 # Standard library imports.
11 import logging
12 import os.path
13 import pickle
14
15 from traits.api import (
16 Bool,
17 Callable,
18 Directory,
19 Event,
20 HasStrictTraits,
21 Instance,
22 Int,
23 List,
24 Str,
25 Vetoable,
26 )
27 from traits.etsconfig.api import ETSConfig
28
29 # Enthought library imports.
30 from envisage.api import Application, ExtensionPoint
31
32 # Logging.
33 logger = logging.getLogger(__name__)
34
35 #: Default filename for saving layout information
36 DEFAULT_STATE_FILENAME = "application_memento"
37
38
39 class TasksApplication(Application):
40 """The entry point for an Envisage Tasks application.
41
42 This class handles the common case for Tasks applications and is
43 intended to be subclassed to modify its start/stop behavior, etc.
44
45 """
46
47 #: Extension point ID for task factories
48 TASK_FACTORIES = "envisage.ui.tasks.tasks"
49
50 #: Extension point ID for task extensions
51 TASK_EXTENSIONS = "envisage.ui.tasks.task_extensions"
52
53 #: Pickle protocol to use for persisting layout information.
54 layout_save_protocol = Int(4)
55
56 #### 'TasksApplication' interface #########################################
57
58 #: The active task window (the last one to get focus).
59 active_window = Instance("envisage.ui.tasks.task_window.TaskWindow")
60
61 #: The Pyface GUI for the application.
62 gui = Instance("pyface.i_gui.IGUI")
63
64 #: Icon for the whole application. Will be used to override all taskWindows
65 #: icons to have the same.
66 icon = Instance("pyface.image_resource.ImageResource", allow_none=True)
67
68 #: The name of the application (also used on window title bars).
69 name = Str
70
71 #: The splash screen for the application. By default, there is no splash
72 #: screen.
73 splash_screen = Instance("pyface.splash_screen.SplashScreen")
74
75 #: The directory on the local file system used to persist window layout
76 #: information.
77 state_location = Directory
78
79 #: The filename that the application uses to persist window layout
80 #: information.
81 state_filename = Str(DEFAULT_STATE_FILENAME)
82
83 #: Contributed task factories. This attribute is primarily for run-time
84 #: inspection; to instantiate a task, use the 'create_task' method.
85 task_factories = ExtensionPoint(id=TASK_FACTORIES)
86
87 #: Contributed task extensions.
88 task_extensions = ExtensionPoint(id=TASK_EXTENSIONS)
89
90 #: The list of task windows created by the application.
91 windows = List(Instance("envisage.ui.tasks.task_window.TaskWindow"))
92
93 #: The factory for creating task windows.
94 window_factory = Callable
95
96 #### Application layout ###################################################
97
98 #: The default layout for the application. If not specified, a single
99 #: window will be created with the first available task factory.
100 default_layout = List(
101 Instance("pyface.tasks.task_window_layout.TaskWindowLayout")
102 )
103
104 #: Whether to always apply the default *application level* layout when the
105 #: application is started. Even if this is True, the layout state of
106 #: individual tasks will be restored.
107 always_use_default_layout = Bool(False)
108
109 #### Application lifecycle events #########################################
110
111 #: Fired after the initial windows have been created and the GUI event loop
112 #: has been started.
113 application_initialized = Event
114
115 #: Fired immediately before the extant windows are destroyed and the GUI
116 #: event loop is terminated.
117 application_exiting = Event
118
119 #: Fired when a task window has been created.
120 window_created = Event(
121 Instance("envisage.ui.tasks.task_window_event.TaskWindowEvent")
122 )
123
124 #: Fired when a task window is opening.
125 window_opening = Event(
126 Instance("envisage.ui.tasks.task_window_event.VetoableTaskWindowEvent")
127 )
128
129 #: Fired when a task window has been opened.
130 window_opened = Event(
131 Instance("envisage.ui.tasks.task_window_event.TaskWindowEvent")
132 )
133
134 #: Fired when a task window is closing.
135 window_closing = Event(
136 Instance("envisage.ui.tasks.task_window_event.VetoableTaskWindowEvent")
137 )
138
139 #: Fired when a task window has been closed.
140 window_closed = Event(
141 Instance("envisage.ui.tasks.task_window_event.TaskWindowEvent")
142 )
143
144 #### Protected interface ##################################################
145
146 # An 'explicit' exit is when the the 'exit' method is called.
147 # An 'implicit' exit is when the user closes the last open window.
148 _explicit_exit = Bool(False)
149
150 # Application state.
151 _state = Instance(
152 "envisage.ui.tasks.tasks_application.TasksApplicationState"
153 )
154
155 ###########################################################################
156 # 'IApplication' interface.
157 ###########################################################################
158
159 def run(self):
160 """Run the application.
161
162 Returns
163 -------
164 bool
165 Whether the application started successfully (i.e., without a
166 veto).
167 """
168 # Make sure the GUI has been created (so that, if required, the splash
169 # screen is shown).
170 gui = self.gui
171
172 started = self.start()
173 if started:
174 # Create windows from the default or saved application layout.
175 self._create_windows()
176
177 # Start the GUI event loop.
178 gui.set_trait_later(self, "application_initialized", self)
179 gui.start_event_loop()
180 self.stop()
181
182 return started
183
184 ###########################################################################
185 # 'TasksApplication' interface.
186 ###########################################################################
187
188 def create_task(self, id):
189 """Creates the Task with the specified ID.
190
191 Returns
192 -------
193 pyface.tasks.task.Task
194 The new Task, or None if there is not a suitable TaskFactory.
195 """
196 # Get the factory for the task.
197 factory = self._get_task_factory(id)
198 if factory is None:
199 return None
200
201 # Create the task using suitable task extensions.
202 extensions = [
203 ext
204 for ext in self.task_extensions
205 if ext.task_id == id or not ext.task_id
206 ]
207 task = factory.create_with_extensions(extensions)
208 task.id = factory.id
209 return task
210
211 def create_window(self, layout=None, restore=True, **traits):
212 """Creates a new TaskWindow, possibly with some Tasks.
213
214 Parameters
215 ----------
216 layout : TaskWindowLayout, optional
217 The layout to use for the window. The tasks described in
218 the layout will be created and added to the window
219 automatically. If not specified, the window will contain
220 no tasks.
221
222 restore : bool, optional (default True)
223 If set, the application will restore old size and
224 positions for the window and its panes, if possible. If a
225 layout is not provided, this parameter has no effect.
226
227 **traits : dict, optional
228 Additional parameters to pass to ``window_factory()``
229 when creating the TaskWindow.
230
231 Returns
232 -------
233 envisage.ui.tasks.task_window.TaskWindow
234 The new TaskWindow.
235
236 """
237 from pyface.tasks.task_window_layout import TaskWindowLayout
238
239 from .task_window_event import TaskWindowEvent
240
241 window = self.window_factory(application=self, **traits)
242
243 # Listen for the window events.
244 window.on_trait_change(self._on_window_activated, "activated")
245 window.on_trait_change(self._on_window_opening, "opening")
246 window.on_trait_change(self._on_window_opened, "opened")
247 window.on_trait_change(self._on_window_closing, "closing")
248 window.on_trait_change(self._on_window_closed, "closed")
249
250 # Event notification.
251 self.window_created = TaskWindowEvent(window=window)
252
253 if layout:
254 # Create and add tasks.
255 for task_id in layout.get_tasks():
256 task = self.create_task(task_id)
257 if task:
258 window.add_task(task)
259 else:
260 logger.error(
261 "Missing factory for task with ID %r", task_id
262 )
263
264 # Apply a suitable layout.
265 if restore:
266 layout = self._restore_layout_from_state(layout)
267 else:
268 # Create an empty layout to set default size and position only
269 layout = TaskWindowLayout()
270
271 window.set_window_layout(layout)
272
273 return window
274
275 def exit(self, force=False):
276 """Exits the application, closing all open task windows.
277
278 Each window is sent a veto-able closing event. If any window vetoes the
279 close request, no window will be closed. Otherwise, all windows will be
280 closed and the GUI event loop will terminate.
281
282 This method is not called when the user clicks the close
283 button on a window or otherwise closes a window through his or
284 her window manager. It is only called via the File->Exit menu
285 item. It can also, of course, be called programatically.
286
287 Parameters
288 ----------
289 force : bool, optional (default False)
290 If set, windows will receive no closing events and will be
291 destroyed unconditionally. This can be useful for reliably
292 tearing down regression tests, but should be used with
293 caution.
294
295 Returns
296 -------
297 bool
298 A boolean indicating whether the application exited.
299
300 """
301 self._explicit_exit = True
302 try:
303 if not force:
304 for window in reversed(self.windows):
305 window.closing = event = Vetoable()
306 if event.veto:
307 return False
308
309 self._prepare_exit()
310 for window in reversed(self.windows):
311 window.destroy()
312 window.closed = True
313 finally:
314 self._explicit_exit = False
315 return True
316
317 ###########################################################################
318 # Protected interface.
319 ###########################################################################
320
321 def _create_windows(self):
322 """Called at startup to create TaskWindows from the default or saved
323 application layout.
324 """
325 # Build a list of TaskWindowLayouts.
326 self._load_state()
327 if (
328 self.always_use_default_layout
329 or not self._state.previous_window_layouts
330 ):
331 window_layouts = self.default_layout
332 else:
333 # Choose the stored TaskWindowLayouts, but only if all the task IDs
334 # are still valid.
335 window_layouts = self._state.previous_window_layouts
336 for layout in window_layouts:
337 for task_id in layout.get_tasks():
338 if not self._get_task_factory(task_id):
339 logger.warning(
340 "Saved application layout references "
341 "non-existent task %r. Falling back to "
342 "default application layout." % task_id
343 )
344 window_layouts = self.default_layout
345 break
346 else:
347 continue
348 break
349
350 # Create a TaskWindow for each TaskWindowLayout.
351 for window_layout in window_layouts:
352 if self.always_use_default_layout:
353 window = self.create_window(window_layout, restore=False)
354 else:
355 window = self.create_window(window_layout, restore=True)
356 window.open()
357
358 def _get_task_factory(self, id):
359 """Returns the TaskFactory with the specified ID, or None."""
360 for factory in self.task_factories:
361 if factory.id == id:
362 return factory
363 return None
364
365 def _prepare_exit(self):
366 """Called immediately before the extant windows are destroyed and the
367 GUI event loop is terminated.
368 """
369 self.application_exiting = self
370 self._save_state()
371
372 def _load_state(self):
373 """Loads saved application state, if possible."""
374 state = TasksApplicationState()
375 filename = os.path.join(self.state_location, self.state_filename)
376 if os.path.exists(filename):
377 # Attempt to unpickle the saved application state.
378 logger.debug("Loading application state from %s", filename)
379 try:
380 with open(filename, "rb") as f:
381 restored_state = pickle.load(f)
382 except Exception:
383 # If anything goes wrong, log the error and continue.
384 logger.exception("Error while restoring application state")
385 else:
386 if state.version == restored_state.version:
387 state = restored_state
388 logger.debug("Application state successfully restored")
389 else:
390 logger.warning(
391 "Discarding outdated application state: "
392 "expected version %s, got version %s",
393 state.version,
394 restored_state.version,
395 )
396 else:
397 logger.debug("No saved application state found at %s", filename)
398
399 self._state = state
400
401 def _restore_layout_from_state(self, layout):
402 """Restores an equivalent layout from saved application state."""
403 # First, see if a window layout matches exactly.
404 match = self._state.get_equivalent_window_layout(layout)
405 if match:
406 # The active task is not part of the equivalency relation, so we
407 # ensure that it is correct.
408 match.active_task = layout.get_active_task()
409 layout = match
410
411 # If that fails, at least try to restore the layout of
412 # individual tasks.
413 else:
414 layout = layout.clone_traits()
415 for i, item in enumerate(layout.items):
416 id = item if isinstance(item, str) else item.id
417 match = self._state.get_task_layout(id)
418 if match:
419 layout.items[i] = match
420
421 return layout
422
423 def _save_state(self):
424 """Saves the application state."""
425 # Grab the current window layouts.
426 window_layouts = [w.get_window_layout() for w in self.windows]
427 self._state.previous_window_layouts = window_layouts
428
429 # Attempt to pickle the application state.
430 filename = os.path.join(self.state_location, self.state_filename)
431 logger.debug("Saving application state to %s", filename)
432 try:
433 with open(filename, "wb") as f:
434 pickle.dump(self._state, f, protocol=self.layout_save_protocol)
435 except Exception:
436 # If anything goes wrong, log the error and continue.
437 logger.exception("Error while saving application state")
438 else:
439 logger.debug("Application state successfully saved")
440
441 def _initialize_application_home(self):
442 """Initialize the application directories."""
443 # Extend the base class method to ensure the state directory exists.
444 super()._initialize_application_home()
445
446 state_location = self.state_location
447 logger.debug(f"Creating folder for tasks state: {state_location}")
448 os.makedirs(state_location, mode=0o700, exist_ok=True)
449
450 #### Trait initializers ###################################################
451
452 def _window_factory_default(self):
453 from envisage.ui.tasks.task_window import TaskWindow
454
455 return TaskWindow
456
457 def _default_layout_default(self):
458 from pyface.tasks.task_window_layout import TaskWindowLayout
459
460 window_layout = TaskWindowLayout()
461 if self.task_factories:
462 window_layout.items = [self.task_factories[0].id]
463 return [window_layout]
464
465 def _gui_default(self):
466 from pyface.gui import GUI
467
468 return GUI(splash_screen=self.splash_screen)
469
470 def _state_location_default(self):
471 state_location = os.path.join(self.home, "tasks", ETSConfig.toolkit)
472 logger.debug("Tasks state location is %s", state_location)
473
474 return state_location
475
476 #### Trait change handlers ################################################
477
478 def _on_window_activated(self, window, trait_name, event):
479 self.active_window = window
480
481 def _on_window_opening(self, window, trait_name, event):
482 from .task_window_event import VetoableTaskWindowEvent
483
484 # Event notification.
485 self.window_opening = window_event = VetoableTaskWindowEvent(
486 window=window
487 )
488
489 if window_event.veto:
490 event.veto = True
491
492 def _on_window_opened(self, window, trait_name, event):
493 from .task_window_event import TaskWindowEvent
494
495 self.windows.append(window)
496
497 # Event notification.
498 self.window_opened = TaskWindowEvent(window=window)
499
500 def _on_window_closing(self, window, trait_name, event):
501 from .task_window_event import VetoableTaskWindowEvent
502
503 # Event notification.
504 self.window_closing = window_event = VetoableTaskWindowEvent(
505 window=window
506 )
507
508 if window_event.veto:
509 event.veto = True
510 else:
511 # Store the layout of the window.
512 window_layout = window.get_window_layout()
513 self._state.push_window_layout(window_layout)
514
515 # If we're exiting implicitly and this is the last window, save
516 # state, because we won't get another chance.
517 if len(self.windows) == 1 and not self._explicit_exit:
518 self._prepare_exit()
519
520 def _on_window_closed(self, window, trait_name, event):
521 from .task_window_event import TaskWindowEvent
522
523 self.windows.remove(window)
524
525 # Event notification.
526 self.window_closed = TaskWindowEvent(window=window)
527
528 # Was this the last window?
529 if len(self.windows) == 0:
530 self.gui.stop_event_loop()
531
532
533 class TasksApplicationState(HasStrictTraits):
534 """A class used internally by TasksApplication for saving and restoring
535 application state.
536 """
537
538 # TaskWindowLayouts for the windows extant at application
539 # exit. Only used if 'always_use_default_layout' is disabled.
540 previous_window_layouts = List(
541 Instance("pyface.tasks.task_window_layout.TaskWindowLayout")
542 )
543
544 # A list of TaskWindowLayouts accumulated throughout the application's
545 # lifecycle.
546 window_layouts = List(
547 Instance("pyface.tasks.task_window_layout.TaskWindowLayout")
548 )
549
550 # The "version" for the state data. This should be incremented whenever a
551 # backwards incompatible change is made to this class or any of the layout
552 # classes. This ensures that loading application state is always safe.
553 version = Int(1)
554
555 def get_equivalent_window_layout(self, window_layout):
556 """Gets an equivalent TaskWindowLayout, if there is one."""
557 for layout in self.window_layouts:
558 if layout.is_equivalent_to(window_layout):
559 return layout
560 return None
561
562 def get_task_layout(self, task_id):
563 """Gets a TaskLayout with the specified ID, there is one."""
564 for window_layout in self.window_layouts:
565 for layout in window_layout.items:
566 if layout.id == task_id:
567 return layout
568 return None
569
570 def push_window_layout(self, window_layout):
571 """Merge a TaskWindowLayout into the accumulated list."""
572 self.window_layouts = [
573 layout
574 for layout in self.window_layouts
575 if not layout.is_equivalent_to(window_layout)
576 ]
577 self.window_layouts.insert(0, window_layout)