Initial commit.
[jspeed] / src / imageelement.cpp
1 /*
2  * This file is part of jSpeed.
3  *
4  * jSpeed is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * jSpeed is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with jSpeed.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  */
18
19 #include <QtCore/QString>
20 #include <QtCore/QDebug>
21 #include <QtGui/QGraphicsScene>
22 #include <QtGui/QGraphicsPixmapItem>
23 #include "imageelement.h"
24 #include "reader.h"
25 #include "graphicsscene.h"
26
27 namespace
28 {
29     const GraphicsElement::AttributeDetails ATTRIBUTES[ImageElement::ATTRIBUTE_COUNT] =
30     {
31      {"xpos", true},
32      {"ypos", true},
33      {"src", false}
34     };
35 }
36
37 ImageElement::ImageElement(Reader* reader): GraphicsElement(reader)
38 {
39     element_ = new QGraphicsPixmapItem();
40 }
41
42 bool ImageElement::setAttribute(QString const& name,
43                                 QString const& value)
44 {
45     int intVal = 0;
46     int attrId = -1;
47
48     if((attrId = getAttribute(name, value, ATTRIBUTES, ATTRIBUTE_COUNT, intVal)) != -1)
49     {
50         Attribute attr = static_cast<Attribute>(attrId);
51
52         switch(attr)
53         {
54         case XPOS:
55             element_->setX(intVal);
56             break;
57         case YPOS:
58             element_->setY(intVal);
59             break;
60         case SRC:
61             return loadImage(value);
62             break;
63
64         default:
65             qDebug() << "Unknown attribute: " << attr;
66             return false;
67         }
68
69         return true;
70     }
71     else
72     {
73         return false;
74     }
75 }
76
77 void ImageElement::addToScene(GraphicsScene* scene)
78 {
79     scene->addItem(element_);
80 }
81
82 void ImageElement::update()
83 {
84 }
85
86 bool ImageElement::loadImage(QString const& name)
87 {
88     QPixmap pixmap;
89     QByteArray data;
90
91     if(!readFile(name, data))
92     {
93         return false;
94     }
95
96     if(!pixmap.loadFromData(data))
97     {
98         setError("Invalid image file: " + name);
99         return false;
100     }
101
102     element_->setPixmap(pixmap);
103
104     return true;
105 }