source: orange/Orange/OrangeCanvas/canvas/scene.py @ 11207:8145a5984767

Revision 11207:8145a5984767, 25.2 KB checked in by Ales Erjavec <ales.erjavec@…>, 17 months ago (diff)

Fixed anchor point layout order reset while dragging (creating) a new link.

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, QColor, QFont, \
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        scheme_link.enabled_changed.connect(item.setEnabled)
360
361        if scheme_link.is_dynamic():
362            item.setDynamic(True)
363            item.setDynamicEnabled(scheme_link.dynamic_enabled)
364            scheme_link.dynamic_enabled_changed.connect(item.setDynamicEnabled)
365
366        self.add_link_item(item)
367        self.__item_for_link[scheme_link] = item
368        return item
369
370    def new_link_item(self, source_item, source_channel,
371                      sink_item, sink_channel):
372        """Construct and return a new `LinkItem`
373        """
374        item = items.LinkItem()
375        item.setSourceItem(source_item)
376        item.setSinkItem(sink_item)
377        fmt = "<b>{0}</b>&nbsp;-->&nbsp;<b>{1}</b>"
378        item.setToolTip(
379            fmt.format(escape(source_channel.name),
380                       escape(sink_channel.name))
381        )
382
383        item.setSourceName(source_channel.name)
384        item.setSinkName(sink_channel.name)
385        item.setChannelNamesVisible(self.__channel_names_visible)
386
387        return item
388
389    def remove_link_item(self, item):
390        """Remove a link (:class:`LinkItem`) from the scene.
391        """
392        # Invalidate the anchor layout.
393        self.__anchor_layout.invalidateAnchorItem(
394            item.sourceItem.outputAnchorItem
395        )
396        self.__anchor_layout.invalidateAnchorItem(
397            item.sinkItem.inputAnchorItem
398        )
399
400        self.__link_items.remove(item)
401
402        # Remove the anchor points.
403        item.removeLink()
404        self.removeItem(item)
405
406        self.link_item_removed.emit(item)
407
408        log.info("Removed link '%s' from '%s'" % (item, self))
409
410        return item
411
412    def remove_link(self, scheme_link):
413        """ Remove a `LinkItem` instance that was previously constructed for
414        a `SchemeLink` node using the `add_link` method.
415
416        """
417        item = self.__item_for_link.pop(scheme_link)
418        scheme_link.enabled_changed.disconnect(item.setEnabled)
419        self.remove_link_item(item)
420
421    def link_items(self):
422        """Return all :class:`LinkItems` in the scene.
423
424        """
425        return list(self.__link_items)
426
427    def add_annotation_item(self, annotation):
428        """Add an `Annotation` item to the scene.
429
430        """
431        self.__annotation_items.append(annotation)
432        self.addItem(annotation)
433        self.annotation_added.emit(annotation)
434        return annotation
435
436    def add_annotation(self, scheme_annot):
437        """Create a new item for :class:`SchemeAnnotation` and add it
438        to the scene. If the `scheme_annot` is already in the scene do
439        nothing and just return its item.
440
441        """
442        if scheme_annot in self.__item_for_annotation:
443            # Already added
444            return self.__item_for_annotation[scheme_annot]
445
446        if isinstance(scheme_annot, scheme.SchemeTextAnnotation):
447            item = items.TextAnnotation()
448            item.setPlainText(scheme_annot.text)
449            x, y, w, h = scheme_annot.rect
450            item.setPos(x, y)
451            item.resize(w, h)
452            item.setTextInteractionFlags(Qt.TextEditorInteraction)
453
454            font = font_from_dict(scheme_annot.font, item.font())
455            item.setFont(font)
456            scheme_annot.text_changed.connect(item.setPlainText)
457
458        elif isinstance(scheme_annot, scheme.SchemeArrowAnnotation):
459            item = items.ArrowAnnotation()
460            start, end = scheme_annot.start_pos, scheme_annot.end_pos
461            item.setLine(QLineF(QPointF(*start), QPointF(*end)))
462            item.setColor(QColor(scheme_annot.color))
463
464        scheme_annot.geometry_changed.connect(
465            self.__on_scheme_annot_geometry_change
466        )
467
468        self.add_annotation_item(item)
469        self.__item_for_annotation[scheme_annot] = item
470
471        return item
472
473    def remove_annotation_item(self, annotation):
474        """Remove an `Annotation` item from the scene.
475
476        """
477        self.__annotation_items.remove(annotation)
478        self.removeItem(annotation)
479        self.annotation_removed.emit(annotation)
480
481    def remove_annotation(self, scheme_annotation):
482        item = self.__item_for_annotation.pop(scheme_annotation)
483
484        scheme_annotation.geometry_changed.disconnect(
485            self.__on_scheme_annot_geometry_change
486        )
487
488        if isinstance(scheme_annotation, scheme.SchemeTextAnnotation):
489            scheme_annotation.text_changed.disconnect(
490                item.setPlainText
491            )
492
493        self.remove_annotation_item(item)
494
495    def annotation_items(self):
496        """Return all `Annotation` items in the scene.
497
498        """
499        return self.__annotation_items
500
501    def item_for_annotation(self, scheme_annotation):
502        return self.__item_for_annotation[scheme_annotation]
503
504    def annotation_for_item(self, item):
505        rev = dict(reversed(item) \
506                   for item in self.__item_for_annotation.items())
507        return rev[item]
508
509    def commit_scheme_node(self, node):
510        """Commit the `node` into the scheme.
511        """
512        if not self.editable:
513            raise Exception("Scheme not editable.")
514
515        if node not in self.__item_for_node:
516            raise ValueError("No 'NodeItem' for node.")
517
518        item = self.__item_for_node[node]
519
520        try:
521            self.scheme.add_node(node)
522        except Exception:
523            log.error("An unexpected error occurred while commiting node '%s'",
524                      node, exc_info=True)
525            # Cleanup (remove the node item)
526            self.remove_node_item(item)
527            raise
528
529        log.info("Commited node '%s' from '%s' to '%s'" % \
530                 (node, self, self.scheme))
531
532    def commit_scheme_link(self, link):
533        """Commit a scheme link.
534        """
535        if not self.editable:
536            raise Exception("Scheme not editable")
537
538        if link not in self.__item_for_link:
539            raise ValueError("No 'LinkItem' for link.")
540
541        self.scheme.add_link(link)
542        log.info("Commited link '%s' from '%s' to '%s'" % \
543                 (link, self, self.scheme))
544
545    def node_for_item(self, item):
546        """Return the `SchemeNode` for the `item`.
547        """
548        rev = dict([(v, k) for k, v in self.__item_for_node.items()])
549        return rev[item]
550
551    def item_for_node(self, node):
552        """Return the :class:`NodeItem` instance for a :class:`SchemeNode`.
553        """
554        return self.__item_for_node[node]
555
556    def link_for_item(self, item):
557        """Return the `SchemeLink for `item` (:class:`LinkItem`).
558        """
559        rev = dict([(v, k) for k, v in self.__item_for_link.items()])
560        return rev[item]
561
562    def item_for_link(self, link):
563        """Return the :class:`LinkItem` for a :class:`SchemeLink`
564        """
565        return self.__item_for_link[link]
566
567    def selected_node_items(self):
568        """Return the selected :class:`NodeItem`'s.
569        """
570        return [item for item in self.__node_items if item.isSelected()]
571
572    def selected_annotation_items(self):
573        """Return the selected :class:`Annotation`'s
574        """
575        return [item for item in self.__annotation_items if item.isSelected()]
576
577    def node_links(self, node_item):
578        """Return all links from the `node_item` (:class:`NodeItem`).
579        """
580        return self.node_output_links(node_item) + \
581               self.node_input_links(node_item)
582
583    def node_output_links(self, node_item):
584        """Return a list of all output links from `node_item`.
585        """
586        return [link for link in self.__link_items
587                if link.sourceItem == node_item]
588
589    def node_input_links(self, node_item):
590        """Return a list of all input links for `node_item`.
591        """
592        return [link for link in self.__link_items
593                if link.sinkItem == node_item]
594
595    def neighbor_nodes(self, node_item):
596        """Return a list of `node_item`'s (class:`NodeItem`) neighbor nodes.
597        """
598        neighbors = map(attrgetter("sourceItem"),
599                        self.node_input_links(node_item))
600
601        neighbors.extend(map(attrgetter("sinkItem"),
602                             self.node_output_links(node_item)))
603        return neighbors
604
605    def on_widget_state_change(self, widget, state):
606        pass
607
608    def on_link_state_change(self, link, state):
609        pass
610
611    def on_scheme_change(self, ):
612        pass
613
614    def _on_position_change(self, item):
615        # Invalidate the anchor point layout and schedule a layout.
616        self.__anchor_layout.invalidateNode(item)
617
618        self.node_item_position_changed.emit(item, item.pos())
619
620    def __on_node_pos_changed(self, pos):
621        node = self.sender()
622        item = self.__item_for_node[node]
623        item.setPos(*pos)
624
625    def __on_scheme_annot_geometry_change(self):
626        annot = self.sender()
627        item = self.__item_for_annotation[annot]
628        if isinstance(annot, scheme.SchemeTextAnnotation):
629            item.setGeometry(QRectF(*annot.rect))
630        elif isinstance(annot, scheme.SchemeArrowAnnotation):
631            p1 = item.mapFromScene(QPointF(*annot.start_pos))
632            p2 = item.mapFromScene(QPointF(*annot.end_pos))
633            item.setLine(QLineF(p1, p2))
634        else:
635            pass
636
637    def item_at(self, pos, type_or_tuple=None):
638        rect = QRectF(pos - QPointF(1.5, 1.5), QSizeF(3, 3))
639        items = self.items(rect)
640        if type_or_tuple:
641            items = [i for i in items if isinstance(i, type_or_tuple)]
642
643        return items[0] if items else None
644
645    if PYQT_VERSION_STR < "4.9":
646        # For QGraphicsObject subclasses items, itemAt ... return a
647        # QGraphicsItem wrapper instance and not the actual class instance.
648        def itemAt(self, *args, **kwargs):
649            item = QGraphicsScene.itemAt(self, *args, **kwargs)
650            return toGraphicsObjectIfPossible(item)
651
652        def items(self, *args, **kwargs):
653            items = QGraphicsScene.items(self, *args, **kwargs)
654            return map(toGraphicsObjectIfPossible, items)
655
656        def selectedItems(self, *args, **kwargs):
657            return map(toGraphicsObjectIfPossible,
658                       QGraphicsScene.selectedItems(self, *args, **kwargs))
659
660        def collidingItems(self, *args, **kwargs):
661            return map(toGraphicsObjectIfPossible,
662                       QGraphicsScene.collidingItems(self, *args, **kwargs))
663
664        def focusItem(self, *args, **kwargs):
665            item = QGraphicsScene.focusItem(self, *args, **kwargs)
666            return toGraphicsObjectIfPossible(item)
667
668        def mouseGrabberItem(self, *args, **kwargs):
669            item = QGraphicsScene.mouseGrabberItem(self, *args, **kwargs)
670            return toGraphicsObjectIfPossible(item)
671
672    def mousePressEvent(self, event):
673        if self.user_interaction_handler and \
674                self.user_interaction_handler.mousePressEvent(event):
675            return
676
677        # Right (context) click on the node item. If the widget is not
678        # in the current selection then select the widget (only the widget).
679        # Else simply return and let customContextMenuReqested signal
680        # handle it
681        shape_item = self.item_at(event.scenePos(), items.NodeItem)
682        if shape_item and event.button() == Qt.RightButton and \
683                shape_item.flags() & QGraphicsItem.ItemIsSelectable:
684            if not shape_item.isSelected():
685                self.clearSelection()
686                shape_item.setSelected(True)
687
688        return QGraphicsScene.mousePressEvent(self, event)
689
690    def mouseMoveEvent(self, event):
691        if self.user_interaction_handler and \
692                self.user_interaction_handler.mouseMoveEvent(event):
693            return
694
695        return QGraphicsScene.mouseMoveEvent(self, event)
696
697    def mouseReleaseEvent(self, event):
698        if self.user_interaction_handler and \
699                self.user_interaction_handler.mouseReleaseEvent(event):
700            return
701        return QGraphicsScene.mouseReleaseEvent(self, event)
702
703    def mouseDoubleClickEvent(self, event):
704        if self.user_interaction_handler and \
705                self.user_interaction_handler.mouseDoubleClickEvent(event):
706            return
707
708        return QGraphicsScene.mouseDoubleClickEvent(self, event)
709
710    def keyPressEvent(self, event):
711        if self.user_interaction_handler and \
712                self.user_interaction_handler.keyPressEvent(event):
713            return
714        return QGraphicsScene.keyPressEvent(self, event)
715
716    def keyReleaseEvent(self, event):
717        if self.user_interaction_handler and \
718                self.user_interaction_handler.keyReleaseEvent(event):
719            return
720        return QGraphicsScene.keyReleaseEvent(self, event)
721
722    def set_user_interaction_handler(self, handler):
723        if self.user_interaction_handler and \
724                not self.user_interaction_handler.isFinished():
725            self.user_interaction_handler.cancel()
726
727        log.info("Setting interaction '%s' to '%s'" % (handler, self))
728
729        self.user_interaction_handler = handler
730        if handler:
731            handler.start()
732
733    def __str__(self):
734        return "%s(objectName=%r, ...)" % \
735                (type(self).__name__, str(self.objectName()))
736
737
738def font_from_dict(font_dict, font=None):
739    if font is None:
740        font = QFont()
741    else:
742        font = QFont(font)
743
744    if "family" in font_dict:
745        font.setFamily(font_dict["family"])
746
747    if "size" in font_dict:
748        font.setPointSize(font_dict["size"])
749
750    return font
751
752
753def grab_svg(scene):
754    """Return a SVG rendering of the scene contents.
755    """
756    from PyQt4.QtSvg import QSvgGenerator
757    svg_buffer = QBuffer()
758    gen = QSvgGenerator()
759    gen.setOutputDevice(svg_buffer)
760
761    items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10)
762
763    if items_rect.isNull():
764        items_rect = QRectF(0, 0, 10, 10)
765
766    width, height = items_rect.width(), items_rect.height()
767    rect_ratio = float(width) / height
768
769    # Keep a fixed aspect ratio.
770    aspect_ratio = 1.618
771    if rect_ratio > aspect_ratio:
772        height = int(height * rect_ratio / aspect_ratio)
773    else:
774        width = int(width * aspect_ratio / rect_ratio)
775
776    target_rect = QRectF(0, 0, width, height)
777    source_rect = QRectF(0, 0, width, height)
778    source_rect.moveCenter(items_rect.center())
779
780    gen.setSize(target_rect.size().toSize())
781    gen.setViewBox(target_rect)
782
783    painter = QPainter(gen)
784
785    # Draw background.
786    painter.setBrush(QBrush(Qt.white))
787    painter.drawRect(target_rect)
788
789    # Render the scene
790    scene.render(painter, target_rect, source_rect)
791    painter.end()
792
793    buffer_str = str(svg_buffer.buffer())
794    return unicode(buffer_str.decode("utf-8"))
Note: See TracBrowser for help on using the repository browser.