plot_directpainter.py 9.99 KB
Newer Older
xuebingbing's avatar
xuebingbing committed
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
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 Uwe Rathmann, for the original C++ code
# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization
# (see LICENSE file for more details)

"""
QwtPlotDirectPainter
--------------------

.. autoclass:: QwtPlotDirectPainter
   :members:
"""

from qwt.qt.QtGui import QPainter, QRegion
from qwt.qt.QtCore import QObject, QT_VERSION, Qt, QEvent

from qwt.plot import QwtPlotItem
from qwt.plot_canvas import QwtPlotCanvas


def qwtRenderItem(painter, canvasRect, seriesItem, from_, to):
    #TODO: A minor performance improvement is possible with caching the maps
    plot = seriesItem.plot()
    xMap = plot.canvasMap(seriesItem.xAxis())
    yMap = plot.canvasMap(seriesItem.yAxis())
    painter.setRenderHint(QPainter.Antialiasing,
                      seriesItem.testRenderHint(QwtPlotItem.RenderAntialiased))
    seriesItem.drawSeries(painter, xMap, yMap, canvasRect, from_, to)


def qwtHasBackingStore(canvas):
    return canvas.testPaintAttribute(QwtPlotCanvas.BackingStore)\
           and canvas.backingStore()


class QwtPlotDirectPainter_PrivateData(object):
    def __init__(self):
        self.attributes = 0
        self.hasClipping = False
        self.seriesItem = None  # QwtPlotSeriesItem
        self.clipRegion = QRegion()
        self.painter = QPainter()
        self.from_ = None
        self.to = None


class QwtPlotDirectPainter(QObject):
    """
    Painter object trying to paint incrementally

    Often applications want to display samples while they are
    collected. When there are too many samples complete replots
    will be expensive to be processed in a collection cycle.

    `QwtPlotDirectPainter` offers an API to paint
    subsets (f.e all additions points) without erasing/repainting
    the plot canvas.

    On certain environments it might be important to calculate a proper
    clip region before painting. F.e. for Qt Embedded only the clipped part
    of the backing store will be copied to a (maybe unaccelerated) 
    frame buffer.

    .. warning::
    
        Incremental painting will only help when no replot is triggered
        by another operation (like changing scales) and nothing needs
        to be erased.
        
    Paint attributes:
    
      * `QwtPlotDirectPainter.AtomicPainter`:
      
        Initializing a `QPainter` is an expensive operation.
        When `AtomicPainter` is set each call of `drawSeries()` opens/closes
        a temporary `QPainter`. Otherwise `QwtPlotDirectPainter` tries to
        use the same `QPainter` as long as possible.

      * `QwtPlotDirectPainter.FullRepaint`:
      
        When `FullRepaint` is set the plot canvas is explicitly repainted
        after the samples have been rendered.

      * `QwtPlotDirectPainter.CopyBackingStore`:
      
        When `QwtPlotCanvas.BackingStore` is enabled the painter
        has to paint to the backing store and the widget. In certain 
        situations/environments it might be faster to paint to 
        the backing store only and then copy the backing store to the canvas.
        This flag can also be useful for settings, where Qt fills the
        the clip region with the widget background.
    """
    
    # enum Attribute
    AtomicPainter = 0x01
    FullRepaint = 0x02
    CopyBackingStore = 0x04
    
    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.__data = QwtPlotDirectPainter_PrivateData()
    
    def setAttribute(self, attribute, on=True):
        """
        Change an attribute
        
        :param int attribute: Attribute to change
        :param bool on: On/Off

        .. seealso::

            :py:meth:`testAttribute()`
        """
        if self.testAttribute(attribute) != on:
            self.__data.attributes |= attribute
        else:
            self.__data.attributes &= ~attribute
        if attribute == self.AtomicPainter and on:
            self.reset()
    
    def testAttribute(self, attribute):
        """
        :param int attribute: Attribute to be tested
        :return: True, when attribute is enabled

        .. seealso::

            :py:meth:`setAttribute()`
        """
        return self.__data.attributes & attribute
    
    def setClipping(self, enable):
        """
        En/Disables clipping
            
        :param bool enable: Enables clipping is true, disable it otherwise
        
        .. seealso::
        
            :py:meth:`hasClipping()`, :py:meth:`clipRegion()`, 
            :py:meth:`setClipRegion()`
        """
        self.__data.hasClipping = enable
    
    def hasClipping(self):
        """
        :return: Return true, when clipping is enabled
        
        .. seealso::
        
            :py:meth:`setClipping()`, :py:meth:`clipRegion()`, 
            :py:meth:`setClipRegion()`
        """
        return self.__data.hasClipping
    
    def setClipRegion(self, region):
        """
        Assign a clip region and enable clipping

        Depending on the environment setting a proper clip region might 
        improve the performance heavily. F.e. on Qt embedded only the clipped 
        part of the backing store will be copied to a (maybe unaccelerated) 
        frame buffer device.
        
        :param QRegion region: Clip region
        
        .. seealso::
        
            :py:meth:`hasClipping()`, :py:meth:`setClipping()`, 
            :py:meth:`clipRegion()`
        """
        self.__data.clipRegion = region
        self.__data.hasClipping = True
    
    def clipRegion(self):
        """
        :return: Return Currently set clip region.
        
        .. seealso::
        
            :py:meth:`hasClipping()`, :py:meth:`setClipping()`, 
            :py:meth:`setClipRegion()`
        """
        return self.__data.clipRegion
    
    def drawSeries(self, seriesItem, from_, to):
        """
        Draw a set of points of a seriesItem.
        
        When observing a measurement while it is running, new points have 
        to be added to an existing seriesItem. drawSeries() can be used to 
        display them avoiding a complete redraw of the canvas.

        Setting `plot().canvas().setAttribute(Qt.WA_PaintOutsidePaintEvent, True)`
        will result in faster painting, if the paint engine of the canvas widget
        supports this feature.
        
        :param qwt.plot_series.QwtPlotSeriesItem seriesItem: Item to be painted
        :param int from_: Index of the first point to be painted
        :param int to: Index of the last point to be painted. If to < 0 the series will be painted to its last point.
        """
        if seriesItem is None or seriesItem.plot() is None:
            return
        canvas = seriesItem.plot().canvas()
        canvasRect = canvas.contentsRect()
        plotCanvas = canvas  #XXX: cast to QwtPlotCanvas
        if plotCanvas and qwtHasBackingStore(plotCanvas):
            painter = QPainter(plotCanvas.backingStore())  #XXX: cast plotCanvas.backingStore() to QPixmap
            if self.__data.hasClipping:
                painter.setClipRegion(self.__data.clipRegion)
            qwtRenderItem(painter, canvasRect, seriesItem, from_, to)
            if self.testAttribute(self.FullRepaint):
                plotCanvas.repaint()
                return
        immediatePaint = True
        if not canvas.testAttribute(Qt.WA_WState_InPaintEvent):
            if QT_VERSION >= 0x050000 or\
               not canvas.testAttribute(Qt.WA_PaintOutsidePaintEvent):
                immediatePaint = False
        if immediatePaint:
            if not self.__data.painter.isActive():
                self.reset()
                self.__data.painter.begin(canvas)
                canvas.installEventFilter(self)
            if self.__data.hasClipping:
                self.__data.painter.setClipRegion(
                        QRegion(canvasRect) & self.__data.clipRegion)
            elif not self.__data.painter.hasClipping():
                self.__data.painter.setClipRect(canvasRect)
            qwtRenderItem(self.__data.painter,
                          canvasRect, seriesItem, from_, to)
            if self.__data.attributes & self.AtomicPainter:
                self.reset()
            elif self.__data.hasClipping:
                self.__data.painter.setClipping(False)
        else:
            self.reset()
            self.__data.seriesItem = seriesItem
            self.__data.from_ = from_
            self.__data.to = to
            clipRegion = QRegion(canvasRect)
            if self.__data.hasClipping:
                clipRegion &= self.__data.clipRegion
            canvas.installEventFilter(self)
            canvas.repaint(clipRegion)
            canvas.removeEventFilter(self)
            self.__data.seriesItem = None
    
    def reset(self):
        """Close the internal QPainter"""
        if self.__data.painter.isActive():
            w = self.__data.painter.device()  #XXX: cast to QWidget
            if w:
                w.removeEventFilter(self)
            self.__data.painter.end()
    
    def eventFilter(self, obj_, event):
        if event.type() == QEvent.Paint:
            self.reset()
            if self.__data.seriesItem:
                pe = event  #XXX: cast to QPaintEvent
                canvas = self.__data.seriesItem.plot().canvas()
                painter = QPainter(canvas)
                painter.setClipRegion(pe.region())
                doCopyCache = self.testAttribute(self.CopyBackingStore)
                if doCopyCache:
                    plotCanvas = canvas  #XXX: cast to QwtPlotCanvas
                    if plotCanvas:
                        doCopyCache = qwtHasBackingStore(plotCanvas)
                        if doCopyCache:
                            painter.drawPixmap(plotCanvas.contentsRect().topLeft(),
                                               plotCanvas.backingStore())
                if not doCopyCache:
                    qwtRenderItem(painter, canvas.contentsRect(),
                                  self.__data.seriesItem,
                                  self.__data.from_, self.__data.to)
                return True
        return False