cefb8edf74dd0e88408c0032a8a273bbedbc91ea
[profile/ivi/qtbase.git] / src / gui / image / qpixmap.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <qglobal.h>
43
44 #include "qpixmap.h"
45 #include "qplatformpixmap_qpa.h"
46 #include "qimagepixmapcleanuphooks_p.h"
47
48 #include "qbitmap.h"
49 #include "qimage.h"
50 #include "qpainter.h"
51 #include "qdatastream.h"
52 #include "qbuffer.h"
53 #include <private/qguiapplication_p.h>
54 #include "qevent.h"
55 #include "qfile.h"
56 #include "qfileinfo.h"
57 #include "qpixmapcache.h"
58 #include "qdatetime.h"
59 #include "qimagereader.h"
60 #include "qimagewriter.h"
61 #include "qpaintengine.h"
62 #include "qscreen.h"
63 #include "qthread.h"
64 #include "qdebug.h"
65
66 # include "qplatformintegration_qpa.h"
67
68 #include "qpixmap_raster_p.h"
69 #include "private/qhexstring_p.h"
70
71 QT_BEGIN_NAMESPACE
72
73 static bool qt_pixmap_thread_test()
74 {
75     if (!QCoreApplication::instance()) {
76         qFatal("QPixmap: Must construct a QApplication before a QPaintDevice");
77         return false;
78     }
79
80     if (qApp->thread() != QThread::currentThread()) {
81         bool fail = false;
82         if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) {
83             printf("Lighthouse plugin does not support threaded pixmaps!\n");
84             fail = true;
85         }
86         if (fail) {
87             qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
88             return false;
89         }
90     }
91     return true;
92 }
93
94 void QPixmap::doInit(int w, int h, int type)
95 {
96     if ((w > 0 && h > 0) || type == QPlatformPixmap::BitmapType)
97         data = QPlatformPixmap::create(w, h, (QPlatformPixmap::PixelType) type);
98     else
99         data = 0;
100 }
101
102 /*!
103     Constructs a null pixmap.
104
105     \sa isNull()
106 */
107
108 QPixmap::QPixmap()
109     : QPaintDevice()
110 {
111     (void) qt_pixmap_thread_test();
112     doInit(0, 0, QPlatformPixmap::PixmapType);
113 }
114
115 /*!
116     \fn QPixmap::QPixmap(int width, int height)
117
118     Constructs a pixmap with the given \a width and \a height. If
119     either \a width or \a height is zero, a null pixmap is
120     constructed.
121
122     \warning This will create a QPixmap with uninitialized data. Call
123     fill() to fill the pixmap with an appropriate color before drawing
124     onto it with QPainter.
125
126     \sa isNull()
127 */
128
129 QPixmap::QPixmap(int w, int h)
130     : QPaintDevice()
131 {
132     if (!qt_pixmap_thread_test())
133         doInit(0, 0, QPlatformPixmap::PixmapType);
134     else
135         doInit(w, h, QPlatformPixmap::PixmapType);
136 }
137
138 /*!
139     \overload
140
141     Constructs a pixmap of the given \a size.
142
143     \warning This will create a QPixmap with uninitialized data. Call
144     fill() to fill the pixmap with an appropriate color before drawing
145     onto it with QPainter.
146 */
147
148 QPixmap::QPixmap(const QSize &size)
149     : QPaintDevice()
150 {
151     if (!qt_pixmap_thread_test())
152         doInit(0, 0, QPlatformPixmap::PixmapType);
153     else
154         doInit(size.width(), size.height(), QPlatformPixmap::PixmapType);
155 }
156
157 /*!
158   \internal
159 */
160 QPixmap::QPixmap(const QSize &s, int type)
161 {
162     if (!qt_pixmap_thread_test())
163         doInit(0, 0, static_cast<QPlatformPixmap::PixelType>(type));
164     else
165         doInit(s.width(), s.height(), static_cast<QPlatformPixmap::PixelType>(type));
166 }
167
168 /*!
169     \internal
170 */
171 QPixmap::QPixmap(QPlatformPixmap *d)
172     : QPaintDevice(), data(d)
173 {
174 }
175
176 /*!
177     Constructs a pixmap from the file with the given \a fileName. If the
178     file does not exist or is of an unknown format, the pixmap becomes a
179     null pixmap.
180
181     The loader attempts to read the pixmap using the specified \a
182     format. If the \a format is not specified (which is the default),
183     the loader probes the file for a header to guess the file format.
184
185     The file name can either refer to an actual file on disk or to
186     one of the application's embedded resources. See the
187     \l{resources.html}{Resource System} overview for details on how
188     to embed images and other resource files in the application's
189     executable.
190
191     If the image needs to be modified to fit in a lower-resolution
192     result (e.g. converting from 32-bit to 8-bit), use the \a
193     flags to control the conversion.
194
195     The \a fileName, \a format and \a flags parameters are
196     passed on to load(). This means that the data in \a fileName is
197     not compiled into the binary. If \a fileName contains a relative
198     path (e.g. the filename only) the relevant file must be found
199     relative to the runtime working directory.
200
201     \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
202     Image Files}
203 */
204
205 QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
206     : QPaintDevice()
207 {
208     doInit(0, 0, QPlatformPixmap::PixmapType);
209     if (!qt_pixmap_thread_test())
210         return;
211
212     load(fileName, format, flags);
213 }
214
215 /*!
216     Constructs a pixmap that is a copy of the given \a pixmap.
217
218     \sa copy()
219 */
220
221 QPixmap::QPixmap(const QPixmap &pixmap)
222     : QPaintDevice()
223 {
224     if (!qt_pixmap_thread_test()) {
225         doInit(0, 0, QPlatformPixmap::PixmapType);
226         return;
227     }
228     if (pixmap.paintingActive()) {                // make a deep copy
229         operator=(pixmap.copy());
230     } else {
231         data = pixmap.data;
232     }
233 }
234
235 /*!
236     Constructs a pixmap from the given \a xpm data, which must be a
237     valid XPM image.
238
239     Errors are silently ignored.
240
241     Note that it's possible to squeeze the XPM variable a little bit
242     by using an unusual declaration:
243
244     \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0
245
246     The extra \c const makes the entire definition read-only, which is
247     slightly more efficient (for example, when the code is in a shared
248     library) and ROMable when the application is to be stored in ROM.
249 */
250 #ifndef QT_NO_IMAGEFORMAT_XPM
251 QPixmap::QPixmap(const char * const xpm[])
252     : QPaintDevice()
253 {
254     doInit(0, 0, QPlatformPixmap::PixmapType);
255     if (!xpm)
256         return;
257
258     QImage image(xpm);
259     if (!image.isNull()) {
260         if (data && data->pixelType() == QPlatformPixmap::BitmapType)
261             *this = QBitmap::fromImage(image);
262         else
263             *this = fromImage(image);
264     }
265 }
266 #endif
267
268
269 /*!
270     Destroys the pixmap.
271 */
272
273 QPixmap::~QPixmap()
274 {
275     Q_ASSERT(!data || data->ref.load() >= 1); // Catch if ref-counting changes again
276 }
277
278 /*!
279   \internal
280 */
281 int QPixmap::devType() const
282 {
283     return QInternal::Pixmap;
284 }
285
286 /*!
287     \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
288     \overload
289
290     Returns a deep copy of the subset of the pixmap that is specified
291     by the rectangle QRect( \a x, \a y, \a width, \a height).
292 */
293
294 /*!
295     \fn QPixmap QPixmap::copy(const QRect &rectangle) const
296
297     Returns a deep copy of the subset of the pixmap that is specified
298     by the given \a rectangle. For more information on deep copies,
299     see the \l {Implicit Data Sharing} documentation.
300
301     If the given \a rectangle is empty, the whole image is copied.
302
303     \sa operator=(), QPixmap(), {QPixmap#Pixmap
304     Transformations}{Pixmap Transformations}
305 */
306 QPixmap QPixmap::copy(const QRect &rect) const
307 {
308     if (isNull())
309         return QPixmap();
310
311     QRect r(0, 0, width(), height());
312     if (!rect.isEmpty())
313         r = r.intersected(rect);
314
315     QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
316     d->copy(data.data(), r);
317     return QPixmap(d);
318 }
319
320 /*!
321     \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
322     \since 4.6
323
324     This convenience function is equivalent to calling QPixmap::scroll(\a dx,
325     \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
326
327     \sa QWidget::scroll(), QGraphicsItem::scroll()
328 */
329
330 /*!
331     \since 4.6
332
333     Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
334     region is left unchanged. You can optionally pass a pointer to an empty
335     QRegion to get the region that is \a exposed by the scroll operation.
336
337     \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2
338
339     You cannot scroll while there is an active painter on the pixmap.
340
341     \sa QWidget::scroll(), QGraphicsItem::scroll()
342 */
343 void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
344 {
345     if (isNull() || (dx == 0 && dy == 0))
346         return;
347     QRect dest = rect & this->rect();
348     QRect src = dest.translated(-dx, -dy) & dest;
349     if (src.isEmpty()) {
350         if (exposed)
351             *exposed += dest;
352         return;
353     }
354
355     detach();
356
357     if (!data->scroll(dx, dy, src)) {
358         // Fallback
359         QPixmap pix = *this;
360         QPainter painter(&pix);
361         painter.setCompositionMode(QPainter::CompositionMode_Source);
362         painter.drawPixmap(src.translated(dx, dy), *this, src);
363         painter.end();
364         *this = pix;
365     }
366
367     if (exposed) {
368         *exposed += dest;
369         *exposed -= src.translated(dx, dy);
370     }
371 }
372
373 /*!
374     Assigns the given \a pixmap to this pixmap and returns a reference
375     to this pixmap.
376
377     \sa copy(), QPixmap()
378 */
379
380 QPixmap &QPixmap::operator=(const QPixmap &pixmap)
381 {
382     if (paintingActive()) {
383         qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
384         return *this;
385     }
386     if (pixmap.paintingActive()) {                // make a deep copy
387         *this = pixmap.copy();
388     } else {
389         data = pixmap.data;
390     }
391     return *this;
392 }
393
394 /*!
395     \fn void QPixmap::swap(QPixmap &other)
396     \since 4.8
397
398     Swaps pixmap \a other with this pixmap. This operation is very
399     fast and never fails.
400 */
401
402 /*!
403    Returns the pixmap as a QVariant.
404 */
405 QPixmap::operator QVariant() const
406 {
407     return QVariant(QVariant::Pixmap, this);
408 }
409
410 /*!
411     \fn bool QPixmap::operator!() const
412
413     Returns true if this is a null pixmap; otherwise returns false.
414
415     \sa isNull()
416 */
417
418 /*!
419     Converts the pixmap to a QImage. Returns a null image if the
420     conversion fails.
421
422     If the pixmap has 1-bit depth, the returned image will also be 1
423     bit deep. Images with more bits will be returned in a format
424     closely represents the underlying system. Usually this will be
425     QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
426     QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
427     alpha.
428
429     Note that for the moment, alpha masks on monochrome images are
430     ignored.
431
432     \sa fromImage(), {QImage#Image Formats}{Image Formats}
433 */
434 QImage QPixmap::toImage() const
435 {
436     if (isNull())
437         return QImage();
438
439     return data->toImage();
440 }
441
442 /*!
443     \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
444
445     Returns the actual matrix used for transforming a pixmap with the
446     given \a width, \a height and \a matrix.
447
448     When transforming a pixmap using the transformed() function, the
449     transformation matrix is internally adjusted to compensate for
450     unwanted translation, i.e. transformed() returns the smallest
451     pixmap containing all transformed points of the original
452     pixmap. This function returns the modified matrix, which maps
453     points correctly from the original pixmap into the new pixmap.
454
455     \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
456     Transformations}
457 */
458 QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
459 {
460     return QImage::trueMatrix(m, w, h);
461 }
462
463 /*!
464   \overload
465
466   This convenience function loads the matrix \a m into a
467   QTransform and calls the overloaded function with the
468   QTransform and the width \a w and the height \a h.
469  */
470 QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
471 {
472     return trueMatrix(QTransform(m), w, h).toAffine();
473 }
474
475
476 /*!
477     \fn bool QPixmap::isQBitmap() const
478
479     Returns true if this is a QBitmap; otherwise returns false.
480 */
481
482 bool QPixmap::isQBitmap() const
483 {
484     return data->type == QPlatformPixmap::BitmapType;
485 }
486
487 /*!
488     \fn bool QPixmap::isNull() const
489
490     Returns true if this is a null pixmap; otherwise returns false.
491
492     A null pixmap has zero width, zero height and no contents. You
493     cannot draw in a null pixmap.
494 */
495 bool QPixmap::isNull() const
496 {
497     return !data || data->isNull();
498 }
499
500 /*!
501     \fn int QPixmap::width() const
502
503     Returns the width of the pixmap.
504
505     \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
506 */
507 int QPixmap::width() const
508 {
509     return data ? data->width() : 0;
510 }
511
512 /*!
513     \fn int QPixmap::height() const
514
515     Returns the height of the pixmap.
516
517     \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
518 */
519 int QPixmap::height() const
520 {
521     return data ? data->height() : 0;
522 }
523
524 /*!
525     \fn QSize QPixmap::size() const
526
527     Returns the size of the pixmap.
528
529     \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
530     Information}
531 */
532 QSize QPixmap::size() const
533 {
534     return data ? QSize(data->width(), data->height()) : QSize(0, 0);
535 }
536
537 /*!
538     \fn QRect QPixmap::rect() const
539
540     Returns the pixmap's enclosing rectangle.
541
542     \sa {QPixmap#Pixmap Information}{Pixmap Information}
543 */
544 QRect QPixmap::rect() const
545 {
546     return data ? QRect(0, 0, data->width(), data->height()) : QRect();
547 }
548
549 /*!
550     \fn int QPixmap::depth() const
551
552     Returns the depth of the pixmap.
553
554     The pixmap depth is also called bits per pixel (bpp) or bit planes
555     of a pixmap. A null pixmap has depth 0.
556
557     \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
558     Information}
559 */
560 int QPixmap::depth() const
561 {
562     return data ? data->depth() : 0;
563 }
564
565 /*!
566     Sets a mask bitmap.
567
568     This function merges the \a mask with the pixmap's alpha channel. A pixel
569     value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
570     means the pixel is transparent. The mask must have the same size as this
571     pixmap.
572
573     Setting a null mask resets the mask, leaving the previously transparent
574     pixels black. The effect of this function is undefined when the pixmap is
575     being painted on.
576
577     \warning This is potentially an expensive operation.
578
579     \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
580     QBitmap
581 */
582 void QPixmap::setMask(const QBitmap &mask)
583 {
584     if (paintingActive()) {
585         qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
586         return;
587     }
588
589     if (!mask.isNull() && mask.size() != size()) {
590         qWarning("QPixmap::setMask() mask size differs from pixmap size");
591         return;
592     }
593
594     if (isNull())
595         return;
596
597     if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
598        return;
599
600     detach();
601
602     QImage image = data->toImage();
603     if (mask.size().isEmpty()) {
604         if (image.depth() != 1) { // hw: ????
605             image = image.convertToFormat(QImage::Format_RGB32);
606         }
607     } else {
608         const int w = image.width();
609         const int h = image.height();
610
611         switch (image.depth()) {
612         case 1: {
613             const QImage imageMask = mask.toImage().convertToFormat(image.format());
614             for (int y = 0; y < h; ++y) {
615                 const uchar *mscan = imageMask.scanLine(y);
616                 uchar *tscan = image.scanLine(y);
617                 int bytesPerLine = image.bytesPerLine();
618                 for (int i = 0; i < bytesPerLine; ++i)
619                     tscan[i] &= mscan[i];
620             }
621             break;
622         }
623         default: {
624             const QImage imageMask = mask.toImage().convertToFormat(QImage::Format_MonoLSB);
625             image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
626             for (int y = 0; y < h; ++y) {
627                 const uchar *mscan = imageMask.scanLine(y);
628                 QRgb *tscan = (QRgb *)image.scanLine(y);
629                 for (int x = 0; x < w; ++x) {
630                     if (!(mscan[x>>3] & (1 << (x&7))))
631                         tscan[x] = 0;
632                 }
633             }
634             break;
635         }
636         }
637     }
638     data->fromImage(image, Qt::AutoColor);
639 }
640
641 #ifndef QT_NO_IMAGE_HEURISTIC_MASK
642 /*!
643     Creates and returns a heuristic mask for this pixmap.
644
645     The function works by selecting a color from one of the corners
646     and then chipping away pixels of that color, starting at all the
647     edges.  If \a clipTight is true (the default) the mask is just
648     large enough to cover the pixels; otherwise, the mask is larger
649     than the data pixels.
650
651     The mask may not be perfect but it should be reasonable, so you
652     can do things such as the following:
653
654     \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1
655
656     This function is slow because it involves converting to/from a
657     QImage, and non-trivial computations.
658
659     \sa QImage::createHeuristicMask(), createMaskFromColor()
660 */
661 QBitmap QPixmap::createHeuristicMask(bool clipTight) const
662 {
663     QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
664     return m;
665 }
666 #endif
667
668 /*!
669     Creates and returns a mask for this pixmap based on the given \a
670     maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
671     maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels
672     matching the maskColor will be opaque.
673
674     This function is slow because it involves converting to/from a
675     QImage.
676
677     \sa createHeuristicMask(), QImage::createMaskFromColor()
678 */
679 QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
680 {
681     QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
682     return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode));
683 }
684
685 /*!
686     Loads a pixmap from the file with the given \a fileName. Returns
687     true if the pixmap was successfully loaded; otherwise returns
688     false.
689
690     The loader attempts to read the pixmap using the specified \a
691     format. If the \a format is not specified (which is the default),
692     the loader probes the file for a header to guess the file format.
693
694     The file name can either refer to an actual file on disk or to one
695     of the application's embedded resources. See the
696     \l{resources.html}{Resource System} overview for details on how to
697     embed pixmaps and other resource files in the application's
698     executable.
699
700     If the data needs to be modified to fit in a lower-resolution
701     result (e.g. converting from 32-bit to 8-bit), use the \a flags to
702     control the conversion.
703
704     Note that QPixmaps are automatically added to the QPixmapCache
705     when loaded from a file; the key used is internal and can not
706     be acquired.
707
708     \sa loadFromData(), {QPixmap#Reading and Writing Image
709     Files}{Reading and Writing Image Files}
710 */
711
712 bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
713 {
714     if (fileName.isEmpty())
715         return false;
716
717     QFileInfo info(fileName);
718     QString key = QLatin1String("qt_pixmap")
719                   % info.absoluteFilePath()
720                   % HexString<uint>(info.lastModified().toTime_t())
721                   % HexString<quint64>(info.size())
722                   % HexString<uint>(data ? data->pixelType() : QPlatformPixmap::PixmapType);
723
724     // Note: If no extension is provided, we try to match the
725     // file against known plugin extensions
726     if (!info.completeSuffix().isEmpty() && !info.exists())
727         return false;
728
729     if (QPixmapCache::find(key, *this))
730         return true;
731
732     QScopedPointer<QPlatformPixmap> tmp(QPlatformPixmap::create(0, 0, data ? data->type : QPlatformPixmap::PixmapType));
733     if (tmp->fromFile(fileName, format, flags)) {
734         data = tmp.take();
735         QPixmapCache::insert(key, *this);
736         return true;
737     }
738
739     return false;
740 }
741
742 /*!
743     \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
744
745     Loads a pixmap from the \a len first bytes of the given binary \a
746     data.  Returns true if the pixmap was loaded successfully;
747     otherwise returns false.
748
749     The loader attempts to read the pixmap using the specified \a
750     format. If the \a format is not specified (which is the default),
751     the loader probes the file for a header to guess the file format.
752
753     If the data needs to be modified to fit in a lower-resolution
754     result (e.g. converting from 32-bit to 8-bit), use the \a flags to
755     control the conversion.
756
757     \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
758     Writing Image Files}
759 */
760
761 bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
762 {
763     if (len == 0 || buf == 0)
764         return false;
765
766     if (!data)
767         data = QPlatformPixmap::create(0, 0, QPlatformPixmap::PixmapType);
768
769     return data->fromData(buf, len, format, flags);
770 }
771
772 /*!
773     \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
774
775     \overload
776
777     Loads a pixmap from the binary \a data using the specified \a
778     format and conversion \a flags.
779 */
780
781
782 /*!
783     Saves the pixmap to the file with the given \a fileName using the
784     specified image file \a format and \a quality factor. Returns true
785     if successful; otherwise returns false.
786
787     The \a quality factor must be in the range [0,100] or -1. Specify
788     0 to obtain small compressed files, 100 for large uncompressed
789     files, and -1 to use the default settings.
790
791     If \a format is 0, an image format will be chosen from \a fileName's
792     suffix.
793
794     \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
795     Image Files}
796 */
797
798 bool QPixmap::save(const QString &fileName, const char *format, int quality) const
799 {
800     if (isNull())
801         return false;                                // nothing to save
802     QImageWriter writer(fileName, format);
803     return doImageIO(&writer, quality);
804 }
805
806 /*!
807     \overload
808
809     This function writes a QPixmap to the given \a device using the
810     specified image file \a format and \a quality factor. This can be
811     used, for example, to save a pixmap directly into a QByteArray:
812
813     \snippet doc/src/snippets/image/image.cpp 1
814 */
815
816 bool QPixmap::save(QIODevice* device, const char* format, int quality) const
817 {
818     if (isNull())
819         return false;                                // nothing to save
820     QImageWriter writer(device, format);
821     return doImageIO(&writer, quality);
822 }
823
824 /*! \internal
825 */
826 bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
827 {
828     if (quality > 100  || quality < -1)
829         qWarning("QPixmap::save: quality out of range [-1,100]");
830     if (quality >= 0)
831         writer->setQuality(qMin(quality,100));
832     return writer->write(toImage());
833 }
834
835 /*!
836     \fn void QPixmap::fill(const QPaintDevice *device, int x, int y)
837     \overload
838
839     \obsolete
840
841     Fills the pixmap with the \a device's background color or pixmap.
842     The given point, (\a x, \a y), defines an offset in widget
843     coordinates to which the pixmap's top-left pixel will be mapped
844     to.
845 */
846
847 void QPixmap::fill(const QPaintDevice *, const QPoint &)
848 {
849     qWarning() << "QPixmap::fill(const QPaintDevice *device, const QPoint &offset) is deprecated, ignored";
850 }
851
852
853 /*!
854     Fills the pixmap with the given \a color.
855
856     The effect of this function is undefined when the pixmap is
857     being painted on.
858
859     \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
860 */
861
862 void QPixmap::fill(const QColor &color)
863 {
864     if (isNull())
865         return;
866
867     // Some people are probably already calling fill while a painter is active, so to not break
868     // their programs, only print a warning and return when the fill operation could cause a crash.
869     if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
870         qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
871         return;
872     }
873
874     if (data->ref.load() == 1) {
875         // detach() will also remove this pixmap from caches, so
876         // it has to be called even when ref == 1.
877         detach();
878     } else {
879         // Don't bother to make a copy of the data object, since
880         // it will be filled with new pixel data anyway.
881         QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
882         d->resize(data->width(), data->height());
883         data = d;
884     }
885     data->fill(color);
886 }
887
888 /*! \fn int QPixmap::serialNumber() const
889     \obsolete
890     Returns a number that identifies the contents of this QPixmap
891     object. Distinct QPixmap objects can only have the same serial
892     number if they refer to the same contents (but they don't have
893     to).
894
895     Use cacheKey() instead.
896
897     \warning The serial number doesn't necessarily change when
898     the pixmap is altered. This means that it may be dangerous to use
899     it as a cache key. For caching pixmaps, we recommend using the
900     QPixmapCache class whenever possible.
901 */
902
903 /*!
904     Returns a number that identifies this QPixmap. Distinct QPixmap
905     objects can only have the same cache key if they refer to the same
906     contents.
907
908     The cacheKey() will change when the pixmap is altered.
909 */
910 qint64 QPixmap::cacheKey() const
911 {
912     if (isNull())
913         return 0;
914
915     Q_ASSERT(data);
916     return data->cacheKey();
917 }
918
919 #if 0
920 static void sendResizeEvents(QWidget *target)
921 {
922     QResizeEvent e(target->size(), QSize());
923     QApplication::sendEvent(target, &e);
924
925     const QObjectList children = target->children();
926     for (int i = 0; i < children.size(); ++i) {
927         QWidget *child = static_cast<QWidget*>(children.at(i));
928         if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
929             sendResizeEvents(child);
930     }
931 }
932 #endif
933
934 QPixmap QPixmap::grabWidget(QObject *widget, const QRect &rectangle)
935 {
936     QPixmap pixmap;
937     qWarning("QPixmap::grabWidget is deprecated, use QWidget::grab() instead");
938     if (!widget)
939         return pixmap;
940     QMetaObject::invokeMethod(widget, "grab", Qt::DirectConnection,
941                               Q_RETURN_ARG(QPixmap, pixmap),
942                               Q_ARG(QRect, rectangle));
943     return pixmap;
944 }
945
946 /*****************************************************************************
947   QPixmap stream functions
948  *****************************************************************************/
949 #if !defined(QT_NO_DATASTREAM)
950 /*!
951     \relates QPixmap
952
953     Writes the given \a pixmap to the given \a stream as a PNG
954     image. Note that writing the stream to a file will not produce a
955     valid image file.
956
957     \sa QPixmap::save(), {Serializing Qt Data Types}
958 */
959
960 QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
961 {
962     return stream << pixmap.toImage();
963 }
964
965 /*!
966     \relates QPixmap
967
968     Reads an image from the given \a stream into the given \a pixmap.
969
970     \sa QPixmap::load(), {Serializing Qt Data Types}
971 */
972
973 QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
974 {
975     QImage image;
976     stream >> image;
977
978     if (image.isNull()) {
979         pixmap = QPixmap();
980     } else if (image.depth() == 1) {
981         pixmap = QBitmap::fromImage(image);
982     } else {
983         pixmap = QPixmap::fromImage(image);
984     }
985     return stream;
986 }
987
988 #endif // QT_NO_DATASTREAM
989
990 /*!
991     \internal
992 */
993
994 bool QPixmap::isDetached() const
995 {
996     return data && data->ref.load() == 1;
997 }
998
999 /*!
1000     Replaces this pixmap's data with the given \a image using the
1001     specified \a flags to control the conversion.  The \a flags
1002     argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1003     Passing 0 for \a flags sets all the default options. Returns true
1004     if the result is that this pixmap is not null.
1005
1006     Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
1007     It has been promoted to official API status in 4.7 to support updating
1008     the pixmap's image without creating a new QPixmap as fromImage() would.
1009
1010     \sa fromImage()
1011     \since 4.7
1012 */
1013 bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1014 {
1015     if (image.isNull() || !data)
1016         *this = QPixmap::fromImage(image, flags);
1017     else
1018         data->fromImage(image, flags);
1019     return !isNull();
1020 }
1021
1022 /*!
1023     \fn QPixmap QPixmap::scaled(int width, int height,
1024     Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1025     transformMode) const
1026
1027     \overload
1028
1029     Returns a copy of the pixmap scaled to a rectangle with the given
1030     \a width and \a height according to the given \a aspectRatioMode and
1031     \a transformMode.
1032
1033     If either the \a width or the \a height is zero or negative, this
1034     function returns a null pixmap.
1035 */
1036
1037 /*!
1038     \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1039     aspectRatioMode, Qt::TransformationMode transformMode) const
1040
1041     Scales the pixmap to the given \a size, using the aspect ratio and
1042     transformation modes specified by \a aspectRatioMode and \a
1043     transformMode.
1044
1045     \image qimage-scaling.png
1046
1047     \list
1048     \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1049        is scaled to \a size.
1050     \li If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1051        scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1052     \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1053        the pixmap is scaled to a rectangle as small as possible
1054        outside \a size, preserving the aspect ratio.
1055     \endlist
1056
1057     If the given \a size is empty, this function returns a null
1058     pixmap.
1059
1060
1061     In some cases it can be more beneficial to draw the pixmap to a
1062     painter with a scale set rather than scaling the pixmap. This is
1063     the case when the painter is for instance based on OpenGL or when
1064     the scale factor changes rapidly.
1065
1066     \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1067     Transformations}
1068
1069 */
1070 QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1071 {
1072     if (isNull()) {
1073         qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1074         return QPixmap();
1075     }
1076     if (s.isEmpty())
1077         return QPixmap();
1078
1079     QSize newSize = size();
1080     newSize.scale(s, aspectMode);
1081     newSize.rwidth() = qMax(newSize.width(), 1);
1082     newSize.rheight() = qMax(newSize.height(), 1);
1083     if (newSize == size())
1084         return *this;
1085
1086     QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1087                                           (qreal)newSize.height() / height());
1088     QPixmap pix = transformed(wm, mode);
1089     return pix;
1090 }
1091
1092 /*!
1093     \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1094     mode) const
1095
1096     Returns a scaled copy of the image. The returned image is scaled
1097     to the given \a width using the specified transformation \a mode.
1098     The height of the pixmap is automatically calculated so that the
1099     aspect ratio of the pixmap is preserved.
1100
1101     If \a width is 0 or negative, a null pixmap is returned.
1102
1103     \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1104     Transformations}
1105 */
1106 QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1107 {
1108     if (isNull()) {
1109         qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1110         return copy();
1111     }
1112     if (w <= 0)
1113         return QPixmap();
1114
1115     qreal factor = (qreal) w / width();
1116     QTransform wm = QTransform::fromScale(factor, factor);
1117     return transformed(wm, mode);
1118 }
1119
1120 /*!
1121     \fn QPixmap QPixmap::scaledToHeight(int height,
1122     Qt::TransformationMode mode) const
1123
1124     Returns a scaled copy of the image. The returned image is scaled
1125     to the given \a height using the specified transformation \a mode.
1126     The width of the pixmap is automatically calculated so that the
1127     aspect ratio of the pixmap is preserved.
1128
1129     If \a height is 0 or negative, a null pixmap is returned.
1130
1131     \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1132     Transformations}
1133 */
1134 QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1135 {
1136     if (isNull()) {
1137         qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1138         return copy();
1139     }
1140     if (h <= 0)
1141         return QPixmap();
1142
1143     qreal factor = (qreal) h / height();
1144     QTransform wm = QTransform::fromScale(factor, factor);
1145     return transformed(wm, mode);
1146 }
1147
1148 /*!
1149     Returns a copy of the pixmap that is transformed using the given
1150     transformation \a transform and transformation \a mode. The original
1151     pixmap is not changed.
1152
1153     The transformation \a transform is internally adjusted to compensate
1154     for unwanted translation; i.e. the pixmap produced is the smallest
1155     pixmap that contains all the transformed points of the original
1156     pixmap. Use the trueMatrix() function to retrieve the actual
1157     matrix used for transforming the pixmap.
1158
1159     This function is slow because it involves transformation to a
1160     QImage, non-trivial computations and a transformation back to a
1161     QPixmap.
1162
1163     \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1164     Transformations}
1165 */
1166 QPixmap QPixmap::transformed(const QTransform &transform,
1167                              Qt::TransformationMode mode) const
1168 {
1169     if (isNull() || transform.type() <= QTransform::TxTranslate)
1170         return *this;
1171
1172     return data->transformed(transform, mode);
1173 }
1174
1175 /*!
1176   \overload
1177
1178   This convenience function loads the \a matrix into a
1179   QTransform and calls the overloaded function.
1180  */
1181 QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1182 {
1183     return transformed(QTransform(matrix), mode);
1184 }
1185
1186
1187
1188
1189
1190
1191
1192
1193 /*!
1194     \class QPixmap
1195
1196     \brief The QPixmap class is an off-screen image representation
1197     that can be used as a paint device.
1198
1199     \ingroup painting
1200     \ingroup shared
1201
1202
1203     Qt provides four classes for handling image data: QImage, QPixmap,
1204     QBitmap and QPicture. QImage is designed and optimized for I/O,
1205     and for direct pixel access and manipulation, while QPixmap is
1206     designed and optimized for showing images on screen. QBitmap is
1207     only a convenience class that inherits QPixmap, ensuring a depth
1208     of 1. The isQBitmap() function returns true if a QPixmap object is
1209     really a bitmap, otherwise returns false. Finally, the QPicture class
1210     is a paint device that records and replays QPainter commands.
1211
1212     A QPixmap can easily be displayed on the screen using QLabel or
1213     one of QAbstractButton's subclasses (such as QPushButton and
1214     QToolButton). QLabel has a pixmap property, whereas
1215     QAbstractButton has an icon property.
1216
1217     In addition to the ordinary constructors, a QPixmap can be
1218     constructed using the static grabWidget() and grabWindow()
1219     functions which creates a QPixmap and paints the given widget, or
1220     window, into it.
1221
1222     QPixmap objects can be passed around by value since the QPixmap
1223     class uses implicit data sharing. For more information, see the \l
1224     {Implicit Data Sharing} documentation. QPixmap objects can also be
1225     streamed.
1226
1227     Note that the pixel data in a pixmap is internal and is managed by
1228     the underlying window system. Because QPixmap is a QPaintDevice
1229     subclass, QPainter can be used to draw directly onto pixmaps.
1230     Pixels can only be accessed through QPainter functions or by
1231     converting the QPixmap to a QImage. However, the fill() function
1232     is available for initializing the entire pixmap with a given color.
1233
1234     There are functions to convert between QImage and
1235     QPixmap. Typically, the QImage class is used to load an image
1236     file, optionally manipulating the image data, before the QImage
1237     object is converted into a QPixmap to be shown on
1238     screen. Alternatively, if no manipulation is desired, the image
1239     file can be loaded directly into a QPixmap. On Windows, the
1240     QPixmap class also supports conversion between \c HBITMAP and
1241     QPixmap.
1242
1243     QPixmap provides a collection of functions that can be used to
1244     obtain a variety of information about the pixmap. In addition,
1245     there are several functions that enables transformation of the
1246     pixmap.
1247
1248     \tableofcontents
1249
1250     \section1 Reading and Writing Image Files
1251
1252     QPixmap provides several ways of reading an image file: The file
1253     can be loaded when constructing the QPixmap object, or by using
1254     the load() or loadFromData() functions later on. When loading an
1255     image, the file name can either refer to an actual file on disk or
1256     to one of the application's embedded resources. See \l{The Qt
1257     Resource System} overview for details on how to embed images and
1258     other resource files in the application's executable.
1259
1260     Simply call the save() function to save a QPixmap object.
1261
1262     The complete list of supported file formats are available through
1263     the QImageReader::supportedImageFormats() and
1264     QImageWriter::supportedImageFormats() functions. New file formats
1265     can be added as plugins. By default, Qt supports the following
1266     formats:
1267
1268     \table
1269     \header \li Format \li Description                      \li Qt's support
1270     \row    \li BMP    \li Windows Bitmap                   \li Read/write
1271     \row    \li GIF    \li Graphic Interchange Format (optional) \li Read
1272     \row    \li JPG    \li Joint Photographic Experts Group \li Read/write
1273     \row    \li JPEG   \li Joint Photographic Experts Group \li Read/write
1274     \row    \li PNG    \li Portable Network Graphics        \li Read/write
1275     \row    \li PBM    \li Portable Bitmap                  \li Read
1276     \row    \li PGM    \li Portable Graymap                 \li Read
1277     \row    \li PPM    \li Portable Pixmap                  \li Read/write
1278     \row    \li XBM    \li X11 Bitmap                       \li Read/write
1279     \row    \li XPM    \li X11 Pixmap                       \li Read/write
1280     \endtable
1281
1282     \section1 Pixmap Information
1283
1284     QPixmap provides a collection of functions that can be used to
1285     obtain a variety of information about the pixmap:
1286
1287     \table
1288     \header
1289     \li \li Available Functions
1290     \row
1291     \li Geometry
1292     \li
1293     The size(), width() and height() functions provide information
1294     about the pixmap's size. The rect() function returns the image's
1295     enclosing rectangle.
1296
1297     \row
1298     \li Alpha component
1299     \li
1300
1301     The hasAlphaChannel() returns true if the pixmap has a format that
1302     respects the alpha channel, otherwise returns false. The hasAlpha(),
1303     setMask() and mask() functions are legacy and should not be used.
1304     They are potentially very slow.
1305
1306     The createHeuristicMask() function creates and returns a 1-bpp
1307     heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1308     selecting a color from one of the corners and then chipping away
1309     pixels of that color, starting at all the edges. The
1310     createMaskFromColor() function creates and returns a mask (i.e. a
1311     QBitmap) for the pixmap based on a given color.
1312
1313     \row
1314     \li Low-level information
1315     \li
1316
1317     The depth() function returns the depth of the pixmap. The
1318     defaultDepth() function returns the default depth, i.e. the depth
1319     used by the application on the given screen.
1320
1321     The cacheKey() function returns a number that uniquely
1322     identifies the contents of the QPixmap object.
1323
1324     The x11Info() function returns information about the configuration
1325     of the X display used by the screen to which the pixmap currently
1326     belongs. The x11PictureHandle() function returns the X11 Picture
1327     handle of the pixmap for XRender support. Note that the two latter
1328     functions are only available on x11.
1329
1330     \endtable
1331
1332     \section1 Pixmap Conversion
1333
1334     A QPixmap object can be converted into a QImage using the
1335     toImage() function. Likewise, a QImage can be converted into a
1336     QPixmap using the fromImage(). If this is too expensive an
1337     operation, you can use QBitmap::fromImage() instead.
1338
1339     In addition, on Windows, the QPixmap class supports conversion to
1340     and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1341     equivalent to the QPixmap, based on the given HBitmapFormat, and
1342     returns the HBITMAP handle. The fromWinHBITMAP() function returns
1343     a QPixmap that is equivalent to the given bitmap which has the
1344     specified format. The QPixmap class also supports conversion to
1345     and from HICON: the toWinHICON() function creates a HICON equivalent
1346     to the QPixmap, and returns the HICON handle. The fromWinHICON()
1347     function returns a QPixmap that is equivalent to the given icon.
1348
1349     \section1 Pixmap Transformations
1350
1351     QPixmap supports a number of functions for creating a new pixmap
1352     that is a transformed version of the original:
1353
1354     The scaled(), scaledToWidth() and scaledToHeight() functions
1355     return scaled copies of the pixmap, while the copy() function
1356     creates a QPixmap that is a plain copy of the original one.
1357
1358     The transformed() function returns a copy of the pixmap that is
1359     transformed with the given transformation matrix and
1360     transformation mode: Internally, the transformation matrix is
1361     adjusted to compensate for unwanted translation,
1362     i.e. transformed() returns the smallest pixmap containing all
1363     transformed points of the original pixmap. The static trueMatrix()
1364     function returns the actual matrix used for transforming the
1365     pixmap.
1366
1367     \note When using the native X11 graphics system, the pixmap
1368     becomes invalid when the QApplication instance is destroyed.
1369
1370     \sa QBitmap, QImage, QImageReader, QImageWriter
1371 */
1372
1373
1374 /*!
1375     \typedef QPixmap::DataPtr
1376     \internal
1377 */
1378
1379 /*!
1380     \fn DataPtr &QPixmap::data_ptr()
1381     \internal
1382 */
1383
1384 /*!
1385     Returns true if this pixmap has an alpha channel, \e or has a
1386     mask, otherwise returns false.
1387
1388     \sa hasAlphaChannel(), mask()
1389 */
1390 bool QPixmap::hasAlpha() const
1391 {
1392     return data && data->hasAlphaChannel();
1393 }
1394
1395 /*!
1396     Returns true if the pixmap has a format that respects the alpha
1397     channel, otherwise returns false.
1398
1399     \sa hasAlpha()
1400 */
1401 bool QPixmap::hasAlphaChannel() const
1402 {
1403     return data && data->hasAlphaChannel();
1404 }
1405
1406 /*!
1407     \internal
1408 */
1409 int QPixmap::metric(PaintDeviceMetric metric) const
1410 {
1411     return data ? data->metric(metric) : 0;
1412 }
1413
1414 /*!
1415     \internal
1416 */
1417 QPaintEngine *QPixmap::paintEngine() const
1418 {
1419     return data ? data->paintEngine() : 0;
1420 }
1421
1422 /*!
1423     \fn QBitmap QPixmap::mask() const
1424
1425     Extracts a bitmap mask from the pixmap's alpha channel.
1426
1427     \warning This is potentially an expensive operation. The mask of
1428     the pixmap is extracted dynamically from the pixeldata.
1429
1430     \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1431 */
1432 QBitmap QPixmap::mask() const
1433 {
1434     if (!data || !hasAlphaChannel())
1435         return QBitmap();
1436
1437     const QImage img = toImage();
1438     const QImage image = (img.depth() < 32 ? img.convertToFormat(QImage::Format_ARGB32_Premultiplied) : img);
1439     const int w = image.width();
1440     const int h = image.height();
1441
1442     QImage mask(w, h, QImage::Format_MonoLSB);
1443     if (mask.isNull()) // allocation failed
1444         return QBitmap();
1445
1446     mask.setColorCount(2);
1447     mask.setColor(0, QColor(Qt::color0).rgba());
1448     mask.setColor(1, QColor(Qt::color1).rgba());
1449
1450     const int bpl = mask.bytesPerLine();
1451
1452     for (int y = 0; y < h; ++y) {
1453         const QRgb *src = reinterpret_cast<const QRgb*>(image.scanLine(y));
1454         uchar *dest = mask.scanLine(y);
1455         memset(dest, 0, bpl);
1456         for (int x = 0; x < w; ++x) {
1457             if (qAlpha(*src) > 0)
1458                 dest[x >> 3] |= (1 << (x & 7));
1459             ++src;
1460         }
1461     }
1462
1463     return QBitmap::fromImage(mask);
1464 }
1465
1466 /*!
1467     Returns the default pixmap depth used by the application.
1468
1469     On all platforms the depth of the primary screen will be returned.
1470
1471     \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1472
1473 */
1474 int QPixmap::defaultDepth()
1475 {
1476     return QGuiApplication::primaryScreen()->depth();
1477 }
1478
1479 /*!
1480     Detaches the pixmap from shared pixmap data.
1481
1482     A pixmap is automatically detached by Qt whenever its contents are
1483     about to change. This is done in almost all QPixmap member
1484     functions that modify the pixmap (fill(), fromImage(),
1485     load(), etc.), and in QPainter::begin() on a pixmap.
1486
1487     There are two exceptions in which detach() must be called
1488     explicitly, that is when calling the handle() or the
1489     x11PictureHandle() function (only available on X11). Otherwise,
1490     any modifications done using system calls, will be performed on
1491     the shared data.
1492
1493     The detach() function returns immediately if there is just a
1494     single reference or if the pixmap has not been initialized yet.
1495 */
1496 void QPixmap::detach()
1497 {
1498     if (!data)
1499         return;
1500
1501     // QPixmap.data member may be QRuntimePlatformPixmap so use handle() function to get
1502     // the actual underlaying runtime pixmap data.
1503     QPlatformPixmap *pd = handle();
1504     QPlatformPixmap::ClassId id = pd->classId();
1505     if (id == QPlatformPixmap::RasterClass) {
1506         QRasterPlatformPixmap *rasterData = static_cast<QRasterPlatformPixmap*>(pd);
1507         rasterData->image.detach();
1508     }
1509
1510     if (data->is_cached && data->ref.load() == 1)
1511         QImagePixmapCleanupHooks::executePlatformPixmapModificationHooks(data.data());
1512
1513     if (data->ref.load() != 1) {
1514         *this = copy();
1515     }
1516     ++data->detach_no;
1517 }
1518
1519 /*!
1520     \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1521
1522     Converts the given \a image to a pixmap using the specified \a
1523     flags to control the conversion.  The \a flags argument is a
1524     bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1525     flags sets all the default options.
1526
1527     In case of monochrome and 8-bit images, the image is first
1528     converted to a 32-bit pixmap and then filled with the colors in
1529     the color table. If this is too expensive an operation, you can
1530     use QBitmap::fromImage() instead.
1531
1532     \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1533 */
1534 QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1535 {
1536     if (image.isNull())
1537         return QPixmap();
1538
1539     QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1540     data->fromImage(image, flags);
1541     return QPixmap(data.take());
1542 }
1543
1544 /*!
1545     \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1546
1547     Create a QPixmap from an image read directly from an \a imageReader.
1548     The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1549     Passing 0 for \a flags sets all the default options.
1550
1551     On some systems, reading an image directly to QPixmap can use less memory than
1552     reading a QImage to convert it to QPixmap.
1553
1554     \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1555 */
1556 QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1557 {
1558     QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1559     data->fromImageReader(imageReader, flags);
1560     return QPixmap(data.take());
1561 }
1562
1563 /*!
1564     \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
1565     width, int height)
1566
1567     Creates and returns a pixmap constructed by grabbing the contents
1568     of the given \a window restricted by QRect(\a x, \a y, \a width,
1569     \a height).
1570
1571     The arguments (\a{x}, \a{y}) specify the offset in the window,
1572     whereas (\a{width}, \a{height}) specify the area to be copied.  If
1573     \a width is negative, the function copies everything to the right
1574     border of the window. If \a height is negative, the function
1575     copies everything to the bottom of the window.
1576
1577     The window system identifier (\c WId) can be retrieved using the
1578     QWidget::winId() function. The rationale for using a window
1579     identifier and not a QWidget, is to enable grabbing of windows
1580     that are not part of the application, window system frames, and so
1581     on.
1582
1583     The grabWindow() function grabs pixels from the screen, not from
1584     the window, i.e. if there is another window partially or entirely
1585     over the one you grab, you get pixels from the overlying window,
1586     too. The mouse cursor is generally not grabbed.
1587
1588     Note on X11 that if the given \a window doesn't have the same depth
1589     as the root window, and another window partially or entirely
1590     obscures the one you grab, you will \e not get pixels from the
1591     overlying window.  The contents of the obscured areas in the
1592     pixmap will be undefined and uninitialized.
1593
1594     On Windows Vista and above grabbing a layered window, which is
1595     created by setting the Qt::WA_TranslucentBackground attribute, will
1596     not work. Instead grabbing the desktop widget should work.
1597
1598     \warning In general, grabbing an area outside the screen is not
1599     safe. This depends on the underlying window system.
1600
1601     \warning The function is deprecated in Qt 5.0 since there might be
1602     platform plugins in which window system identifiers (\c WId)
1603     are local to a screen. Use QScreen::grabWindow() instead.
1604
1605     \sa grabWidget(), {Screenshot Example}
1606     \sa QScreen
1607     \deprecated
1608 */
1609
1610 QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
1611 {
1612     qWarning("%s is deprecated, use QScreen::grabWindow() instead."
1613              " Defaulting to primary screen.", Q_FUNC_INFO);
1614     return QGuiApplication::primaryScreen()->grabWindow(window, x, y, w, h);
1615 }
1616
1617 /*!
1618   \internal
1619 */
1620 QPlatformPixmap* QPixmap::handle() const
1621 {
1622     return data.data();
1623 }
1624
1625 #ifndef QT_NO_DEBUG_STREAM
1626 QDebug operator<<(QDebug dbg, const QPixmap &r)
1627 {
1628     dbg.nospace() << "QPixmap(" << r.size() << ')';
1629     return dbg.space();
1630 }
1631 #endif
1632
1633 QT_END_NAMESPACE