Debian Codegraph @

envisage/application.py

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