summaryrefslogtreecommitdiff
path: root/gui/pixelwidget.cpp
blob: 8f8fdc71b2b4ca1924a63985dc36a8764cc3f8ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/**
 * The source code is based on qpixeltool.cpp.
 * Original license follows.
 */

/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "pixelwidget.h"

#include <qapplication.h>
#include <qdesktopwidget.h>
#include <qapplication.h>
#ifndef QT_NO_CLIPBOARD
#include <qclipboard.h>
#endif
#include <qpainter.h>
#include <qevent.h>
#include <qfiledialog.h>
#include <qmenu.h>
#include <qactiongroup.h>

#include <qdebug.h>

PixelWidget::PixelWidget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle(QLatin1String("PixelTool"));
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    m_gridSize = 1;
    m_gridActive = 0;
    m_zoom = 1;
    m_displayGridSize = false;
    m_displayGridSizeId = 0;

    m_mouseDown = false;

    m_initialSize = QSize(250, 250);

    setMouseTracking(true);
    setAutoFillBackground(true);
}

PixelWidget::~PixelWidget()
{
}

void PixelWidget::setSurface(const QImage &image)
{
    m_surface = image;
    updateGeometry();
    update();
}

void PixelWidget::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_displayGridSizeId) {
        killTimer(m_displayGridSizeId);
        m_displayGridSize = false;
    }
}

void render_string(QPainter *p, int w, int h, const QString &text, int flags)
{
    p->setBrush(QColor(255, 255, 255, 191));
    p->setPen(Qt::black);
    QRect bounds;
    p->drawText(0, 0, w, h, Qt::TextDontPrint | flags, text, &bounds);

    if (bounds.x() == 0) bounds.adjust(0, 0, 10, 0);
    else bounds.adjust(-10, 0, 0, 0);

    if (bounds.y() == 0) bounds.adjust(0, 0, 0, 10);
    else bounds.adjust(0, -10, 0, 0);

    p->drawRect(bounds);
    p->drawText(bounds, flags, text);
}

void PixelWidget::paintEvent(QPaintEvent *)
{
    QPainter p(this);

    int w = width();
    int h = height();

    p.save();
    p.scale(zoomValue(), zoomValue());
    p.setCompositionMode(QPainter::CompositionMode_SourceOver);
    p.drawImage(0, 0, m_surface);
    p.scale(1/zoomValue(), 1/zoomValue());
    p.restore();

    // Draw the grid on top.
    if (m_gridActive) {
        p.setPen(m_gridActive == 1 ? Qt::black : Qt::white);
        int incr = m_gridSize * zoomValue();
        for (int x=0; x<w; x+=incr)
            p.drawLine(x, 0, x, h);
        for (int y=0; y<h; y+=incr)
            p.drawLine(0, y, w, y);
    }

    QFont f(QLatin1String("courier"));
    f.setBold(true);
    p.setFont(f);

    if (m_displayGridSize) {
        render_string(&p, w, h,
            QString::fromLatin1("Grid size: %1").arg(m_gridSize),
                      Qt::AlignBottom | Qt::AlignLeft);
    }

    if (m_mouseDown && m_dragStart != m_dragCurrent) {
        int x1 = (m_dragStart.x() / zoomValue()) * zoomValue();
        int y1 = (m_dragStart.y() / zoomValue()) * zoomValue();
        int x2 = (m_dragCurrent.x() / zoomValue()) * zoomValue();
        int y2 = (m_dragCurrent.y() / zoomValue()) * zoomValue();
        QRect r = QRect(x1, y1, x2 - x1, y2 - y1).normalized();
        p.setBrush(Qt::NoBrush);
        p.setPen(QPen(Qt::red, 3, Qt::SolidLine));
        p.drawRect(r);
        p.setPen(QPen(Qt::black, 1, Qt::SolidLine));
        p.drawRect(r);

        QRect rect(
            int(r.x() / zoomValue()),
            int(r.y() / zoomValue()),
            int(r.width() / zoomValue()),
            int(r.height() / zoomValue()));
        emit gridGeometry(rect);
    } else {
        QRect empty;
        emit gridGeometry(empty);
    }


}

void PixelWidget::keyPressEvent(QKeyEvent *e)
{
    switch (e->key()) {
    case Qt::Key_Plus:
        increaseZoom();
        break;
    case Qt::Key_Minus:
        decreaseZoom();
        break;
    case Qt::Key_PageUp:
        setGridSize(m_gridSize + 1);
        break;
    case Qt::Key_PageDown:
        setGridSize(m_gridSize - 1);
        break;
    case Qt::Key_G:
        toggleGrid();
        break;
    case Qt::Key_C:
        if (e->modifiers() & Qt::ControlModifier)
            copyToClipboard();
        break;
    case Qt::Key_S:
        if (e->modifiers() & Qt::ControlModifier) {
            releaseKeyboard();
            saveToFile();
        }
        break;
    case Qt::Key_Control:
        grabKeyboard();
        break;
    }
}

void PixelWidget::keyReleaseEvent(QKeyEvent *e)
{
    switch(e->key()) {
    case Qt::Key_Control:
        releaseKeyboard();
        break;
    default:
        break;
    }
}

void PixelWidget::resizeEvent(QResizeEvent *e)
{
    QWidget::resizeEvent(e);
}

void PixelWidget::mouseMoveEvent(QMouseEvent *e)
{
    if (m_mouseDown)
        m_dragCurrent = e->pos();

    int x = e->x() / zoomValue();
    int y = e->y() / zoomValue();

    if (x < m_surface.width() && y < m_surface.height() && x >= 0 && y >= 0) {
        m_currentColor = m_surface.pixel(x, y);
    } else
        m_currentColor = QColor();

    emit mousePosition(x, y);
    update();
}

void PixelWidget::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton)
        m_mouseDown = true;
    m_dragStart = e->pos();
}

void PixelWidget::mouseReleaseEvent(QMouseEvent *)
{
    m_mouseDown = false;
}

void PixelWidget::contextMenuEvent(QContextMenuEvent *e)
{
    QMenu menu;

    QAction title(QLatin1String("Surface Pixel Tool"), &menu);
    title.setEnabled(false);

    // Grid color options...
    QActionGroup gridGroup(this);
    QAction whiteGrid(QLatin1String("White grid"), &gridGroup);
    whiteGrid.setCheckable(true);
    whiteGrid.setChecked(m_gridActive == 2);
    whiteGrid.setShortcut(QKeySequence(Qt::Key_G));
    QAction blackGrid(QLatin1String("Black grid"), &gridGroup);
    blackGrid.setCheckable(true);
    blackGrid.setChecked(m_gridActive == 1);
    blackGrid.setShortcut(QKeySequence(Qt::Key_G));
    QAction noGrid(QLatin1String("No grid"), &gridGroup);
    noGrid.setCheckable(true);
    noGrid.setChecked(m_gridActive == 0);
    noGrid.setShortcut(QKeySequence(Qt::Key_G));

    // Grid size options
    QAction incrGrid(QLatin1String("Increase grid size"), &menu);
    incrGrid.setShortcut(QKeySequence(Qt::Key_PageUp));
    connect(&incrGrid, SIGNAL(triggered()), this, SLOT(increaseGridSize()));
    QAction decrGrid(QLatin1String("Decrease grid size"), &menu);
    decrGrid.setShortcut(QKeySequence(Qt::Key_PageDown));
    connect(&decrGrid, SIGNAL(triggered()), this, SLOT(decreaseGridSize()));

    // Zoom options
    QAction incrZoom(QLatin1String("Zoom in"), &menu);
    incrZoom.setShortcut(QKeySequence(Qt::Key_Plus));
    connect(&incrZoom, SIGNAL(triggered()), this, SLOT(increaseZoom()));
    QAction decrZoom(QLatin1String("Zoom out"), &menu);
    decrZoom.setShortcut(QKeySequence(Qt::Key_Minus));
    connect(&decrZoom, SIGNAL(triggered()), this, SLOT(decreaseZoom()));

    // Copy to clipboard / save
    QAction save(QLatin1String("Save as image"), &menu);
    save.setShortcut(QKeySequence(QLatin1String("Ctrl+S")));
    connect(&save, SIGNAL(triggered()), this, SLOT(saveToFile()));
#ifndef QT_NO_CLIPBOARD
    QAction copy(QLatin1String("Copy to clipboard"), &menu);
    copy.setShortcut(QKeySequence(QLatin1String("Ctrl+C")));
    connect(&copy, SIGNAL(triggered()), this, SLOT(copyToClipboard()));
#endif

    menu.addAction(&title);
    menu.addSeparator();
    menu.addAction(&whiteGrid);
    menu.addAction(&blackGrid);
    menu.addAction(&noGrid);
    menu.addSeparator();
    menu.addAction(&incrGrid);
    menu.addAction(&decrGrid);
    menu.addSeparator();
    menu.addAction(&incrZoom);
    menu.addAction(&decrZoom);
    menu.addSeparator();
    menu.addAction(&save);
#ifndef QT_NO_CLIPBOARD
    menu.addAction(&copy);
#endif

    menu.exec(mapToGlobal(e->pos()));

    if (noGrid.isChecked()) m_gridActive = 0;
    else if (blackGrid.isChecked()) m_gridActive = 1;
    else m_gridActive = 2;
}

QSize PixelWidget::sizeHint() const
{
    if (m_surface.isNull())
        return m_initialSize;

    QSize sz(m_surface.width() * zoomValue(),
             m_surface.height() * zoomValue());
    return sz;
}

void PixelWidget::startGridSizeVisibleTimer()
{
    if (m_gridActive) {
        if (m_displayGridSizeId > 0)
            killTimer(m_displayGridSizeId);
        m_displayGridSizeId = startTimer(5000);
        m_displayGridSize = true;
        update();
    }
}

void PixelWidget::setZoom(int zoom)
{
    if (zoom > 0 && zoom != m_zoom) {
        QPoint pos = m_lastMousePos;
        m_lastMousePos = QPoint();
        m_zoom = zoom;
        m_lastMousePos = pos;
        m_dragStart = m_dragCurrent = QPoint();

        if (m_zoom == 1)
            m_gridActive = 0;
        else if (!m_gridActive)
            m_gridActive = 1;

        zoomChanged(m_zoom);
        updateGeometry();
        update();
    }
}

void PixelWidget::toggleGrid()
{
    if (++m_gridActive > 2)
        m_gridActive = 0;
    update();
}

void PixelWidget::setGridSize(int gridSize)
{
    if (m_gridActive && gridSize > 0) {
        m_gridSize = gridSize;
        startGridSizeVisibleTimer();
        update();
    }
}

void PixelWidget::copyToClipboard()
{
    QClipboard *cb = QApplication::clipboard();
    cb->setImage(m_surface);
}

void PixelWidget::saveToFile()
{
    QString name = QFileDialog::getSaveFileName(this, QLatin1String("Save as image"), QString(), QLatin1String("*.png"));
    if (!name.isEmpty()) {
        if (!name.endsWith(QLatin1String(".png")))
            name.append(QLatin1String(".png"));
        m_surface.save(name, "PNG");
    }
}

QColor PixelWidget::colorAtCurrentPosition() const
{
    return m_currentColor;
}

#include "pixelwidget.moc"