1 /*
2  * This file is part of the KDE project
3  *
4  * Copyright (C) 2013 Arjen Hiemstra <ahiemstra@heimr.nl>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public License
17  * along with this library; see the file COPYING.LIB.  If not, write to
18  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 #include "ImageDataItem.h"
24 
25 #include <QPixmap>
26 #include <QSGSimpleTextureNode>
27 #include <QQuickWindow>
28 
29 using namespace Calligra::Components;
30 
31 class ImageDataItem::Private
32 {
33 public:
Private()34     Private() : imageChanged(false)
35     { }
36 
37     QImage data;
38     bool imageChanged;
39 };
40 
ImageDataItem(QQuickItem * parent)41 ImageDataItem::ImageDataItem(QQuickItem* parent)
42     : QQuickItem{parent}, d{new Private}
43 {
44     setFlag(QQuickItem::ItemHasContents, true);
45 }
46 
~ImageDataItem()47 ImageDataItem::~ImageDataItem()
48 {
49     delete d;
50 }
51 
data() const52 QImage ImageDataItem::data() const
53 {
54     return d->data;
55 }
56 
setData(const QImage & newValue)57 void ImageDataItem::setData(const QImage& newValue)
58 {
59     if(newValue != d->data) {
60         d->data = newValue;
61         setImplicitWidth(d->data.width());
62         setImplicitHeight(d->data.height());
63         d->imageChanged = true;
64         update();
65         emit dataChanged();
66     }
67 }
68 
updatePaintNode(QSGNode * node,QQuickItem::UpdatePaintNodeData *)69 QSGNode* ImageDataItem::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData*)
70 {
71     if(d->data.isNull()) {
72         return node;
73     }
74 
75     float w = widthValid() ? width() : d->data.width();
76     float h = heightValid() ? height() : d->data.height();
77 
78     auto texNode = static_cast<QSGSimpleTextureNode*>(node);
79     if(!texNode) {
80         texNode = new QSGSimpleTextureNode{};
81     }
82     texNode->setRect(0, 0, w, h);
83 
84     if (!texNode->texture() || d->imageChanged) {
85         delete texNode->texture();
86         auto texture = window()->createTextureFromImage(d->data);
87         texNode->setTexture(texture);
88         d->imageChanged = false;
89     }
90 
91     return texNode;
92 }
93