1 /* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "TilePainter.h"
7
8 #include <QImage>
9 #include <QMouseEvent>
10 #include <QPainter>
11
12 using namespace QGBA;
13
TilePainter(QWidget * parent)14 TilePainter::TilePainter(QWidget* parent)
15 : QWidget(parent)
16 {
17 m_backing.fill(Qt::transparent);
18 resize(256, 768);
19 setTileCount(3072);
20 }
21
paintEvent(QPaintEvent *)22 void TilePainter::paintEvent(QPaintEvent*) {
23 QPainter painter(this);
24 painter.drawPixmap(QPoint(), m_backing);
25 }
26
resizeEvent(QResizeEvent *)27 void TilePainter::resizeEvent(QResizeEvent*) {
28 int w = width() / m_size;
29 if (!w) {
30 w = 1;
31 }
32 int calculatedHeight = (m_tileCount + w - 1) * m_size / w;
33 calculatedHeight -= calculatedHeight % m_size;
34 if (width() / m_size != m_backing.width() / m_size || m_backing.height() != calculatedHeight) {
35 m_backing = QPixmap(width(), calculatedHeight);
36 m_backing.fill(Qt::transparent);
37 emit needsRedraw();
38 }
39 }
40
mousePressEvent(QMouseEvent * event)41 void TilePainter::mousePressEvent(QMouseEvent* event) {
42 int x = event->x() / m_size;
43 int y = event->y() / m_size;
44 emit indexPressed(y * (width() / m_size) + x);
45 }
46
clearTile(int index)47 void TilePainter::clearTile(int index) {
48 QPainter painter(&m_backing);
49 int w = width() / m_size;
50 int x = index % w;
51 int y = index / w;
52 QRect r(x * m_size, y * m_size, m_size, m_size);
53 painter.eraseRect(r);
54 update(r);
55 }
56
setTile(int index,const color_t * data)57 void TilePainter::setTile(int index, const color_t* data) {
58 QPainter painter(&m_backing);
59 int w = width() / m_size;
60 int x = index % w;
61 int y = index / w;
62 QRect r(x * m_size, y * m_size, m_size, m_size);
63 QImage tile(reinterpret_cast<const uchar*>(data), 8, 8, QImage::Format_ARGB32);
64 tile = tile.convertToFormat(QImage::Format_RGB32).rgbSwapped();
65 painter.drawImage(r, tile);
66 update(r);
67 }
68
setTileCount(int tiles)69 void TilePainter::setTileCount(int tiles) {
70 m_tileCount = tiles;
71 if (sizePolicy().horizontalPolicy() != QSizePolicy::Fixed) {
72 // Only manage the size ourselves if we don't appear to have something else managing it
73 int w = width() / m_size;
74 int h = (tiles + w - 1) * m_size / w;
75 setMinimumSize(m_size, h - (h % m_size));
76 } else {
77 int w = minimumSize().width() / m_size;
78 if (!w) {
79 w = 1;
80 }
81 int h = (tiles + w - 1) * m_size / w;
82 setMinimumSize(w * m_size, h - (h % m_size));
83 }
84 resizeEvent(nullptr);
85 }
86
setTileMagnification(int mag)87 void TilePainter::setTileMagnification(int mag) {
88 m_size = mag * 8;
89 setTileCount(m_tileCount);
90 }
91