Adding icon
[impuzzle] / src / imageimporter.cpp
1 /*
2   Image Puzzle - A set your pieces straight game
3   Copyright (C) 2009  Timo Härkönen
4
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "imageimporter.h"
20 #include "puzzleitem.h"
21 #include "defines.h"
22
23 #include <QPixmap>
24
25 #include <QDebug>
26
27 ImageImporter *ImageImporter::instance_ = 0;
28
29 ImageImporter::ImageImporter(QObject *parent) :
30         QObject(parent)
31 {
32
33 }
34
35 ImageImporter *ImageImporter::instance()
36 {
37     if(!instance_) {
38         instance_ = new ImageImporter;
39     }
40
41     return instance_;
42 }
43
44 QList<PuzzleItem *> ImageImporter::newPieces(const QPixmap &pixmap, const int count)
45 {
46     QPixmap tmp;
47
48     if(pixmap.isNull()) {
49         qDebug() << "Got NULL image - using default.jpg";
50         tmp = QPixmap(":/images/default.jpg");
51     }
52     else {
53         tmp = pixmap;
54     }
55
56     if(tmp.size().height() != IMAGE_HEIGHT || tmp.size().width() != IMAGE_WIDTH) {
57         tmp = pixmap.scaled(QSize(IMAGE_WIDTH, IMAGE_HEIGHT), Qt::KeepAspectRatioByExpanding);
58     }
59
60     QList<PuzzleItem *> list;
61
62     int horizontalCount = 0;
63
64     if(count == EASY_PIECE_COUNT) {
65         horizontalCount = EASY_HORIZONTAL_COUNT;
66     }
67     else if(count == HARD_PIECE_COUNT) {
68         horizontalCount = HARD_HORIZONTAL_COUNT;
69     }
70     else {
71         qDebug() << QString("Bad piece count ( %1 ) @ ImageImporter::newPieces").arg(count);
72         return list;
73     }
74
75     int verticalCount = count / horizontalCount;
76     int verticalStep = IMAGE_HEIGHT / verticalCount;
77     int horizontalStep = IMAGE_WIDTH / horizontalCount;
78
79     int pieceNo = 1;
80
81     for(int i = 0; i < verticalCount; ++i) {
82         for(int j = 0; j < horizontalCount; ++j) {
83             PuzzleItem *item = new PuzzleItem;
84             item->setPixmap(tmp.copy(QRect(QPoint(j * horizontalStep, i * verticalStep),
85                                            QPoint(horizontalStep + j * horizontalStep, verticalStep + i * verticalStep))));
86             item->setPieceNumber(pieceNo);
87             pieceNo++;
88             list.append(item);
89         }
90     }
91
92     return list;
93 }