File: elementfactory.py

package info (click to toggle)
gaphor 0.13.0-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,692 kB
  • ctags: 2,971
  • sloc: python: 19,981; xml: 247; makefile: 54; sh: 40
file content (223 lines) | stat: -rw-r--r-- 6,810 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# vim: sw=4
"""
Factory for and registration of model elements.
"""

from zope import interface
from zope import component
from gaphor.misc import uniqueid, odict
from gaphor.interfaces import IService, IEventFilter
from gaphor.UML.interfaces import IElementCreateEvent, IElementDeleteEvent, \
                                  IFlushFactoryEvent, IModelFactoryEvent, \
                                  IElementChangeEvent, IElementEvent
from gaphor.UML.event import ElementCreateEvent, ElementDeleteEvent, \
                             FlushFactoryEvent, ModelFactoryEvent
from gaphor.UML.element import Element
from gaphor.UML.diagram import Diagram


class ElementChangedEventBlocker(object):
    """
    Blocks all events of type IElementChangeEvent.

    This filter is placed when the the element factory flushes it's content.
    """
    component.adapts(IElementChangeEvent)
    interface.implements(IEventFilter)

    def __init__(self, event):
        self._event = event

    def filter(self):
        """
        Return the event or None if the event is not to be emitted.
        """
        return 'Blocked by ElementFactory.flush()'


class ElementFactory(object):
    """
    The ElementFactory is used to create elements and do lookups to
    elements.

    Notifications are send with as arguments (name, element, *user_data).
    The following names are used:
    create - a new model element is created (element is newly created element)
    remove - a model element is removed (element is to be removed element)
    model - a new model has been loaded (element is None)
    flush - model is flushed: all element are removed from the factory
            (element is None)
    """
    interface.implements(IService)

    def __init__(self):
        self._elements = odict.odict()
        self._observers = list()
        self._app = None

    def init(self, app):
        self._app = app
        app.register_handler(self._element_notify)
        app.register_handler(self._element_deleted)

    def shutdown(self):
        # unregister after flush: the handler is needed to empty the _elements
        if self._app:
            self._app.unregister_handler(self._element_notify)
        self.flush()
        if self._app:
            self._app.unregister_handler(self._element_deleted)

    def create(self, type):
        """
        Create a new model element of type type.
        """
        obj = self.create_as(type, uniqueid.generate_id())
        if self._app:
            self._app.handle(ElementCreateEvent(self, obj))
        return obj

    def create_as(self, type, id):
        """
        Create a new model element of type 'type' with 'id' as its ID.
        This method should only be used when loading models, since it does
        not emit an ElementCreateEvent event.
        """
        assert issubclass(type, Element)
        obj = type(id, self)
        self._elements[id] = obj
        return obj

    def size(self):
        """
        Return the amount of elements currently in the factory.
        """
        return len(self._elements)

    def lookup(self, id):
        """
        Find element with a specific id.
        """
        return self._elements.get(id)

    __getitem__ = lookup

    def __contains__(self, element):
        return self.lookup(element.id) is element

    def select(self, expression=None):
        """
        Iterate elements that comply with expression.
        """
        if expression is None:
            for e in self._elements.itervalues():
                yield e
        else:
            for e in self._elements.itervalues():
                if expression(e):
                    yield e

    def lselect(self, expression=None):
        """
        Like select(), but returns a list.
        """
        return list(self.select(expression))

    def keys(self):
        """
        Return a list with all id's in the factory.
        """
        return self._elements.keys()

    def iterkeys(self):
        """
        Return a iterator with all id's in the factory.
        """
        return self._elements.iterkeys()

    def values(self):
        """
        Return a list with all elements in the factory.
        """
        return self._elements.values()

    def itervalues(self):
        """
        Return a iterator with all elements in the factory.
        """
        return self._elements.itervalues()

    def is_empty(self):
        """
        Returns True if the factory holds no elements.
        """
        if self._elements:
            return False
        else:
            return True

    def flush(self):
        """
        Flush all elements (remove them from the factory).
        """
        app = self._app
        if app:
            app.handle(FlushFactoryEvent(self))
            app.register_subscription_adapter(ElementChangedEventBlocker)

        try:
            # First flush all diagrams:
            for value in list(self.select(lambda e: isinstance(e, Diagram))):
                # Make sure no updates happen while destroying the canvas
                value.canvas.block_updates = True
                value.unlink()
                if not app:
                    self._element_deleted(ElementDeleteEvent(self, value))
            for key, value in self._elements.items():
                value.unlink()
                if not app:
                    self._element_deleted(ElementDeleteEvent(self, value))
        finally:
            if app:
                app.unregister_subscription_adapter(ElementChangedEventBlocker)

        assert len(self._elements) == 0, 'Still items in the factory: %s' % str(self._elements.values())

        # Force Garbage collection, so memory allocated by items is freed.
        import gc
        for i in range(4): gc.collect()


    def swap_element(self, element, new_class):
	assert element in self._elements.values()
        if element.__class__ is not new_class:
            element.__class__ = new_class

    def notify_model(self):
        """
        Send notification that a new model has been loaded by means of the
        ModelFactoryEvent event from gaphor.UML.event.
        """
        if self._app:
            self._app.handle(ModelFactoryEvent(self))

    @component.adapter(IElementEvent)
    def _element_notify(self, event):
        """
        Dispatch IElementEvent events to interested adapters registered
        by (class, event).
        """
        if self._app:
            self._app.handle(event.element, event)

    @component.adapter(IElementDeleteEvent)
    def _element_deleted(self, event):
        """
        Remove an element from the factory.
        """
        element = event.element
        if self._elements.has_key(element.id):
            del self._elements[element.id]


# vim:sw=4:et