Debian Codegraph @

envisage/application.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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 """ An extensible, pluggable, application. """
11
12
13 # Standard library imports.
14 import logging
15 import os
16
17 # Enthought library imports.
18 from apptools.preferences.api import (
19 IPreferences,
20 ScopedPreferences,
21 set_default_preferences,
22 )
23 from traits.api import (
24 Delegate,
25 Event,
26 HasTraits,
27 Instance,
28 observe,
29 provides,
30 Str,
31 VetoableEvent,
32 )
33 from traits.etsconfig.api import ETSConfig
34
35 from .application_event import ApplicationEvent
36
37 # Local imports.
38 from .i_application import IApplication
39 from .i_extension_registry import IExtensionRegistry
40 from .i_import_manager import IImportManager
41 from .i_plugin_manager import IPluginManager
42 from .i_service_registry import IServiceRegistry
43 from .import_manager import ImportManager
44
45 # Logging.
46 logger = logging.getLogger(__name__)
47
48
49 @provides(IApplication)
50 class Application(HasTraits):
51 """An extensible, pluggable, application.
52
53 This class handles the common case for non-GUI applications, and it is
54 intended to be subclassed to change start/stop behaviour etc.
55
56 """
57
58 #### 'IApplication' interface #############################################
59
60 #: The application's globally unique identifier.
61 id = Str
62
63 #: The name of a directory (created for you) to which the application can
64 #: read and write non-user accessible data, i.e. configuration information,
65 #: preferences, etc.
66 home = Str
67
68 #: The name of a directory (created for you upon access) to which the
69 #: application can read and write user-accessible data, e.g. projects
70 #: created by the user.
71 user_data = Str
72
73 #: The root preferences node.
74 preferences = Instance(IPreferences)
75
76 #### Events ####
77
78 #: Fired when the application is starting.
79 starting = VetoableEvent(ApplicationEvent)
80
81 #: Fired when all plugins have been started.
82 started = Event(ApplicationEvent)
83
84 #: Fired when the application is stopping.
85 stopping = VetoableEvent(ApplicationEvent)
86
87 #: Fired when all plugins have been stopped.
88 stopped = Event(ApplicationEvent)
89
90 #### 'IPluginManager' interface ###########################################
91
92 #### Events ####
93
94 #: Fired when a plugin has been added.
95 plugin_added = Delegate("plugin_manager", modify=True)
96
97 #: Fired when a plugin has been removed.
98 plugin_removed = Delegate("plugin_manager", modify=True)
99
100 #### 'Application' interface ##############################################
101
102 # These traits allow application developers to build completely different
103 # styles of extensible application. It allows Envisage to be used as a
104 # framework for frameworks ;^)
105
106 #: The extension registry.
107 extension_registry = Instance(IExtensionRegistry)
108
109 #: The plugin manager (starts and stops plugins etc).
110 plugin_manager = Instance(IPluginManager)
111
112 #: The service registry.
113 service_registry = Instance(IServiceRegistry)
114
115 #### Private interface ####################################################
116
117 # The import manager.
118 _import_manager = Instance(IImportManager, factory=ImportManager)
119
120 ###########################################################################
121 # 'object' interface.
122 ###########################################################################
123
124 def __init__(self, plugins=None, **traits):
125 """Constructor.
126
127 We allow the caller to specify an initial list of plugins, but the list
128 itself is not part of the public API. To add and remove plugins after
129 after construction, use the 'add_plugin' and 'remove_plugin' methods
130 respectively. The application is also iterable, so to iterate over the
131 plugins use 'for plugin in application: ...'.
132
133 """
134
135 super().__init__(**traits)
136
137 # fixme: We have to initialize the application home here (i.e. we can't
138 # wait until the 'home' trait is accessed) because the scoped
139 # preferences uses 'ETSConfig.application' home as the name of the
140 # default preferences file.
141 self._initialize_application_home()
142
143 # Set the default preferences node used by the preferences package.
144 # This allows 'PreferencesHelper' and 'PreferenceBinding' instances to
145 # be used as more convenient ways to access preferences.
146 #
147 # fixme: This is another sneaky global!
148 set_default_preferences(self.preferences)
149
150 # We allow the caller to specify an initial list of plugins, but the
151 # list itself is not part of the public API. To add and remove plugins
152 # after construction, use the 'add_plugin' and 'remove_plugin' methods
153 # respectively. The application is also iterable, so to iterate over
154 # the plugins use 'for plugin in application: ...'.
155 if plugins is not None:
156 for plugin in plugins:
157 self.add_plugin(plugin)
158
159 ###########################################################################
160 # 'IApplication' interface.
161 ###########################################################################
162
163 #### Trait initializers ###################################################
164
165 def _home_default(self):
166 """Trait initializer."""
167
168 return ETSConfig.application_home
169
170 def _user_data_default(self):
171 """Trait initializer."""
172
173 return ETSConfig.user_data
174
175 def _preferences_default(self):
176 """Trait initializer."""
177
178 return ScopedPreferences(
179 application_preferences_filename=os.path.join(
180 self.home, "preferences.ini"
181 )
182 )
183
184 #### Methods ##############################################################
185
186 def run(self):
187 """Run the application."""
188
189 if self.start():
190 self.stop()
191
192 ###########################################################################
193 # 'IExtensionRegistry' interface.
194 ###########################################################################
195
196 def add_extension_point_listener(self, listener, extension_point_id=None):
197 """Add a listener for extensions being added/removed."""
198
199 self.extension_registry.add_extension_point_listener(
200 listener, extension_point_id
201 )
202
203 def add_extension_point(self, extension_point):
204 """Add an extension point."""
205
206 self.extension_registry.add_extension_point(extension_point)
207
208 def get_extensions(self, extension_point_id):
209 """Return a list containing all contributions to an extension point."""
210
211 return self.extension_registry.get_extensions(extension_point_id)
212
213 def get_extension_point(self, extension_point_id):
214 """Return the extension point with the specified Id."""
215
216 return self.extension_registry.get_extension_point(extension_point_id)
217
218 def get_extension_points(self):
219 """Return all extension points that have been added to the registry."""
220
221 return self.extension_registry.get_extension_points()
222
223 def remove_extension_point_listener(
224 self, listener, extension_point_id=None
225 ):
226 """Remove a listener for extensions being added/removed."""
227
228 self.extension_registry.remove_extension_point_listener(
229 listener, extension_point_id
230 )
231
232 def remove_extension_point(self, extension_point_id):
233 """Remove an extension point."""
234
235 self.extension_registry.remove_extension_point(extension_point_id)
236
237 def set_extensions(self, extension_point_id, extensions):
238 """Set the extensions contributed to an extension point."""
239
240 self.extension_registry.set_extensions(extension_point_id, extensions)
241
242 ###########################################################################
243 # 'IImportManager' interface.
244 ###########################################################################
245
246 def import_symbol(self, symbol_path):
247 """Import the symbol defined by the specified symbol path."""
248
249 return self._import_manager.import_symbol(symbol_path)
250
251 ###########################################################################
252 # 'IPluginManager' interface.
253 ###########################################################################
254
255 def __iter__(self):
256 """Return an iterator over the manager's plugins."""
257
258 return iter(self.plugin_manager)
259
260 def add_plugin(self, plugin):
261 """Add a plugin to the manager."""
262
263 self.plugin_manager.add_plugin(plugin)
264
265 def get_plugin(self, plugin_id):
266 """Return the plugin with the specified Id."""
267
268 return self.plugin_manager.get_plugin(plugin_id)
269
270 def remove_plugin(self, plugin):
271 """Remove a plugin from the manager."""
272
273 self.plugin_manager.remove_plugin(plugin)
274
275 def start(self):
276 """Start the plugin manager.
277
278 Returns True unless the start was vetoed.
279
280 """
281
282 # fixme: This method is notionally on the 'IPluginManager' interface
283 # but that interface knows nothing about the vetoable events etc and
284 # hence doesn't have a return value.
285 logger.debug("---------- application starting ----------")
286
287 # Lifecycle event.
288 self.starting = event = self._create_application_event()
289 if not event.veto:
290 # Start the plugin manager (this starts all of the manager's
291 # plugins).
292 self.plugin_manager.start()
293
294 # Lifecycle event.
295 self.started = self._create_application_event()
296
297 logger.debug("---------- application started ----------")
298
299 else:
300 logger.debug("---------- application start vetoed ----------")
301
302 return not event.veto
303
304 def start_plugin(self, plugin=None, plugin_id=None):
305 """Start the specified plugin."""
306
307 return self.plugin_manager.start_plugin(plugin, plugin_id)
308
309 def stop(self):
310 """Stop the plugin manager.
311
312 Returns True unless the stop was vetoed.
313
314 """
315
316 # fixme: This method is notionally on the 'IPluginManager' interface
317 # but that interface knows nothing about the vetoable events etc and
318 # hence doesn't have a return value.
319 logger.debug("---------- application stopping ----------")
320
321 # Lifecycle event.
322 self.stopping = event = self._create_application_event()
323 if not event.veto:
324 # Stop the plugin manager (this stops all of the manager's
325 # plugins).
326 self.plugin_manager.stop()
327
328 # Save all preferences.
329 self.preferences.save()
330
331 # Lifecycle event.
332 self.stopped = self._create_application_event()
333
334 logger.debug("---------- application stopped ----------")
335
336 else:
337 logger.debug("---------- application stop vetoed ----------")
338
339 return not event.veto
340
341 def stop_plugin(self, plugin=None, plugin_id=None):
342 """Stop the specified plugin."""
343
344 return self.plugin_manager.stop_plugin(plugin, plugin_id)
345
346 ###########################################################################
347 # 'IServiceRegistry' interface.
348 ###########################################################################
349
350 def get_required_service(
351 self, protocol, query="", minimize="", maximize=""
352 ):
353 """Return the service that matches the specified query.
354
355 Raise a 'NoSuchServiceError' exception if no such service exists.
356
357 """
358
359 service = self.service_registry.get_required_service(
360 protocol, query, minimize, maximize
361 )
362
363 return service
364
365 def get_service(self, protocol, query="", minimize="", maximize=""):
366 """Return at most one service that matches the specified query."""
367
368 service = self.service_registry.get_service(
369 protocol, query, minimize, maximize
370 )
371
372 return service
373
374 def get_service_from_id(self, service_id):
375 """Return the service with the specified id."""
376
377 return self.service_registry.get_service_from_id(service_id)
378
379 def get_service_properties(self, service_id):
380 """Return the dictionary of properties associated with a service."""
381
382 return self.service_registry.get_service_properties(service_id)
383
384 def get_services(self, protocol, query="", minimize="", maximize=""):
385 """Return all services that match the specified query."""
386
387 services = self.service_registry.get_services(
388 protocol, query, minimize, maximize
389 )
390
391 return services
392
393 def register_service(self, protocol, obj, properties=None):
394 """Register a service."""
395
396 service_id = self.service_registry.register_service(
397 protocol, obj, properties
398 )
399
400 return service_id
401
402 def set_service_properties(self, service_id, properties):
403 """Set the dictionary of properties associated with a service."""
404
405 self.service_registry.set_service_properties(service_id, properties)
406
407 def unregister_service(self, service_id):
408 """Unregister a service."""
409
410 self.service_registry.unregister_service(service_id)
411
412 ###########################################################################
413 # 'Application' interface.
414 ###########################################################################
415
416 #### Trait initializers ###################################################
417
418 def _extension_registry_default(self):
419 """Trait initializer."""
420
421 # Do the import here to emphasize the fact that this is just the
422 # default implementation and that the application developer is free
423 # to override it!
424 from .plugin_extension_registry import PluginExtensionRegistry
425
426 return PluginExtensionRegistry(plugin_manager=self)
427
428 def _plugin_manager_default(self):
429 """Trait initializer."""
430
431 # Do the import here to emphasize the fact that this is just the
432 # default implementation and that the application developer is free
433 # to override it!
434 from .plugin_manager import PluginManager
435
436 return PluginManager(application=self)
437
438 def _service_registry_default(self):
439 """Trait initializer."""
440
441 # Do the import here to emphasize the fact that this is just the
442 # default implementation and that the application developer is free
443 # to override it!
444 from .service_registry import ServiceRegistry
445
446 return ServiceRegistry()
447
448 ###########################################################################
449 # Private interface.
450 ###########################################################################
451
452 #### Trait change handlers ################################################
453
454 # fixme: We have this to make it easier to assign a new plugin manager
455 # at construction time due to the fact that the plugin manager needs a
456 # reference to the application and vice-versa, e.g. we can do
457 #
458 # application = Application(plugin_manager=EggPluginManager())
459 #
460 # If we didn't have this then we would have to do this:-
461 #
462 # application = Application()
463 # application.plugin_manager = EggPluginManager(application=application)
464 #
465 # Of course, it would be better if the plugin manager didn't require a
466 # reference to the application at all (it currently uses it to set the
467 # 'application' trait of plugin instances - but that is only done for the
468 # same reason as this (i.e. it is nice to be able to pass plugins into the
469 # application constructor).
470
471 @observe("plugin_manager")
472 def _update_application(self, event):
473 """Static trait change handler."""
474 old, new = event.old, event.new
475
476 if old is not None:
477 old.application = None
478
479 if new is not None:
480 new.application = self
481
482 #### Methods ##############################################################
483
484 def _create_application_event(self):
485 """Create an application event."""
486
487 return ApplicationEvent(application=self)
488
489 def _initialize_application_home(self):
490 """Initialize the application directories."""
491
492 os.makedirs(self.home, mode=0o700, exist_ok=True)
493 os.makedirs(self.user_data, exist_ok=True)