This file is indexed.

/usr/lib/python2.7/dist-packages/qwt/graphic.py is in python-qwt 0.5.5-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# -*- 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)

"""
QwtGraphic
----------

.. autoclass:: QwtGraphic
   :members:
"""

from qwt.null_paintdevice import QwtNullPaintDevice
from qwt.painter_command import QwtPainterCommand

from qwt.qt.QtGui import (QPainter, QPainterPathStroker, QPaintEngine, QPixmap,
                          QTransform, QImage)
from qwt.qt.QtCore import Qt, QRectF, QSizeF, QSize, QPointF, QRect

import numpy as np


def qwtHasScalablePen(painter):
    pen = painter.pen()
    scalablePen = False
    if pen.style() != Qt.NoPen and pen.brush().style() != Qt.NoBrush:
        scalablePen = not pen.isCosmetic()
        if not scalablePen and pen.widthF() == 0.:
            hints = painter.renderHints()
            if hints & QPainter.NonCosmeticDefaultPen:
                scalablePen = True
    return scalablePen


def qwtStrokedPathRect(painter, path):
    stroker = QPainterPathStroker()
    stroker.setWidth(painter.pen().widthF())
    stroker.setCapStyle(painter.pen().capStyle())
    stroker.setJoinStyle(painter.pen().joinStyle())
    stroker.setMiterLimit(painter.pen().miterLimit())
    rect = QRectF()
    if qwtHasScalablePen(painter):
        stroke = stroker.createStroke(path)
        rect = painter.transform().map(stroke).boundingRect()
    else:
        mappedPath = painter.transform().map(path)
        mappedPath = stroker.createStroke(mappedPath)
        rect = mappedPath.boundingRect()
    return rect


def qwtExecCommand(painter, cmd, renderHints, transform, initialTransform):
    if cmd.type() == QwtPainterCommand.Path:
        doMap = False
        if bool(renderHints & QwtGraphic.RenderPensUnscaled)\
           and painter.transform().isScaling():
            isCosmetic = painter.pen().isCosmetic()
            if isCosmetic and painter.pen().widthF() == 0.:
                hints = painter.renderHints()
                if hints & QPainter.NonCosmeticDefaultPen:
                    isCosmetic = False
            doMap = not isCosmetic
        if doMap:
            tr = painter.transform()
            painter.resetTransform()
            path = tr.map(cmd.path())
            if initialTransform:
                painter.setTransform(initialTransform)
                invt, _ok = initialTransform.inverted()
                path = invt.map(path)
            painter.drawPath(path)
            painter.setTransform(tr)
        else:
            painter.drawPath(cmd.path())
    elif cmd.type() == QwtPainterCommand.Pixmap:
        data = cmd.pixmapData()
        painter.drawPixmap(data.rect, data.pixmap, data.subRect)
    elif cmd.type() == QwtPainterCommand.Image:
        data = cmd.imageData()
        painter.drawImage(data.rect, data.image, data.subRect, data.flags)
    elif cmd.type() == QwtPainterCommand.State:
        data = cmd.stateData()
        if data.flags & QPaintEngine.DirtyPen:
            painter.setPen(data.pen)
        if data.flags & QPaintEngine.DirtyBrush:
            painter.setBrush(data.brush)
        if data.flags & QPaintEngine.DirtyBrushOrigin:
            painter.setBrushOrigin(data.brushOrigin)
        if data.flags & QPaintEngine.DirtyFont:
            painter.setFont(data.font)
        if data.flags & QPaintEngine.DirtyBackground:
            painter.setBackgroundMode(data.backgroundMode)
            painter.setBackground(data.backgroundBrush)
        if data.flags & QPaintEngine.DirtyTransform:
            painter.setTransform(data.transform)
        if data.flags & QPaintEngine.DirtyClipEnabled:
            painter.setClipping(data.isClipEnabled)
        if data.flags & QPaintEngine.DirtyClipRegion:
            painter.setClipRegion(data.clipRegion, data.clipOperation)
        if data.flags & QPaintEngine.DirtyClipPath:
            painter.setClipPath(data.clipPath, data.clipOperation)
        if data.flags & QPaintEngine.DirtyHints:
            for hint in (QPainter.Antialiasing,
                         QPainter.TextAntialiasing,
                         QPainter.SmoothPixmapTransform,
                         QPainter.HighQualityAntialiasing,
                         QPainter.NonCosmeticDefaultPen):
                painter.setRenderHint(hint, bool(data.renderHints & hint))
        if data.flags & QPaintEngine.DirtyCompositionMode:
            painter.setCompositionMode(data.compositionMode)
        if data.flags & QPaintEngine.DirtyOpacity:
            painter.setOpacity(data.opacity)


class PathInfo(object):
    def __init__(self, *args):
        if len(args) == 0:
            self.__scalablePen = False
        elif len(args) == 3:
            pointRect, boundingRect, scalablePen = args
            self.__pointRect = pointRect
            self.__boundingRect = boundingRect
            self.__scalablePen = scalablePen
        else:
            raise TypeError("%s() takes 0 or 3 argument(s) (%s given)"\
                            % (self.__class__.__name__, len(args)))
    
    def scaledBoundingRect(self, sx, sy, scalePens):
        if sx == 1. and sy == 1.:
            return self.__boundingRect
        transform = QTransform()
        transform.scale(sx, sy)
        if scalePens and self.__scalablePen:
            rect = transform.mapRect(self.__boundingRect)
        else:
            rect = transform.mapRect(self.__pointRect)
            l = abs(self.__pointRect.left()-self.__boundingRect.left())
            r = abs(self.__pointRect.right()-self.__boundingRect.right())
            t = abs(self.__pointRect.top()-self.__boundingRect.top())
            b = abs(self.__pointRect.bottom()-self.__boundingRect.bottom())
            rect.adjust(-l, -t, r, b)
        return rect
    
    def scaleFactorX(self, pathRect, targetRect, scalePens):
        if pathRect.width() <= 0.0:
            return 0.
        p0 = self.__pointRect.center()
        l = abs(pathRect.left()-p0.x())
        r = abs(pathRect.right()-p0.x())
        w = 2.*min([l, r])*targetRect.width()/pathRect.width()
        if scalePens and self.__scalablePen:
            sx = w/self.__boundingRect.width()
        else:
            pw = max([abs(self.__boundingRect.left()-self.__pointRect.left()),
                      abs(self.__boundingRect.right()-self.__pointRect.right())])
            sx = (w-2*pw)/self.__pointRect.width()
        return sx
    
    def scaleFactorY(self, pathRect, targetRect, scalePens):
        if pathRect.height() <= 0.0:
            return 0.
        p0 = self.__pointRect.center()
        t = abs(pathRect.top()-p0.y())
        b = abs(pathRect.bottom()-p0.y())
        h = 2.*min([t, b])*targetRect.height()/pathRect.height()
        if scalePens and self.__scalablePen:
            sy = h/self.__boundingRect.height()
        else:
            pw = max([abs(self.__boundingRect.top()-self.__pointRect.top()),
                      abs(self.__boundingRect.bottom()-self.__pointRect.bottom())])
            sy = (h-2*pw)/self.__pointRect.height()
        return sy
    

class QwtGraphic_PrivateData(object):
    def __init__(self):
        self.boundingRect = QRectF(0.0, 0.0, -1.0, -1.0)
        self.pointRect = QRectF(0.0, 0.0, -1.0, -1.0)
        self.initialTransform = None
        self.defaultSize = QSizeF()
        self.commands = []
        self.pathInfos = []
        self.renderHints = 0


class QwtGraphic(QwtNullPaintDevice):
    """
    A paint device for scalable graphics
    
    `QwtGraphic` is the representation of a graphic that is tailored for
    scalability. Like `QPicture` it will be initialized by `QPainter`
    operations and can be replayed later to any target paint device.

    While the usual image representations `QImage` and `QPixmap` are not
    scalable `Qt` offers two paint devices, that might be candidates
    for representing a vector graphic:

        - `QPicture`:
        
          Unfortunately `QPicture` had been forgotten, when Qt4
          introduced floating point based render engines. Its API
          is still on integers, what make it unusable for proper scaling.

        - `QSvgRenderer`, `QSvgGenerator`:
        
          Unfortunately `QSvgRenderer` hides to much information about
          its nodes in internal APIs, that are necessary for proper 
          layout calculations. Also it is derived from `QObject` and 
          can't be copied like `QImage`/`QPixmap`.

    `QwtGraphic` maps all scalable drawing primitives to a `QPainterPath`
    and stores them together with the painter state changes 
    ( pen, brush, transformation ... ) in a list of `QwtPaintCommands`. 
    For being a complete `QPaintDevice` it also stores pixmaps or images, 
    what is somehow against the idea of the class, because these objects 
    can't be scaled without a loss in quality.

    The main issue about scaling a `QwtGraphic` object are the pens used for
    drawing the outlines of the painter paths. While non cosmetic pens 
    ( `QPen.isCosmetic()` ) are scaled with the same ratio as the path, 
    cosmetic pens have a fixed width. A graphic might have paths with 
    different pens - cosmetic and non-cosmetic.

    `QwtGraphic` caches 2 different rectangles:

        - control point rectangle:
        
          The control point rectangle is the bounding rectangle of all
          control point rectangles of the painter paths, or the target 
          rectangle of the pixmaps/images.

        - bounding rectangle:
        
          The bounding rectangle extends the control point rectangle by
          what is needed for rendering the outline with an unscaled pen.

    Because the offset for drawing the outline depends on the shape 
    of the painter path ( the peak of a triangle is different than the flat side ) 
    scaling with a fixed aspect ratio always needs to be calculated from the 
    control point rectangle.
        
    .. py:class:: QwtGraphic()
    
        Initializes a null graphic
        
    .. py:class:: QwtGraphic(other)
    
        Copy constructor
        
        :param qwt.graphic.QwtGraphic other: Source
    """
    
    # enum RenderHint
    RenderPensUnscaled = 0x1
    
    def __init__(self, *args):
        QwtNullPaintDevice.__init__(self)
        if len(args) == 0:
            self.setMode(QwtNullPaintDevice.PathMode)
            self.__data = QwtGraphic_PrivateData()
        elif len(args) == 1:
            other, = args
            self.setMode(other.mode())
            self.__data = other.__data
        else:
            raise TypeError("%s() takes 0 or 1 argument(s) (%s given)"\
                            % (self.__class__.__name__, len(args)))
    
    def reset(self):
        """Clear all stored commands"""
        self.__data.commands = []
        self.__data.pathInfos = []
        self.__data.boundingRect = QRectF(0.0, 0.0, -1.0, -1.0)
        self.__data.pointRect = QRectF(0.0, 0.0, -1.0, -1.0)
        self.__data.defaultSize = QSizeF()
    
    def isNull(self):
        """Return True, when no painter commands have been stored"""
        return len(self.__data.commands) == 0
    
    def isEmpty(self):
        """Return True, when the bounding rectangle is empty"""
        return self.__data.boundingRect.isEmpty()
    
    def setRenderHint(self, hint, on=True):
        """Toggle an render hint"""
        if on:
            self.__data.renderHints |= hint
        else:
            self.__data.renderHints &= ~hint
    
    def testRenderHint(self, hint):
        """Test a render hint"""
        return bool(self.__data.renderHints & hint)
    
    def boundingRect(self):
        """
        The bounding rectangle is the :py:meth:`controlPointRect`
        extended by the areas needed for rendering the outlines
        with unscaled pens.

        :return: Bounding rectangle of the graphic
        
        .. seealso::
            
            :py:meth:`controlPointRect`, :py:meth:`scaledBoundingRect`
        """
        if self.__data.boundingRect.width() < 0:
            return QRectF()
        return self.__data.boundingRect
    
    def controlPointRect(self):
        """
        The control point rectangle is the bounding rectangle 
        of all control points of the paths and the target
        rectangles of the images/pixmaps.

        :return: Control point rectangle
        
        .. seealso::
        
            :py:meth:`boundingRect()`, :py:meth:`scaledBoundingRect()`
        """
        if self.__data.pointRect.width() < 0:
            return QRectF()
        return self.__data.pointRect
    
    def scaledBoundingRect(self, sx, sy):
        """
        Calculate the target rectangle for scaling the graphic
        
        :param float sx: Horizontal scaling factor 
        :param float sy: Vertical scaling factor 
        :return: Scaled bounding rectangle
            
        .. note::
        
            In case of paths that are painted with a cosmetic pen 
            (see :py:meth:`QPen.isCosmetic()`) the target rectangle is 
            different to multiplying the bounding rectangle.

        .. seealso::
        
            :py:meth:`boundingRect()`, :py:meth:`controlPointRect()`
        """
        if sx == 1. and sy == 1.:
            return self.__data.boundingRect
        transform = QTransform()
        transform.scale(sx, sy)
        rect = transform.mapRect(self.__data.pointRect)
        for pathInfo in self.__data.pathInfos:
            rect |= pathInfo.scaledBoundingRect(sx, sy,
                not bool(self.__data.renderHints & self.RenderPensUnscaled))
        return rect
    
    def sizeMetrics(self):
        """Return Ceiled :py:meth:`defaultSize()`"""
        sz = self.defaultSize()
        return QSize(np.ceil(sz.width()), np.ceil(sz.height()))
        
    def setDefaultSize(self, size):
        """
        The default size is used in all methods rendering the graphic,
        where no size is explicitly specified. Assigning an empty size
        means, that the default size will be calculated from the bounding 
        rectangle.
        
        :param QSizeF size: Default size

        .. seealso::
        
            :py:meth:`defaultSize()`, :py:meth:`boundingRect()`
        """
        w = max([0., size.width()])
        h = max([0., size.height()])
        self.__data.defaultSize = QSizeF(w, h)
        
    def defaultSize(self):
        """
        When a non empty size has been assigned by setDefaultSize() this
        size will be returned. Otherwise the default size is the size
        of the bounding rectangle.

        The default size is used in all methods rendering the graphic,
        where no size is explicitly specified. 
        
        :return: Default size

        .. seealso::
        
            :py:meth:`setDefaultSize()`, :py:meth:`boundingRect()`
        """
        if not self.__data.defaultSize.isEmpty():
            return self.__data.defaultSize
        return self.boundingRect().size()
    
    def render(self, *args):
        """
        .. py:method:: render(painter)
        
            Replay all recorded painter commands
            
            :param QPainter painter: Qt painter
        
        .. py:method:: render(painter, size, aspectRatioMode)
        
            Replay all recorded painter commands
            
            The graphic is scaled to fit into the rectangle
            of the given size starting at ( 0, 0 ).
            
            :param QPainter painter: Qt painter
            :param QSizeF size: Size for the scaled graphic
            :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale
        
        .. py:method:: render(painter, rect, aspectRatioMode)
        
            Replay all recorded painter commands
            
            The graphic is scaled to fit into the given rectangle
            
            :param QPainter painter: Qt painter
            :param QRectF rect: Rectangle for the scaled graphic
            :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale        
        
        .. py:method:: render(painter, pos, aspectRatioMode)
        
            Replay all recorded painter commands
            
            The graphic is scaled to the :py:meth:`defaultSize()` and aligned
            to a position.
            
            :param QPainter painter: Qt painter
            :param QPointF pos: Reference point, where to render
            :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale        
        """
        if len(args) == 1:
            painter, = args
            if self.isNull():
                return
            transform = painter.transform()
            painter.save()
            for command in self.__data.commands:
                qwtExecCommand(painter, command, self.__data.renderHints,
                               transform, self.__data.initialTransform)
            painter.restore()
        elif len(args) in (2, 3) and isinstance(args[1], QSizeF):
            painter, size = args[:2]
            aspectRatioMode = Qt.IgnoreAspectRatio
            if len(args) == 3:
                aspectRatioMode = args[-1]
            r = QRectF(0., 0., size.width(), size.height())
            self.render(painter, r, aspectRatioMode)
        elif len(args) in (2, 3) and isinstance(args[1], QRectF):
            painter, rect = args[:2]
            aspectRatioMode = Qt.IgnoreAspectRatio
            if len(args) == 3:
                aspectRatioMode = args[-1]
            if self.isEmpty() or rect.isEmpty():
                return
            sx = 1.
            sy = 1.
            if self.__data.pointRect.width() > 0.:
                sx = rect.width()/self.__data.pointRect.width()
            if self.__data.pointRect.height() > 0.:
                sy = rect.height()/self.__data.pointRect.height()
            scalePens = not bool(self.__data.renderHints & self.RenderPensUnscaled)
            for info in self.__data.pathInfos:
                ssx = info.scaleFactorX(self.__data.pointRect, rect, scalePens)
                if ssx > 0.:
                    sx = min([sx, ssx])
                ssy = info.scaleFactorY(self.__data.pointRect, rect, scalePens)
                if ssy > 0.:
                    sy = min([sy, ssy])
            if aspectRatioMode == Qt.KeepAspectRatio:
                s = min([sx, sy])
                sx = s
                sy = s
            elif aspectRatioMode == Qt.KeepAspectRatioByExpanding:
                s = max([sx, sy])
                sx = s
                sy = s
            tr = QTransform()
            tr.translate(rect.center().x()-.5*sx*self.__data.pointRect.width(),
                         rect.center().y()-.5*sy*self.__data.pointRect.height())
            tr.scale(sx, sy)
            tr.translate(-self.__data.pointRect.x(),
                         -self.__data.pointRect.y())
            transform = painter.transform()
            if not scalePens and transform.isScaling():
                #  we don't want to scale pens according to sx/sy,
                #  but we want to apply the scaling from the 
                #  painter transformation later
                self.__data.initialTransform = QTransform()
                self.__data.initialTransform.scale(transform.m11(),
                                                   transform.m22())
            painter.setTransform(tr, True)
            self.render(painter)
            painter.setTransform(transform)
            self.__data.initialTransform = None
        elif len(args) in (2, 3) and isinstance(args[1], QPointF):
            painter, pos = args[:2]
            alignment = Qt.AlignTop|Qt.AlignLeft
            if len(args) == 3:
                alignment = args[-1]
            r = QRectF(pos, self.defaultSize())
            if alignment & Qt.AlignLeft:
                r.moveLeft(pos.x())
            elif alignment & Qt.AlignHCenter:
                r.moveCenter(QPointF(pos.x(), r.center().y()))
            elif alignment & Qt.AlignRight:
                r.moveRight(pos.x())
            if alignment & Qt.AlignTop:
                r.moveTop(pos.y())
            elif alignment & Qt.AlignVCenter:
                r.moveCenter(QPointF(r.center().x(), pos.y()))
            elif alignment & Qt.AlignBottom:
                r.moveBottom(pos.y())
            self.render(painter, r)
        else:
            raise TypeError("%s().render() takes 1, 2 or 3 argument(s) (%s "\
                            "given)" % (self.__class__.__name__, len(args)))
    
    def toPixmap(self, *args):
        """
        Convert the graphic to a `QPixmap`

        All pixels of the pixmap get initialized by `Qt.transparent`
        before the graphic is scaled and rendered on it.

        The size of the pixmap is the default size ( ceiled to integers )
        of the graphic.
        
        :return: The graphic as pixmap in default size

        .. seealso::
        
            :py:meth:`defaultSize()`, :py:meth:`toImage()`, :py:meth:`render()`
        """
        if len(args) == 0:
            if self.isNull():
                return QPixmap()
            sz = self.defaultSize()
            w = np.ceil(sz.width())
            h = np.ceil(sz.height())
            pixmap = QPixmap(w, h)
            pixmap.fill(Qt.transparent)
            r = QRectF(0., 0., sz.width(), sz.height())
            painter = QPainter(pixmap)
            self.render(painter, r, Qt.KeepAspectRatio)
            painter.end()
            return pixmap
        elif len(args) in (1, 2):
            size = args[0]
            aspectRatioMode = Qt.IgnoreAspectRatio
            if len(args) == 2:
                aspectRatioMode = args[-1]
            pixmap = QPixmap(size)
            pixmap.fill(Qt.transparent)
            r = QRect(0, 0, size.width(), size.height())
            painter = QPainter(pixmap)
            self.render(painter, r, aspectRatioMode)
            painter.end()
            return pixmap
        
    def toImage(self, *args):
        """
        .. py:method:: toImage()
        
            Convert the graphic to a `QImage`

            All pixels of the image get initialized by 0 ( transparent )
            before the graphic is scaled and rendered on it.

            The format of the image is `QImage.Format_ARGB32_Premultiplied`.
            
            The size of the image is the default size ( ceiled to integers )
            of the graphic.

            :return: The graphic as image in default size

        .. py:method:: toImage(size, [aspectRatioMode=Qt.IgnoreAspectRatio])
        
            Convert the graphic to a `QImage`

            All pixels of the image get initialized by 0 ( transparent )
            before the graphic is scaled and rendered on it.

            The format of the image is `QImage.Format_ARGB32_Premultiplied`.
            
            :param QSize size: Size of the image
            :param `Qt.AspectRatioMode` aspectRatioMode: Aspect ratio how to scale the graphic
            :return: The graphic as image

        .. seealso::
        
            :py:meth:`toPixmap()`, :py:meth:`render()`
        """
        if len(args) == 0:
            if self.isNull():
                return QImage()
            sz = self.defaultSize()
            w = np.ceil(sz.width())
            h = np.ceil(sz.height())
            image = QImage(w, h, QImage.Format_ARGB32)
            image.fill(0)
            r = QRect(0, 0, sz.width(), sz.height())
            painter = QPainter(image)
            self.render(painter, r, Qt.KeepAspectRatio)
            painter.end()
            return image
        elif len(args) in (1, 2):
            size = args[0]
            aspectRatioMode = Qt.IgnoreAspectRatio
            if len(args) == 2:
                aspectRatioMode = args[-1]
            image = QImage(size, QImage.Format_ARGB32_Premultiplied)
            image.fill(0)
            r = QRect(0, 0, size.width(), size.height())
            painter = QPainter(image)
            self.render(painter, r, aspectRatioMode)
            return image
        
    def drawPath(self, path):
        """
        Store a path command in the command list
        
        :param QPainterPath path: Painter path

        .. seealso::
        
            :py:meth:`QPaintEngine.drawPath()`
        """
        painter = self.paintEngine().painter()
        if painter is None:
            return
        self.__data.commands += [QwtPainterCommand(path)]
        if not path.isEmpty():
            scaledPath = painter.transform().map(path)
            pointRect = scaledPath.boundingRect()
            boundingRect = QRectF(pointRect)
            if painter.pen().style() != Qt.NoPen\
               and painter.pen().brush().style() != Qt.NoBrush:
                boundingRect = qwtStrokedPathRect(painter, path)
            self.updateControlPointRect(pointRect)
            self.updateBoundingRect(boundingRect)
            self.__data.pathInfos += [PathInfo(pointRect, boundingRect,
                                               qwtHasScalablePen(painter))]
    
    def drawPixmap(self, rect, pixmap, subRect):
        """
        Store a pixmap command in the command list
        
        :param QRectF rect: target rectangle
        :param QPixmap pixmap: Pixmap to be painted
        :param QRectF subRect: Reactangle of the pixmap to be painted

        .. seealso::
        
            :py:meth:`QPaintEngine.drawPixmap()`
        """
        painter = self.paintEngine().painter()
        if painter is None:
            return
        self.__data.commands += [QwtPainterCommand(rect, pixmap, subRect)]
        r = painter.transform().mapRect(rect)
        self.updateControlPointRect(r)
        self.updateBoundingRect(r)
    
    def drawImage(self, rect, image, subRect, flags):
        """
        Store a image command in the command list
        
        :param QRectF rect: target rectangle
        :param QImage image: Pixmap to be painted
        :param QRectF subRect: Reactangle of the pixmap to be painted
        :param Qt.ImageConversionFlags flags: Pixmap to be painted

        .. seealso::
        
            :py:meth:`QPaintEngine.drawImage()`
        """
        painter = self.paintEngine().painter()
        if painter is None:
            return
        self.__data.commands += [QwtPainterCommand(rect, image, subRect, flags)]
        r = painter.transform().mapRect(rect)
        self.updateControlPointRect(r)
        self.updateBoundingRect(r)
        
    def updateState(self, state):
        """
        Store a state command in the command list
        
        :param QPaintEngineState state: State to be stored

        .. seealso::
        
            :py:meth:`QPaintEngine.updateState()`
        """
        #XXX: shall we call the parent's implementation of updateState?
        self.__data.commands += [QwtPainterCommand(state)]
        
    def updateBoundingRect(self, rect):
        br = QRectF(rect)
        painter = self.paintEngine().painter()
        if painter and painter.hasClipping():
            #XXX: there's something fishy about the following lines...
            cr = painter.clipRegion().boundingRect()
            cr = painter.transform().mapRect(br)
            br &= cr
        if self.__data.boundingRect.width() < 0:
            self.__data.boundingRect = br
        else:
            self.__data.boundingRect |= br
            
    def updateControlPointRect(self, rect):
        if self.__data.pointRect.width() < 0.:
            self.__data.pointRect = rect
        else:
            self.__data.pointRect |= rect
    
    def commands(self):
        return self.__data.commands
    
    def setCommands(self, commands):
        self.reset()
        painter = QPainter(self)
        for cmd in commands:
            qwtExecCommand(painter, cmd, 0, QTransform(), None)
        painter.end()