source: orange/Orange/OrangeCanvas/canvas/scene.py @ 11181:a60586c66457

Revision 11181:a60586c66457, 24.2 KB checked in by Ales Erjavec <ales.erjavec@…>, 17 months ago (diff)

Added channel names to the LinkItems.

Line 
1"""
2Canvas Graphics Scene
3
4"""
5
6import logging
7from operator import attrgetter
8
9from xml.sax.saxutils import escape
10
11from PyQt4.QtGui import QGraphicsScene, QPainter, QBrush, \
12                        QGraphicsItem
13
14from PyQt4.QtCore import Qt, QPointF, QRectF, QSizeF, QLineF, QBuffer
15
16from PyQt4.QtCore import pyqtSignal as Signal
17from PyQt4.QtCore import PYQT_VERSION_STR
18
19
20from .. import scheme
21
22from . import items
23from .layout import AnchorLayout
24from .items.utils import toGraphicsObjectIfPossible, typed_signal_mapper
25
26log = logging.getLogger(__name__)
27
28
29NodeItemSignalMapper = typed_signal_mapper(items.NodeItem)
30
31
32class CanvasScene(QGraphicsScene):
33    """A Graphics Scene for displaying and editing an Orange Scheme.
34    """
35
36    node_item_added = Signal(items.NodeItem)
37    """An node item has been added to the scene"""
38
39    node_item_removed = Signal(items.LinkItem)
40    """An node item has been removed from the scene"""
41
42    node_item_position_changed = Signal(items.NodeItem, QPointF)
43    """The position of a node has changed"""
44
45    node_item_double_clicked = Signal(items.NodeItem)
46    """An node item has been double clicked"""
47
48    node_item_activated = Signal(items.NodeItem)
49    """An node item has been activated (clicked)"""
50
51    node_item_hovered = Signal(items.NodeItem)
52    """An node item has been hovered"""
53
54    link_item_added = Signal(items.LinkItem)
55    """A new link item has been added to the scene"""
56
57    link_item_removed = Signal(items.LinkItem)
58    """Link item has been removed"""
59
60    link_item_hovered = Signal(items.LinkItem)
61    """Link item has been hovered"""
62
63    annotation_added = Signal(items.annotationitem.Annotation)
64    """Annotation item has been added"""
65
66    annotation_removed = Signal(items.annotationitem.Annotation)
67    """Annotation item has been removed"""
68
69    def __init__(self, *args, **kwargs):
70        QGraphicsScene.__init__(self, *args, **kwargs)
71
72        self.scheme = None
73        self.registry = None
74
75        # All node items
76        self.__node_items = []
77        # Mapping from SchemeNodes to canvas items
78        self.__item_for_node = {}
79        # All link items
80        self.__link_items = []
81        # Mapping from SchemeLinks to canvas items.
82        self.__item_for_link = {}
83
84        # All annotation items
85        self.__annotation_items = []
86        # Mapping from SchemeAnnotations to canvas items.
87        self.__item_for_annotation = {}
88
89        # Is the scene editable
90        self.editable = True
91
92        # Anchor Layout
93        self.__anchor_layout = AnchorLayout()
94        self.addItem(self.__anchor_layout)
95
96        self.__channel_names_visible = True
97
98        self.user_interaction_handler = None
99
100        self.activated_mapper = NodeItemSignalMapper(self)
101        self.activated_mapper.pyMapped.connect(
102            self.node_item_activated
103        )
104
105        self.hovered_mapper = NodeItemSignalMapper(self)
106        self.hovered_mapper.pyMapped.connect(
107            self.node_item_hovered
108        )
109
110        self.position_change_mapper = NodeItemSignalMapper(self)
111        self.position_change_mapper.pyMapped.connect(
112            self._on_position_change
113        )
114
115        log.info("'%s' intitialized." % self)
116
117    def clear_scene(self):
118        self.scheme = None
119        self.__node_items = []
120        self.__item_for_node = {}
121        self.__link_items = []
122        self.__item_for_link = {}
123        self.__annotation_items = []
124        self.__item_for_annotation = {}
125
126        self.__anchor_layout.deleteLater()
127
128        self.user_interaction_handler = None
129
130        self.clear()
131        log.info("'%s' cleared." % self)
132
133    def set_scheme(self, scheme):
134        """Set the scheme to display and edit. Populates the scene
135        with nodes and links already in the scheme.
136
137        """
138        if self.scheme is not None:
139            # Clear the old scheme
140            self.scheme.node_added.disconnect(self.add_node)
141            self.scheme.node_removed.disconnect(self.remove_node)
142
143            self.scheme.link_added.disconnect(self.add_link)
144            self.scheme.link_removed.disconnect(self.remove_link)
145
146            self.scheme.annotation_added.disconnect(self.add_annotation)
147            self.scheme.annotation_removed.disconnect(self.remove_annotation)
148
149            self.scheme.node_state_changed.disconnect(
150                self.on_widget_state_change
151            )
152            self.scheme.channel_state_changed.disconnect(
153                self.on_link_state_change
154            )
155
156            self.clear_scene()
157
158        log.info("Setting scheme '%s' on '%s'" % (scheme, self))
159
160        self.scheme = scheme
161        if self.scheme is not None:
162            self.scheme.node_added.connect(self.add_node)
163            self.scheme.node_removed.connect(self.remove_node)
164
165            self.scheme.link_added.connect(self.add_link)
166            self.scheme.link_removed.connect(self.remove_link)
167
168            self.scheme.annotation_added.connect(self.add_annotation)
169            self.scheme.annotation_removed.connect(self.remove_annotation)
170
171            self.scheme.node_state_changed.connect(
172                self.on_widget_state_change
173            )
174            self.scheme.channel_state_changed.connect(
175                self.on_link_state_change
176            )
177
178            self.scheme.topology_changed.connect(self.on_scheme_change)
179
180        for node in scheme.nodes:
181            self.add_node(node)
182
183        for link in scheme.links:
184            self.add_link(link)
185
186        for annot in scheme.annotations:
187            self.add_annotation(annot)
188
189    def set_registry(self, registry):
190        """Set the widget registry.
191        """
192        log.info("Setting registry '%s on '%s'." % (registry, self))
193        self.registry = registry
194
195    def set_anchor_layout(self, layout):
196        if self.__anchor_layout != layout:
197            if self.__anchor_layout:
198                self.__anchor_layout.deleteLater()
199                self.__anchor_layout = None
200
201            self.__anchor_layout = layout
202
203    def anchor_layout(self):
204        return self.__anchor_layout
205
206    def set_channel_names_visible(self, visible):
207        self.__channel_names_visible = visible
208        for link in self.__link_items:
209            link.setChannelNamesVisible(visible)
210
211    def channel_names_visible(self):
212        return self.__channel_names_visible
213
214    def add_node_item(self, item):
215        """Add a :class:`NodeItem` instance to the scene.
216        """
217        if item in self.__node_items:
218            raise ValueError("%r is already in the scene." % item)
219
220        if item.pos().isNull():
221            if self.__node_items:
222                pos = self.__node_items[-1].pos() + QPointF(150, 0)
223            else:
224                pos = QPointF(150, 150)
225
226            item.setPos(pos)
227
228        # Set signal mappings
229        self.activated_mapper.setPyMapping(item, item)
230        item.activated.connect(self.activated_mapper.pyMap)
231
232        self.hovered_mapper.setPyMapping(item, item)
233        item.hovered.connect(self.hovered_mapper.pyMap)
234
235        self.position_change_mapper.setPyMapping(item, item)
236        item.positionChanged.connect(self.position_change_mapper.pyMap)
237
238        self.addItem(item)
239
240        self.__node_items.append(item)
241
242        self.node_item_added.emit(item)
243
244        log.info("Added item '%s' to '%s'" % (item, self))
245        return item
246
247    def add_node(self, node):
248        """Add and return a default constructed `NodeItem` for a
249        `SchemeNode` instance. If the node is already in the scene
250        do nothing and just return its item.
251
252        """
253        if node in self.__item_for_node:
254            # Already added
255            return self.__item_for_node[node]
256
257        item = self.new_node_item(node.description)
258
259        if node.position:
260            pos = QPointF(*node.position)
261            item.setPos(pos)
262
263        self.__item_for_node[node] = item
264
265        node.position_changed.connect(self.__on_node_pos_changed)
266        node.title_changed.connect(item.setTitle)
267        node.progress_changed.connect(item.setProgress)
268        node.processing_state_changed.connect(item.setProcessingState)
269        return self.add_node_item(item)
270
271    def new_node_item(self, widget_desc, category_desc=None):
272        """Construct an new `NodeItem` from a `WidgetDescription`.
273        Optionally also set `CategoryDescription`.
274
275        """
276        item = items.NodeItem()
277        item.setWidgetDescription(widget_desc)
278
279        if category_desc is None and self.registry and widget_desc.category:
280            category_desc = self.registry.category(widget_desc.category)
281
282        if category_desc is None and self.registry is not None:
283            try:
284                category_desc = self.registry.category(widget_desc.category)
285            except KeyError:
286                pass
287
288        if category_desc is not None:
289            item.setWidgetCategory(category_desc)
290
291        return item
292
293    def remove_node_item(self, item):
294        """Remove `item` (:class:`NodeItem`) from the scene.
295        """
296        self.activated_mapper.removePyMappings(item)
297        self.hovered_mapper.removePyMappings(item)
298
299        item.hide()
300        self.removeItem(item)
301        self.__node_items.remove(item)
302
303        self.node_item_removed.emit(item)
304
305        log.info("Removed item '%s' from '%s'" % (item, self))
306
307    def remove_node(self, node):
308        """Remove the `NodeItem` instance that was previously constructed for
309        a `SchemeNode` node using the `add_node` method.
310
311        """
312        item = self.__item_for_node.pop(node)
313
314        node.position_changed.disconnect(self.__on_node_pos_changed)
315        node.title_changed.disconnect(item.setTitle)
316        node.progress_changed.disconnect(item.setProgress)
317        node.processing_state_changed.disconnect(item.setProcessingState)
318
319        self.remove_node_item(item)
320
321    def node_items(self):
322        """Return all :class:`NodeItem` instances in the scene.
323        """
324        return list(self.__node_items)
325
326    def add_link_item(self, item):
327        """Add a link (:class:`LinkItem`)to the scene.
328        """
329        if item.scene() is not self:
330            self.addItem(item)
331
332        self.__link_items.append(item)
333
334        self.link_item_added.emit(item)
335
336        log.info("Added link %r -> %r to '%s'" % \
337                 (item.sourceItem.title, item.sinkItem.title, self))
338
339        self.__anchor_layout.invalidateLink(item)
340
341        return item
342
343    def add_link(self, scheme_link):
344        """Create and add a `LinkItem` instance for a `SchemeLink`
345        instance. If the link is already in the scene do nothing
346        and just return its `LinkItem`.
347
348        """
349        if scheme_link in self.__item_for_link:
350            return self.__item_for_link[scheme_link]
351
352        source = self.__item_for_node[scheme_link.source_node]
353        sink = self.__item_for_node[scheme_link.sink_node]
354
355        item = self.new_link_item(source, scheme_link.source_channel,
356                                  sink, scheme_link.sink_channel)
357
358        item.setEnabled(scheme_link.enabled)
359
360        scheme_link.enabled_changed.connect(item.setEnabled)
361
362        self.add_link_item(item)
363        self.__item_for_link[scheme_link] = item
364        return item
365
366    def new_link_item(self, source_item, source_channel,
367                      sink_item, sink_channel):
368        """Construct and return a new `LinkItem`
369        """
370        item = items.LinkItem()
371        item.setSourceItem(source_item)
372        item.setSinkItem(sink_item)
373        fmt = "<b>{0}</b>&nbsp;-->&nbsp;<b>{1}</b>"
374        item.setToolTip(
375            fmt.format(escape(source_channel.name),
376                       escape(sink_channel.name))
377        )
378
379        item.setSourceName(source_channel.name)
380        item.setSinkName(sink_channel.name)
381        item.setChannelNamesVisible(self.__channel_names_visible)
382
383        return item
384
385    def remove_link_item(self, item):
386        """Remove a link (:class:`LinkItem`) from the scene.
387        """
388        self.__link_items.remove(item)
389
390        # Remove the anchor points.
391        item.removeLink()
392        self.removeItem(item)
393        self.link_item_removed.emit(item)
394
395        log.info("Removed link '%s' from '%s'" % (item, self))
396
397        return item
398
399    def remove_link(self, scheme_link):
400        """ Remove a `LinkItem` instance that was previously constructed for
401        a `SchemeLink` node using the `add_link` method.
402
403        """
404        item = self.__item_for_link.pop(scheme_link)
405        scheme_link.enabled_changed.disconnect(item.setEnabled)
406        self.remove_link_item(item)
407
408    def link_items(self):
409        """Return all :class:`LinkItems` in the scene.
410
411        """
412        return list(self.__link_items)
413
414    def add_annotation_item(self, annotation):
415        """Add an `Annotation` item to the scene.
416
417        """
418        self.__annotation_items.append(annotation)
419        self.addItem(annotation)
420        self.annotation_added.emit(annotation)
421        return annotation
422
423    def add_annotation(self, scheme_annot):
424        """Create a new item for :class:`SchemeAnnotation` and add it
425        to the scene. If the `scheme_annot` is already in the scene do
426        nothing and just return its item.
427
428        """
429        if scheme_annot in self.__item_for_annotation:
430            # Already added
431            return self.__item_for_annotation[scheme_annot]
432
433        if isinstance(scheme_annot, scheme.SchemeTextAnnotation):
434            item = items.TextAnnotation()
435            item.setPlainText(scheme_annot.text)
436            x, y, w, h = scheme_annot.rect
437            item.setPos(x, y)
438            item.resize(w, h)
439            item.setTextInteractionFlags(Qt.TextEditorInteraction)
440            scheme_annot.text_changed.connect(item.setPlainText)
441
442        elif isinstance(scheme_annot, scheme.SchemeArrowAnnotation):
443            item = items.ArrowAnnotation()
444            start, end = scheme_annot.start_pos, scheme_annot.end_pos
445            item.setLine(QLineF(QPointF(*start), QPointF(*end)))
446
447        scheme_annot.geometry_changed.connect(
448            self.__on_scheme_annot_geometry_change
449        )
450
451        self.add_annotation_item(item)
452        self.__item_for_annotation[scheme_annot] = item
453
454        return item
455
456    def remove_annotation_item(self, annotation):
457        """Remove an `Annotation` item from the scene.
458
459        """
460        self.__annotation_items.remove(annotation)
461        self.removeItem(annotation)
462        self.annotation_removed.emit(annotation)
463
464    def remove_annotation(self, scheme_annotation):
465        item = self.__item_for_annotation.pop(scheme_annotation)
466
467        scheme_annotation.geometry_changed.disconnect(
468            self.__on_scheme_annot_geometry_change
469        )
470
471        if isinstance(scheme_annotation, scheme.SchemeTextAnnotation):
472            scheme_annotation.text_changed.disconnect(
473                item.setPlainText
474            )
475
476        self.remove_annotation_item(item)
477
478    def annotation_items(self):
479        """Return all `Annotation` items in the scene.
480
481        """
482        return self.__annotation_items
483
484    def item_for_annotation(self, scheme_annotation):
485        return self.__item_for_annotation[scheme_annotation]
486
487    def annotation_for_item(self, item):
488        rev = dict(reversed(item) \
489                   for item in self.__item_for_annotation.items())
490        return rev[item]
491
492    def commit_scheme_node(self, node):
493        """Commit the `node` into the scheme.
494        """
495        if not self.editable:
496            raise Exception("Scheme not editable.")
497
498        if node not in self.__item_for_node:
499            raise ValueError("No 'NodeItem' for node.")
500
501        item = self.__item_for_node[node]
502
503        try:
504            self.scheme.add_node(node)
505        except Exception:
506            log.error("An unexpected error occurred while commiting node '%s'",
507                      node, exc_info=True)
508            # Cleanup (remove the node item)
509            self.remove_node_item(item)
510            raise
511
512        log.info("Commited node '%s' from '%s' to '%s'" % \
513                 (node, self, self.scheme))
514
515    def commit_scheme_link(self, link):
516        """Commit a scheme link.
517        """
518        if not self.editable:
519            raise Exception("Scheme not editable")
520
521        if link not in self.__item_for_link:
522            raise ValueError("No 'LinkItem' for link.")
523
524        self.scheme.add_link(link)
525        log.info("Commited link '%s' from '%s' to '%s'" % \
526                 (link, self, self.scheme))
527
528    def node_for_item(self, item):
529        """Return the `SchemeNode` for the `item`.
530        """
531        rev = dict([(v, k) for k, v in self.__item_for_node.items()])
532        return rev[item]
533
534    def item_for_node(self, node):
535        """Return the :class:`NodeItem` instance for a :class:`SchemeNode`.
536        """
537        return self.__item_for_node[node]
538
539    def link_for_item(self, item):
540        """Return the `SchemeLink for `item` (:class:`LinkItem`).
541        """
542        rev = dict([(v, k) for k, v in self.__item_for_link.items()])
543        return rev[item]
544
545    def item_for_link(self, link):
546        """Return the :class:`LinkItem` for a :class:`SchemeLink`
547        """
548        return self.__item_for_link[link]
549
550    def selected_node_items(self):
551        """Return the selected :class:`NodeItem`'s.
552        """
553        return [item for item in self.__node_items if item.isSelected()]
554
555    def selected_annotation_items(self):
556        """Return the selected :class:`Annotation`'s
557        """
558        return [item for item in self.__annotation_items if item.isSelected()]
559
560    def node_links(self, node_item):
561        """Return all links from the `node_item` (:class:`NodeItem`).
562        """
563        return self.node_output_links(node_item) + \
564               self.node_input_links(node_item)
565
566    def node_output_links(self, node_item):
567        """Return a list of all output links from `node_item`.
568        """
569        return [link for link in self.__link_items
570                if link.sourceItem == node_item]
571
572    def node_input_links(self, node_item):
573        """Return a list of all input links for `node_item`.
574        """
575        return [link for link in self.__link_items
576                if link.sinkItem == node_item]
577
578    def neighbor_nodes(self, node_item):
579        """Return a list of `node_item`'s (class:`NodeItem`) neighbor nodes.
580        """
581        neighbors = map(attrgetter("sourceItem"),
582                        self.node_input_links(node_item))
583
584        neighbors.extend(map(attrgetter("sinkItem"),
585                             self.node_output_links(node_item)))
586        return neighbors
587
588    def on_widget_state_change(self, widget, state):
589        pass
590
591    def on_link_state_change(self, link, state):
592        pass
593
594    def on_scheme_change(self, ):
595        pass
596
597    def _on_position_change(self, item):
598        # Invalidate the anchor point layout and schedule a layout.
599        self.__anchor_layout.invalidateNode(item)
600
601        self.node_item_position_changed.emit(item, item.pos())
602
603    def __on_node_pos_changed(self, pos):
604        node = self.sender()
605        item = self.__item_for_node[node]
606        item.setPos(*pos)
607
608    def __on_scheme_annot_geometry_change(self):
609        annot = self.sender()
610        item = self.__item_for_annotation[annot]
611        if isinstance(annot, scheme.SchemeTextAnnotation):
612            item.setGeometry(QRectF(*annot.rect))
613        elif isinstance(annot, scheme.SchemeArrowAnnotation):
614            p1 = item.mapFromScene(QPointF(*annot.start_pos))
615            p2 = item.mapFromScene(QPointF(*annot.end_pos))
616            item.setLine(QLineF(p1, p2))
617        else:
618            pass
619
620    def item_at(self, pos, type_or_tuple=None):
621        rect = QRectF(pos - QPointF(1.5, 1.5), QSizeF(3, 3))
622        items = self.items(rect)
623        if type_or_tuple:
624            items = [i for i in items if isinstance(i, type_or_tuple)]
625
626        return items[0] if items else None
627
628    if PYQT_VERSION_STR < "4.9":
629        # For QGraphicsObject subclasses items, itemAt ... return a
630        # QGraphicsItem wrapper instance and not the actual class instance.
631        def itemAt(self, *args, **kwargs):
632            item = QGraphicsScene.itemAt(self, *args, **kwargs)
633            return toGraphicsObjectIfPossible(item)
634
635        def items(self, *args, **kwargs):
636            items = QGraphicsScene.items(self, *args, **kwargs)
637            return map(toGraphicsObjectIfPossible, items)
638
639        def selectedItems(self, *args, **kwargs):
640            return map(toGraphicsObjectIfPossible,
641                       QGraphicsScene.selectedItems(self, *args, **kwargs))
642
643        def collidingItems(self, *args, **kwargs):
644            return map(toGraphicsObjectIfPossible,
645                       QGraphicsScene.collidingItems(self, *args, **kwargs))
646
647        def focusItem(self, *args, **kwargs):
648            item = QGraphicsScene.focusItem(self, *args, **kwargs)
649            return toGraphicsObjectIfPossible(item)
650
651        def mouseGrabberItem(self, *args, **kwargs):
652            item = QGraphicsScene.mouseGrabberItem(self, *args, **kwargs)
653            return toGraphicsObjectIfPossible(item)
654
655    def mousePressEvent(self, event):
656        if self.user_interaction_handler and \
657                self.user_interaction_handler.mousePressEvent(event):
658            return
659
660        # Right (context) click on the node item. If the widget is not
661        # in the current selection then select the widget (only the widget).
662        # Else simply return and let customContextMenuReqested signal
663        # handle it
664        shape_item = self.item_at(event.scenePos(), items.NodeItem)
665        if shape_item and event.button() == Qt.RightButton and \
666                shape_item.flags() & QGraphicsItem.ItemIsSelectable:
667            if not shape_item.isSelected():
668                self.clearSelection()
669                shape_item.setSelected(True)
670
671        return QGraphicsScene.mousePressEvent(self, event)
672
673    def mouseMoveEvent(self, event):
674        if self.user_interaction_handler and \
675                self.user_interaction_handler.mouseMoveEvent(event):
676            return
677
678        return QGraphicsScene.mouseMoveEvent(self, event)
679
680    def mouseReleaseEvent(self, event):
681        if self.user_interaction_handler and \
682                self.user_interaction_handler.mouseReleaseEvent(event):
683            return
684        return QGraphicsScene.mouseReleaseEvent(self, event)
685
686    def mouseDoubleClickEvent(self, event):
687        if self.user_interaction_handler and \
688                self.user_interaction_handler.mouseDoubleClickEvent(event):
689            return
690
691        return QGraphicsScene.mouseDoubleClickEvent(self, event)
692
693    def keyPressEvent(self, event):
694        if self.user_interaction_handler and \
695                self.user_interaction_handler.keyPressEvent(event):
696            return
697        return QGraphicsScene.keyPressEvent(self, event)
698
699    def keyReleaseEvent(self, event):
700        if self.user_interaction_handler and \
701                self.user_interaction_handler.keyReleaseEvent(event):
702            return
703        return QGraphicsScene.keyReleaseEvent(self, event)
704
705    def set_user_interaction_handler(self, handler):
706        if self.user_interaction_handler and \
707                not self.user_interaction_handler.finished:
708            self.user_interaction_handler.cancel()
709
710        log.info("Setting interaction '%s' to '%s'" % (handler, self))
711
712        self.user_interaction_handler = handler
713        if handler:
714            handler.start()
715
716    def __str__(self):
717        return "%s(objectName=%r, ...)" % \
718                (type(self).__name__, str(self.objectName()))
719
720
721def grab_svg(scene):
722    """Return a SVG rendering of the scene contents.
723    """
724    from PyQt4.QtSvg import QSvgGenerator
725    svg_buffer = QBuffer()
726    gen = QSvgGenerator()
727    gen.setOutputDevice(svg_buffer)
728
729    items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10)
730
731    if items_rect.isNull():
732        items_rect = QRectF(0, 0, 10, 10)
733
734    width, height = items_rect.width(), items_rect.height()
735    rect_ratio = float(width) / height
736
737    # Keep a fixed aspect ratio.
738    aspect_ratio = 1.618
739    if rect_ratio > aspect_ratio:
740        height = int(height * rect_ratio / aspect_ratio)
741    else:
742        width = int(width * aspect_ratio / rect_ratio)
743
744    target_rect = QRectF(0, 0, width, height)
745    source_rect = QRectF(0, 0, width, height)
746    source_rect.moveCenter(items_rect.center())
747
748    gen.setSize(target_rect.size().toSize())
749    gen.setViewBox(target_rect)
750
751    painter = QPainter(gen)
752
753    # Draw background.
754    painter.setBrush(QBrush(Qt.white))
755    painter.drawRect(target_rect)
756
757    # Render the scene
758    scene.render(painter, target_rect, source_rect)
759    painter.end()
760
761    return unicode(svg_buffer.buffer())
Note: See TracBrowser for help on using the repository browser.