Debian Codegraph @

envisage/extension_point.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 """ A trait type used to declare and access extension points. """
11
12
13 # Standard library imports.
14 import inspect
15 import weakref
16
17 # Enthought library imports.
18 from traits.api import List, provides, TraitType, Undefined
19
20 # Local imports.
21 from .i_extension_point import IExtensionPoint
22
23 # Exception message template.
24 INVALID_TRAIT_TYPE = (
25 'extension points must be "List"s e.g. List, List(Int)'
26 " but a value of %s was specified."
27 )
28
29
30 # Even though trait types do not themselves have traits, we can still
31 # declare that we implement an interface.
32 @provides(IExtensionPoint)
33 class ExtensionPoint(TraitType):
34 """A trait type used to declare and access extension points.
35
36 Note that this is a trait *type* and hence does *NOT* have traits itself
37 (i.e. it does *not* inherit from 'HasTraits').
38
39 """
40
41 ###########################################################################
42 # 'ExtensionPoint' *CLASS* interface.
43 ###########################################################################
44
45 @staticmethod
46 def connect_extension_point_traits(obj):
47 """Connect all of the 'ExtensionPoint' traits on an object."""
48
49 for trait_name, trait in obj.traits(__extension_point__=True).items():
50 trait.trait_type.connect(obj, trait_name)
51
52 @staticmethod
53 def disconnect_extension_point_traits(obj):
54 """Disconnect all of the 'ExtensionPoint' traits on an object."""
55
56 for trait_name, trait in obj.traits(__extension_point__=True).items():
57 trait.trait_type.disconnect(obj, trait_name)
58
59 ###########################################################################
60 # 'object' interface.
61 ###########################################################################
62
63 def __init__(self, trait_type=List, id=None, **metadata):
64 """Constructor."""
65
66 # We add '__extension_point__' to the metadata to make the extension
67 # point traits easier to find with the 'traits' and 'trait_names'
68 # methods on 'HasTraits'.
69 metadata["__extension_point__"] = True
70 super().__init__(**metadata)
71
72 # The trait type that describes the extension point.
73 #
74 # If we are handed a trait type *class* e.g. List, instead of a trait
75 # type *instance* e.g. List() or List(Int) etc, then we instantiate it.
76 if inspect.isclass(trait_type):
77 trait_type = trait_type()
78
79 # Currently, we only support list extension points (we may in the
80 # future want to allow other collections e.g. dictionaries etc).
81 if not isinstance(trait_type, List):
82 raise TypeError(INVALID_TRAIT_TYPE % trait_type)
83
84 self.trait_type = trait_type
85
86 # The Id of the extension point.
87 if id is None:
88 raise ValueError("an extension point must have an Id")
89
90 self.id = id
91
92 # A dictionary that is used solely to keep a reference to all extension
93 # point listeners alive until their associated objects are garbage
94 # collected.
95 #
96 # Dict(weakref.ref(Any), Dict(Str, Callable))
97 self._obj_to_listeners_map = weakref.WeakKeyDictionary()
98
99 def __repr__(self):
100 """String representation of an ExtensionPoint object"""
101 return "ExtensionPoint(id={!r})".format(self.id)
102
103 ###########################################################################
104 # 'TraitType' interface.
105 ###########################################################################
106
107 def get(self, obj, trait_name):
108 """Trait type getter."""
109
110 extension_registry = self._get_extension_registry(obj)
111
112 # Get the extensions to this extension point.
113 extensions = extension_registry.get_extensions(self.id)
114
115 # Make sure the contributions are of the appropriate type.
116 return self.trait_type.validate(obj, trait_name, extensions)
117
118 def set(self, obj, name, value):
119 """Trait type setter."""
120
121 extension_registry = self._get_extension_registry(obj)
122
123 # Note that some extension registry implementations may not support the
124 # setting of extension points (the default, plugin extension registry
125 # for exxample ;^).
126 extension_registry.set_extensions(self.id, value)
127
128 ###########################################################################
129 # 'ExtensionPoint' interface.
130 ###########################################################################
131
132 def connect(self, obj, trait_name):
133 """Connect the extension point to a trait on an object.
134
135 This allows the object to react when contributions are added or
136 removed from the extension point.
137
138 fixme: It would be nice to be able to make the connection automatically
139 but we would need a slight tweak to traits to allow the trait type to
140 be notified when a new instance that uses the trait type is created.
141
142 """
143
144 def listener(extension_registry, event):
145 """Listener called when an extension point is changed."""
146
147 # If an index was specified then we fire an '_items' changed event.
148 if event.index is not None:
149 name = trait_name + "_items"
150 old = Undefined
151 new = event
152
153 # Otherwise, we fire a normal trait changed event.
154 else:
155 name = trait_name
156 old = event.removed
157 new = event.added
158
159 obj.trait_property_changed(name, old, new)
160
161 extension_registry = self._get_extension_registry(obj)
162
163 # Add the listener to the extension registry.
164 extension_registry.add_extension_point_listener(listener, self.id)
165
166 # Save a reference to the listener so that it does not get garbage
167 # collected until its associated object does.
168 listeners = self._obj_to_listeners_map.setdefault(obj, {})
169 listeners[trait_name] = listener
170
171 def disconnect(self, obj, trait_name):
172 """Disconnect the extension point from a trait on an object."""
173
174 extension_registry = self._get_extension_registry(obj)
175
176 listener = self._obj_to_listeners_map[obj].get(trait_name)
177 if listener is not None:
178 # Remove the listener from the extension registry.
179 extension_registry.remove_extension_point_listener(
180 listener, self.id
181 )
182
183 # Clean up.
184 del self._obj_to_listeners_map[obj][trait_name]
185
186 ###########################################################################
187 # Private interface.
188 ###########################################################################
189
190 def _get_extension_registry(self, obj):
191 """Return the extension registry in effect for an object."""
192
193 extension_registry = getattr(obj, "extension_registry", None)
194 if extension_registry is None:
195 raise ValueError(
196 'The "ExtensionPoint" trait type can only be used in '
197 "objects that have a reference to an extension registry "
198 'via their "extension_registry" trait. '
199 "Extension point Id <%s>" % self.id
200 )
201
202 return extension_registry