Debian Codegraph @

envisage/extension_point_binding.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 binding between a trait on an object and an extension point. """
11
12
13 # Enthought library imports.
14 from traits.api import Any, HasTraits, Instance, Str, Undefined
15
16 # Local imports.
17 from .i_extension_registry import IExtensionRegistry
18
19
20 class ExtensionPointBinding(HasTraits):
21 """A binding between a trait on an object and an extension point."""
22
23 #### 'ExtensionPointBinding' *CLASS* interface ############################
24
25 # Global dictionary used to keep ExtensionPointBinding objects alive.
26 _bindings = {}
27
28 #### 'ExtensionPointBinding' interface ####################################
29
30 # The object that we are binding the extension point to.
31 obj = Any
32
33 # The Id of the extension point.
34 extension_point_id = Str
35
36 # The extension registry used by the binding. If this trait is not set then
37 # the class-scope extension registry set on the 'ExtensionPoint' class is
38 # used (and if that is not set then the binding won't work ;^)
39 extension_registry = Instance(IExtensionRegistry)
40
41 # The name of the trait that we are binding the extension point to.
42 trait_name = Str
43
44 #### Private interface ####################################################
45
46 # A flag that prevents us from setting a trait twice.
47 _event_handled = False
48
49 ###########################################################################
50 # 'object' interface.
51 ###########################################################################
52
53 def __init__(self, **traits):
54 """Constructor."""
55
56 super().__init__(**traits)
57
58 # Initialize the object's trait from the extension point.
59 self._set_trait(notify=False)
60
61 # Wire-up the trait change and extension point handlers.
62 self._bind()
63
64 ###########################################################################
65 # Private interface.
66 ###########################################################################
67
68 #### Trait change handlers ################################################
69
70 def _on_trait_changed(self, obj, trait_name, old, new):
71 """Dynamic trait change handler."""
72
73 if not self._event_handled:
74 self._set_extensions(new)
75
76 def _on_trait_items_changed(self, obj, trait_name, old, event):
77 """Dynamic trait change handler."""
78
79 if not self._event_handled:
80 self._set_extensions(getattr(obj, self.trait_name))
81
82 #### Other observer pattern listeners #####################################
83
84 def _extension_point_listener(self, extension_registry, event):
85 """Listener called when an extension point is changed."""
86
87 self._event_handled = True
88 if event.index is not None:
89 self._update_trait(event)
90
91 else:
92 self._set_trait(notify=True)
93 self._event_handled = False
94
95 #### Methods ##############################################################
96
97 def _bind(self):
98 """Wire-up trait change handlers etc."""
99
100 # Listen for the object's trait being changed.
101 self.obj.on_trait_change(self._on_trait_changed, self.trait_name)
102
103 self.obj.on_trait_change(
104 self._on_trait_items_changed, self.trait_name + "_items"
105 )
106
107 # Listen for the extension point being changed.
108 self.extension_registry.add_extension_point_listener(
109 self._extension_point_listener, self.extension_point_id
110 )
111
112 def _unbind(self):
113 """Undo the effects of _bind"""
114
115 self.extension_registry.remove_extension_point_listener(
116 self._extension_point_listener, self.extension_point_id
117 )
118
119 self.obj.on_trait_change(
120 self._on_trait_items_changed,
121 self.trait_name + "_items",
122 remove=True,
123 )
124
125 self.obj.on_trait_change(
126 self._on_trait_changed, self.trait_name, remove=True
127 )
128
129 def _set_trait(self, notify):
130 """Set the object's trait to the value of the extension point."""
131
132 value = self.extension_registry.get_extensions(self.extension_point_id)
133 traits = {self.trait_name: value}
134
135 self.obj.trait_set(trait_change_notify=notify, **traits)
136
137 def _update_trait(self, event):
138 """Update the object's trait to the value of the extension point."""
139
140 self._set_trait(notify=False)
141
142 self.obj.trait_property_changed(
143 self.trait_name + "_items", Undefined, event
144 )
145
146 def _set_extensions(self, extensions):
147 """Set the extensions to an extension point."""
148
149 self.extension_registry.set_extensions(
150 self.extension_point_id, extensions
151 )
152
153
154 # Factory function for creating bindings.
155 def bind_extension_point(
156 obj, trait_name, extension_point_id, extension_registry
157 ):
158 """Create a binding to an extension point.
159
160 The returned ExtensionPointBinding object is also stored in a (private)
161 global dictionary, so that users aren't required to keep a reference to it.
162 That global dictionary entry can be removed with a matching call to
163 unbind_extension_point.
164
165 Parameters
166 ----------
167 obj : HasTraits
168 The HasTraits object that we're binding to
169 trait_name : str
170 The name of the trait on obj to bind to.
171 extension_point_id : str
172 The id of the extension point.
173 extension_registry : IExtensionRegistry
174 The extension registry that the extension point is registered to.
175
176 Returns
177 -------
178 ExtensionPointBinding
179 An object that manages the binding.
180 """
181
182 binding = ExtensionPointBinding(
183 obj=obj,
184 trait_name=trait_name,
185 extension_point_id=extension_point_id,
186 extension_registry=extension_registry,
187 )
188
189 # Keep a reference to each binding in the ExtensionPointBinding._bindings
190 # global dictionary. Without this, the binding would become inactive
191 # if the caller didn't keep a reference.
192 bindings = ExtensionPointBinding._bindings.setdefault(obj, [])
193 bindings.append(binding)
194 return binding
195
196
197 def unbind_extension_point(
198 obj, trait_name, extension_point_id, extension_registry
199 ):
200 """
201 Remove an extension point binding.
202
203 Changes to extension point contributions will no longer affect the target
204 trait. Also removes the matching ExtensionPointBinding object from the
205 global dictionary.
206
207 Parameters
208 ----------
209 obj : HasTraits
210 The HasTraits object that we're binding to
211 trait_name : str
212 The name of the trait on obj to bind to.
213 extension_point_id : str
214 The id of the extension point.
215 extension_registry : IExtensionRegistry
216 The extension registry that the extension point is registered to.
217 """
218 # Find the corresponding binding in the global dict.
219 bindings = ExtensionPointBinding._bindings
220
221 # Find the matching ExtensionPointBinding object. Search in reverse order,
222 # since that's most likely to give the right binding quickly under the
223 # normal first-in-last-out pattern for nested setup and teardown.
224 index, binding = next(
225 (index, binding)
226 for index, binding in reversed(list(enumerate(bindings[obj])))
227 if binding.trait_name == trait_name
228 if binding.extension_point_id == extension_point_id
229 if binding.extension_registry == extension_registry
230 )
231
232 # Remove the binding from the global dict, and remove the dict entry
233 # altogether if it's now empty.
234 bindings[obj].pop(index)
235 if not bindings[obj]:
236 bindings.pop(obj)
237
238 # Undo the binding
239 binding._unbind()