Debian Codegraph @

envisage/plugin.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 """ The default implementation of the 'IPlugin' interface. """
11
12 # Standard library imports.
13 import logging
14 import os
15 from os.path import exists, join
16
17 # Enthought library imports.
18 from traits.api import Instance, List, Property, provides, Str
19 from traits.util.camel_case import camel_case_to_words
20
21 # Local imports.
22 from .extension_point import ExtensionPoint
23 from .extension_provider import ExtensionProvider
24 from .i_application import IApplication
25 from .i_extension_point_user import IExtensionPointUser
26 from .i_extension_registry import IExtensionRegistry
27 from .i_plugin import IPlugin
28 from .i_plugin_activator import IPluginActivator
29 from .i_service_registry import IServiceRegistry
30 from .i_service_user import IServiceUser
31 from .plugin_activator import PluginActivator
32
33 # Logging.
34 logger = logging.getLogger(__name__)
35
36
37 @provides(IPlugin, IExtensionPointUser, IServiceUser)
38 class Plugin(ExtensionProvider):
39 """The default implementation of the 'IPlugin' interface.
40
41 This class is intended to be subclassed for each plugin that you create.
42
43 """
44
45 #### 'IPlugin' interface ##################################################
46
47 #: The activator used to start and stop the plugin.
48 #:
49 #: By default the *same* activator instance is used for *all* plugins of
50 #: this type.
51 activator = Instance(IPluginActivator, PluginActivator())
52
53 #: The application that the plugin is part of.
54 application = Instance(IApplication)
55
56 #: The name of a directory (created for you) that the plugin can read and
57 #: write to at will.
58 home = Str
59
60 #: The plugin's unique identifier.
61 #:
62 #: If no identifier is specified then the module and class name of the
63 #: plugin are used to create an Id with the form 'module_name.class_name'.
64 id = Str
65
66 #: The plugin's name (suitable for displaying to the user).
67 #:
68 #: If no name is specified then the plugin's class name is used with an
69 #: attempt made to turn camel-case class names into words separated by
70 #: spaces (e.g. if the class name is 'MyPlugin' then the name would be
71 #: 'My Plugin'). Of course, if you really care about the actual name, then
72 #: just set it!
73 name = Str
74
75 #### 'IExtensionPointUser' interface ######################################
76
77 #: The extension registry that the object's extension points are stored in.
78 extension_registry = Property(Instance(IExtensionRegistry))
79
80 #### 'IServiceUser' interface #############################################
81
82 #: The service registry that the object's services are stored in.
83 service_registry = Property(Instance(IServiceRegistry))
84
85 #### Private interface ####################################################
86
87 # The Ids of the services that were automatically registered.
88 _service_ids = List
89
90 ###########################################################################
91 # 'IExtensionPointUser' interface.
92 ###########################################################################
93
94 def _get_extension_registry(self):
95 """Trait property getter."""
96
97 return self.application
98
99 ###########################################################################
100 # 'IServiceUser' interface.
101 ###########################################################################
102
103 def _get_service_registry(self):
104 """Trait property getter."""
105
106 return self.application
107
108 ###########################################################################
109 # 'IExtensionProvider' interface.
110 ###########################################################################
111
112 def get_extension_points(self):
113 """Return the extension points offered by the provider."""
114
115 extension_points = [
116 trait.trait_type
117 for trait in self.traits(__extension_point__=True).values()
118 ]
119
120 return extension_points
121
122 def get_extensions(self, extension_point_id):
123 """Return the provider's extensions to an extension point."""
124
125 # Each class can have at most *one* trait that contributes to a
126 # particular extension point.
127 #
128 # fixme: We make this restriction in case that in future we can wire up
129 # the list traits directly. If we don't end up doing that then it is
130 # fine to allow mutiple traits!
131 trait_names = self.trait_names(contributes_to=extension_point_id)
132
133 if len(trait_names) == 0:
134 extensions = []
135
136 elif len(trait_names) == 1:
137 extensions = self._get_extensions_from_trait(trait_names[0])
138
139 else:
140 raise self._create_multiple_traits_exception(extension_point_id)
141
142 return extensions
143
144 ###########################################################################
145 # 'IPlugin' interface.
146 ###########################################################################
147
148 #### Trait initializers ###################################################
149
150 def _home_default(self):
151 """Trait initializer."""
152
153 # Each plugin gets a sub-directory of a 'plugins' directory in
154 # 'application.home'.
155 #
156 # i.e. .../my.application.id/plugins/
157 plugins_dir = join(self.application.home, "plugins")
158 if not exists(plugins_dir):
159 os.mkdir(plugins_dir)
160
161 # Now create the 'home' directory of this plugin.
162 home_dir = join(plugins_dir, self.id)
163 if not exists(home_dir):
164 os.mkdir(home_dir)
165
166 return home_dir
167
168 def _id_default(self):
169 """Trait initializer."""
170
171 id = "%s.%s" % (type(self).__module__, type(self).__name__)
172 logger.warning(
173 "plugin {} has no Id - using <{}>".format(
174 object.__repr__(self), id
175 )
176 )
177
178 return id
179
180 def _name_default(self):
181 """Trait initializer."""
182
183 name = camel_case_to_words(type(self).__name__)
184 logger.warning(
185 "plugin {} has no name - using <{}>".format(
186 object.__repr__(self), name
187 )
188 )
189
190 return name
191
192 #### Methods ##############################################################
193
194 def start(self):
195 """Start the plugin.
196
197 This method will *always* be empty so that you never have to call
198 'super().start()' if you provide an implementation in a
199 derived class.
200
201 The framework does what it needs to do when it starts a plugin by means
202 of the plugin's activator.
203
204 """
205
206 pass
207
208 def stop(self):
209 """Stop the plugin.
210
211 This method will *always* be empty so that you never have to call
212 'super().stop()' if you provide an implementation in a
213 derived class.
214
215 The framework does what it needs to do when it stops a plugin by means
216 of the plugin's activator.
217
218 """
219
220 pass
221
222 ###########################################################################
223 # 'Plugin' interface.
224 ###########################################################################
225
226 def connect_extension_point_traits(self):
227 """Connect all of the plugin's extension points.
228
229 This means that the plugin will be notified if and when contributions
230 are add or removed.
231
232 """
233
234 ExtensionPoint.connect_extension_point_traits(self)
235
236 def disconnect_extension_point_traits(self):
237 """Disconnect all of the plugin's extension points."""
238
239 ExtensionPoint.disconnect_extension_point_traits(self)
240
241 def register_services(self):
242 """Register the services offered by the plugin."""
243
244 for trait_name, trait in self.traits(service=True).items():
245 logger.warning(
246 'DEPRECATED: Do not use the "service=True" metadata anymore. '
247 "Services should now be offered using the service "
248 "offer extension point (envisage.service_offers) "
249 "from the core plugin. "
250 "Plugin %s trait <%s>" % (self, trait_name)
251 )
252
253 # Register a service factory for the trait.
254 service_id = self._register_service_factory(trait_name, trait)
255
256 # We save the service Id so that so that we can unregister the
257 # service when the plugin is stopped.
258 self._service_ids.append(service_id)
259
260 def unregister_services(self):
261 """Unregister any service offered by the plugin."""
262
263 # Unregister the services in the reverse order that we registered
264 # them.
265 service_ids = self._service_ids[:]
266 service_ids.reverse()
267
268 for service_id in service_ids:
269 try:
270 self.application.get_service_from_id(service_id)
271 except ValueError:
272 # the service may have already been individually unregistered
273 pass
274 else:
275 self.application.unregister_service(service_id)
276
277 # Just in case the plugin is started again!
278 self._service_ids = []
279
280 ###########################################################################
281 # Private interface.
282 ###########################################################################
283
284 #### Trait change handlers ################################################
285
286 def _anytrait_changed(self, trait_name, old, new):
287 """Static trait change handler."""
288
289 # Ignore the '_items' part of the trait name (if it is there!), and get
290 # the actual trait.
291 base_trait_name = trait_name.split("_items")[0]
292 trait = self.trait(base_trait_name)
293
294 # If the trait is one that contributes to an extension point then fire
295 # an appropriate 'extension point changed' event.
296 if trait.contributes_to is not None:
297 if trait_name.endswith("_items"):
298 added = new.added
299 removed = new.removed
300 index = new.index
301
302 else:
303 added = new
304 removed = old
305 index = slice(0, len(old))
306
307 # Let the extension registry know about the change.
308 self._fire_extension_point_changed(
309 trait.contributes_to, added, removed, index
310 )
311
312 #### Methods ##############################################################
313
314 def _create_multiple_traits_exception(self, extension_point_id):
315 """Create the exception raised when multiple traits are found."""
316
317 exception = ValueError(
318 "multiple traits for extension point <%s> in plugin <%s>"
319 % (extension_point_id, self.id)
320 )
321
322 return exception
323
324 def _get_extensions_from_trait(self, trait_name):
325 """Return the extensions contributed via the specified trait."""
326
327 try:
328 extensions = getattr(self, trait_name)
329
330 except Exception:
331 logger.exception(
332 "getting extensions from %s, trait <%s>" % (self, trait_name)
333 )
334 raise
335
336 return extensions
337
338 def _get_service_protocol(self, trait):
339 """Determine the protocol to register a service trait with."""
340
341 # If a specific protocol was specified then use it.
342 if trait.service_protocol is not None:
343 protocol = trait.service_protocol
344
345 # Otherwise, use the type of the objects that can be assigned to the
346 # trait.
347 #
348 # fixme: This works for 'Instance' traits, but what about 'AdaptsTo'
349 # and 'Supports' traits?
350 else:
351 # Note that in traits the protocol can be an actual class or
352 # interfacem or the *name* of a class or interface. This allows
353 # us to lazy load them!
354 protocol = trait.trait_type.klass
355
356 return protocol
357
358 def _register_service_factory(self, trait_name, trait):
359 """Register a service factory for the specified trait."""
360
361 # Determine the protocol that the service should be registered with.
362 protocol = self._get_service_protocol(trait)
363
364 # Register a factory for the service so that it will be lazily loaded
365 # the first time somebody asks for a service with the same protocol
366 # (this could obviously be a lambda function, but I thought it best to
367 # be more explicit 8^).
368 def factory(**properties):
369 """A service factory."""
370
371 return getattr(self, trait_name)
372
373 return self.application.register_service(protocol, factory)
374
375 ###########################################################################
376 # 'object' interface.
377 ###########################################################################
378
379 def __repr__(self):
380 """String representation of a Plugin object"""
381 return f"{type(self).__name__}(id={self.id!r}, name={self.name!r})"