File: namespace.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 (634 lines) | stat: -rw-r--r-- 20,142 bytes parent folder | download | duplicates (2)
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
"""
This is the TreeView that is most common (for example: it is used
in Rational Rose). This is a tree based on namespace relationships. As
a result only classifiers are shown here.
"""

import gobject
import gtk
import operator
import stock

from zope import component

from gaphor.application import Application
from gaphor import UML
from gaphor.UML.event import ElementCreateEvent, ModelFactoryEvent, FlushFactoryEvent
from gaphor.UML.interfaces import IAttributeChangeEvent, IElementDeleteEvent
from gaphor.UML.event import DerivedUnionSetEvent
from gaphor.transaction import Transaction


# The following items will not be shown in the treeview, although they
# are UML.Namespace elements.
_default_filter_list = (
    UML.Class,
    UML.Interface,
    UML.Package,
    UML.Component,
    UML.Node,
    UML.Artifact,
    UML.Interaction,
    UML.UseCase,
    UML.Actor,
    UML.Diagram,
    UML.Profile,
    UML.Stereotype,
    UML.Property,
    UML.Operation
    )

# TODO: update tree sorter:
# Diagram before Class & Package.
# Property before Operation
_tree_sorter = operator.attrgetter('name')


def catchall(func):
    def catchall_wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception, e:
            log.error('Exception in %s. Try to refresh the entire model' % (func,), e)
            try:
                args[0].refresh()
            except Exception, e:
                log.error('Failed to refresh')
            
    return catchall_wrapper


class NamespaceModel(gtk.GenericTreeModel):
    """
    The NamespaceModel holds a view on the data model based on namespace
    relationships (such as a Package containing a Class).

    NamedElement.namespace[1] -- Namespace.ownedMember[*]

    NOTE: when a model is loaded no IAssociation*Event's are emitted.
    
    """


    def __init__(self, factory):
        # Init parent:
        gtk.GenericTreeModel.__init__(self)

        # We own the references to the iterators.
        self.set_property ('leak_references', 0)

        self.factory = factory

        self._nodes = { None: [] }

        self.filter = _default_filter_list

        Application.register_handler(self.flush)
        Application.register_handler(self.refresh)
        Application.register_handler(self._on_element_change)
        Application.register_handler(self._on_element_create)
        Application.register_handler(self._on_element_delete)
        Application.register_handler(self._on_association_set)

        self._build_model()


    def close(self):
        """
        Close the namespace model, unregister handlers.
        """
        Application.unregister_handler(self.flush)
        Application.unregister_handler(self.refresh)
        Application.unregister_handler(self._on_element_change)
        Application.unregister_handler(self._on_element_create)
        Application.unregister_handler(self._on_element_delete)
        Application.unregister_handler(self._on_association_set)


    def path_from_element(self, e):
        if e:
            ns = e.namespace
            n = self._nodes.get(ns)
            if n:
                return self.path_from_element(ns) + (n.index(e),)
            else:
                return ()
        else:
            return ()


    def element_from_path(self, path):
        """
        Get the node form a path. None is returned if no node is found.
        """
        try:
            nodes = self._nodes
            node = None
            for index in path:
                node = nodes[node][index]
            return node
        except IndexError:
            return None


    @component.adapter(IAttributeChangeEvent)
    @catchall
    def _on_element_change(self, event):
        """
        Element changed, update appropriate row.
        """
        element = event.element
        if element not in self._nodes:
            return

        if event.property is UML.Classifier.isAbstract or \
                event.property is UML.BehavioralFeature.isAbstract:
            path = self.path_from_element(element)
            if path:
                self.row_changed(path, self.get_iter(path))

        if event.property is UML.NamedElement.name:
            try:
                path = self.path_from_element(element)
            except KeyError:
                # Element not visible in the tree view
                return

            if not path:
                return
            self.row_changed(path, self.get_iter(path))
            parent_nodes = self._nodes[element.namespace]
            parent_path = self.path_from_element(element.namespace)
            if not parent_path:
                return

            original = list(parent_nodes)
            parent_nodes.sort(key=_tree_sorter)
            if parent_nodes != original:
                # reorder the list:
                self.rows_reordered(parent_path, self.get_iter(parent_path),
                                    map(list.index,
                                        [original] * len(parent_nodes),
                                        parent_nodes))


    def _add_elements(self, element):
        """
        Add a single element.
        """
        if type(element) not in self.filter:
            return
        if element.namespace and type(element.namespace) not in self.filter:
            return

        self._nodes.setdefault(element, [])
        parent = self._nodes[element.namespace]
        parent.append(element)
        parent.sort(key=_tree_sorter)
        path = self.path_from_element(element)
        self.row_inserted(path, self.get_iter(path))

        # Add children
        if isinstance(element, UML.Namespace):
            for e in element.ownedMember:
                self._add_elements(e)


    def _remove_element(self, element):
        """
        Remove elements from the nodes. No update signal is emitted.
        """
        def remove(n):
            for c in self._nodes.get(n, []):
                remove(c)
            try:
                del self._nodes[n]
            except KeyError:
                pass

        remove(element)


    @component.adapter(ElementCreateEvent)
    @catchall
    def _on_element_create(self, event):
        element = event.element
        if event.service is self.factory:
            self._add_elements(element)


    @component.adapter(IElementDeleteEvent)
    @catchall
    def _on_element_delete(self, event):
        element = event.element
        if event.service is self.factory and \
                type(element) in self.filter:
            path = self.path_from_element(element)

            # Remove all sub-elements:
            if path:
                self.row_deleted(path)
                if path[:-1]:
                    self.row_has_child_toggled(path[:-1], self.get_iter(path[:-1]))
            self._remove_element(element)

            parent_node = self._nodes.get(element.namespace)
            if parent_node:
                parent_node.remove(element)

#            if path and parent_node and len(self._nodes[parent_node]) == 0:
#                self.row_has_child_toggled(path[:-1], self.get_iter(path[:-1]))


    @component.adapter(DerivedUnionSetEvent)
    @catchall
    def _on_association_set(self, event):

        element = event.element
        if type(element) not in self.filter:
            return

        if event.property is UML.NamedElement.namespace:
            # Check if the element is actually in the element factory:
            if element not in self.factory:
                return

            old_value, new_value = event.old_value, event.new_value

            # Remove entry from old place
            if self._nodes.has_key(old_value):
                try:
                    path = self.path_from_element(old_value) + (self._nodes[old_value].index(element),)
                except ValueError:
                    log.error('Unable to create path for element %s and old_value %s' % (element, self._nodes[old_value]))
                else:
                    self._nodes[old_value].remove(element)
                    self.row_deleted(path)
                    path = path[:-1] #self.path_from_element(old_value)
                    if path:
                        self.row_has_child_toggled(path, self.get_iter(path))

            # Add to new place. This may fail if the type of the new place is
            # not in the tree model (because it's filtered)
            if self._nodes.has_key(new_value):
                if self._nodes.has_key(element):
                    parent = self._nodes[new_value]
                    parent.append(element)
                    parent.sort(key=_tree_sorter)
                    path = self.path_from_element(element)
                    self.row_inserted(path, self.get_iter(path))
                else:
                    self._add_elements(element)
            elif self._nodes.has_key(element):
                # Non-existent: remove entirely
                self._remove_element(element)


    @component.adapter(ModelFactoryEvent)
    def refresh(self, event=None):
        self.flush()
        self._build_model()


    @component.adapter(FlushFactoryEvent)
    def flush(self, event=None):
        for n in self._nodes[None]:
            self.row_deleted((0,))
        self._nodes = {None: []}


    def _build_model(self):
        toplevel = self.factory.select(lambda e: isinstance(e, UML.Namespace) and not e.namespace)

        for element in toplevel:
            self._add_elements(element)


    # TreeModel methods:

    def on_get_flags(self):
        """
        Returns the GtkTreeModelFlags for this particular type of model.
        """
        return 0


    def on_get_n_columns(self):
        """
        Returns the number of columns in the model.
        """
        return 1


    def on_get_column_type(self, index):
        """
        Returns the type of a column in the model.
        """
        return gobject.TYPE_PYOBJECT


    def on_get_path(self, node):
        """
        Returns the path for a node as a tuple (0, 1, 1).
        """
        path = self.path_from_element(node)
        return path


    def on_get_iter(self, path):
        """
        Returns the node corresponding to the given path.
        The path is a tuple of values, like (0 1 1). Returns None if no
        iterator can be created.
        """
        return self.element_from_path(path)


    def on_get_value(self, node, column):
        """
        Returns the model element that matches 'node'.
        """
        assert column == 0, 'column can only be 0'
        return node


    def on_iter_next(self, node):
        """
        Returns the next node at this level of the tree. None if no
        next element.
        """
        try:
            parent = self._nodes[node.namespace]
            index = parent.index(node)
            return parent[index + 1]
        except (IndexError, ValueError), e:
            return None

        
    def on_iter_has_child(self, node):
        """
        Returns true if this node has children, or None.
        """
        n = self._nodes.get(node)
        return n or len(n) > 0


    def on_iter_children(self, node):
        """
        Returns the first child of this node, or None.
        """
        try:
            return self._nodes[node][0]
        except KeyError:
            pass


    def on_iter_n_children(self, node):
        """
        Returns the number of children of this node.
        """
        return len(self._nodes[node])


    def on_iter_nth_child(self, node, n):
        """
        Returns the nth child of this node.
        """
        try:
            nodes = self._nodes[node]
            return nodes[n]
        except TypeError, e:
            return None


    def on_iter_parent(self, node):
        """
        Returns the parent of this node or None if no parent
        """
        return node.namespace


class NamespaceView(gtk.TreeView):

    TARGET_STRING = 0
    TARGET_ELEMENT_ID = 1
    DND_TARGETS = [
        ('STRING', 0, TARGET_STRING),
        ('text/plain', 0, TARGET_STRING),
        ('gaphor/element-id', 0, TARGET_ELEMENT_ID)]
    # Can not set signals for some reason...
    #__gsignals__ = { 'drag-drop': 'override',
    #                 'drag-data-get': 'override',
    #                 'drag-data-delete': 'override',
    #                 'drag-data-received': 'override' }

    def __init__(self, model, factory):
        assert isinstance (model, NamespaceModel), 'model is not a NamespaceModel (%s)' % str(model)
        self.__gobject_init__()
        gtk.TreeView.__init__(self, model)
        self.factory = factory
        self.icon_cache = {}

        self.set_property('headers-visible', False)
        self.set_property('search-column', 0)
        def search_func(model, column, key, iter, data=None):
            assert column == 0
            element = model.get_value(iter, column)
            if element.name:
                return not element.name.startswith(key)
        self.set_search_equal_func(search_func)

        self.set_rules_hint(True)
        selection = self.get_selection()
        selection.set_mode(gtk.SELECTION_BROWSE)
        column = gtk.TreeViewColumn ('')
        # First cell in the column is for an image...
        cell = gtk.CellRendererPixbuf ()
        column.pack_start (cell, 0)
        column.set_cell_data_func (cell, self._set_pixbuf, None)
        
        # Second cell if for the name of the object...
        cell = gtk.CellRendererText ()
        #cell.set_property ('editable', 1)
        cell.connect('edited', self._text_edited)
        column.pack_start (cell, 0)
        column.set_cell_data_func (cell, self._set_text, None)

        assert len (column.get_cell_renderers()) == 2
        self.append_column (column)

        # DND info:
        # drag
        self.enable_model_drag_source(gtk.gdk.BUTTON1_MASK,
                             [NamespaceView.DND_TARGETS[-1]],
                             gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
        self.drag_source_set(gtk.gdk.BUTTON1_MASK | gtk.gdk.BUTTON3_MASK,
                             NamespaceView.DND_TARGETS,
                             gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_LINK)
        self.connect('drag-data-get', NamespaceView.on_drag_data_get)

        # drop
        #self.drag_dest_set (gtk.DEST_DEFAULT_ALL, [NamespaceView.DND_TARGETS[-1]],
        #                    gtk.gdk.ACTION_DEFAULT)
        self.enable_model_drag_dest([NamespaceView.DND_TARGETS[-1]],
                                    gtk.gdk.ACTION_DEFAULT)
        self.connect('drag-data-received', NamespaceView.on_drag_data_received)
        self.connect('drag-drop', NamespaceView.on_drag_drop)
        self.connect('drag-data-delete', NamespaceView.on_drag_data_delete)


    def get_selected_element(self):
        selection = self.get_selection()
        model, iter = selection.get_selected()
        if not iter:
            return
        return model.get_value(iter, 0)


    def expand_root_nodes(self):
        self.expand_row((0,), False)


    def _set_pixbuf(self, column, cell, model, iter, data):
        value = model.get_value(iter, 0)
        try:
            icon = self.icon_cache[type(value)]
        except KeyError:
            stock_id = stock.get_stock_id(type(value))
            if stock_id:
                icon = self.render_icon(stock_id, gtk.ICON_SIZE_MENU, '')
            else:
                icon = None
            self.icon_cache[type(value)] = icon
        cell.set_property('pixbuf', icon)


    def _set_text(self, column, cell, model, iter, data):
        """
        Set font and of model elements in tree view.
        """
        value = model.get_value(iter, 0)
        text = value and (value.name or '').replace('\n', ' ') or '<None>'

        if isinstance(value, UML.Diagram):
            text = '<b>%s</b>' % text
        elif (isinstance(value, UML.Classifier) 
                or isinstance(value, UML.Operation)) and value.isAbstract:
            text = '<i>%s</i>' % text

        cell.set_property('markup', text)


    def _text_edited(self, cell, path_str, new_text):
        """
        The text has been edited. This method updates the data object.
        Note that 'path_str' is a string where the fields are separated by
        colons ':', like this: '0:1:1'. We first turn them into a tuple.
        """
        try:
            model = self.get_property('model')
            iter = model.get_iter_from_string(path_str)
            element = model.get_value(iter, 0)
            tx = Transaction()
            element.name = new_text
            tx.commit()
        except Exception, e:
            log.error('Could not create path from string "%s"' % path_str)


#    def do_drag_begin (self, context):
#        print 'do_drag_begin'


    def on_drag_data_get(self, context, selection_data, info, time):
        """
        Get the data to be dropped by on_drag_data_received().
        We send the id of the dragged element.
        """
        #log.debug('on_drag_data_get')
        selection = self.get_selection()
        model, iter = selection.get_selected()
        if iter:
            element = model.get_value(iter, 0)
            if info == NamespaceView.TARGET_ELEMENT_ID:
                selection_data.set(selection_data.target, 8, str(element.id))
            else:
                selection_data.set(selection_data.target, 8, element.name)


    def on_drag_data_delete (self, context):
        """
        DnD magic. do not touch.
        """
        self.emit_stop_by_name('drag-data-delete')


    # Drop
    def on_drag_data_received(self, context, x, y, selection, info, time):
        """
        Drop the data send by on_drag_data_get().
        """
        self.emit_stop_by_name('drag-data-received')
        #print 'drag_data_received'
        data = selection.data
        drop_info = self.get_dest_row_at_pos(x, y)
        if drop_info:
            #print 'drop_info', drop_info
            model = self.get_model()
            element = self.factory.lookup(data)
            path, position = drop_info
            iter = model.get_iter(path)
            dest_element = model.get_value(iter, 0)
            assert dest_element
            # Add the item to the parent if it is dropped on the same level,
            # else add it to the item.
            if position in (gtk.TREE_VIEW_DROP_BEFORE, gtk.TREE_VIEW_DROP_AFTER):
                parent_iter = model.iter_parent(iter)
                if parent_iter is None:
                    dest_element = None
                else:
                    dest_element = model.get_value(parent_iter, 0)

            try:
                # Check if element is part of the namespace of dest_element:
                ns = dest_element
                while ns:
                    if ns is element:
                        raise AttributeError
                    ns = ns.namespace

                # Set package. This only works for classifiers, packages and
                # diagrams. Properties and operations should not be moved.
                tx = Transaction()
                if dest_element is None:
                    del element.package
                else:
                    element.package = dest_element
                tx.commit()

            except AttributeError:
                context.drop_finish(False, time)
            else:
                context.drop_finish(True, time)
                # Finally let's try to select the element again.
                path = model.path_from_element(element)
                if len(path) > 1:
                    self.expand_row(path[:-1], False)
                selection = self.get_selection()
                selection.select_path(path)


    def on_drag_drop(self, context, x, y, time):
        """
        DnD magic. do not touch
        """
        self.emit_stop_by_name('drag-drop')
        self.drag_get_data(context, context.targets[-1], time)
        return 1


gobject.type_register(NamespaceModel)
gobject.type_register(NamespaceView)


# vim: sw=4:et:ai