aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/components/propertyeditor/colorpalettebackend.cpp
blob: 8d57ca8f15a684e37a8abdc3b8c147ad17273b25 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "colorpalettebackend.h"

#include <QDebug>
#include <QSettings>
#include <QColorDialog>
#include <QTimer>

#include <QApplication>
#include <QScreen>
#include <QPainter>

namespace QmlDesigner {

QPointer<ColorPaletteBackend> ColorPaletteBackend::m_instance = nullptr;

ColorPaletteBackend::ColorPaletteBackend()
    : m_currentPalette()
    , m_data()
    , m_colorPickingEventFilter(nullptr)
#ifdef Q_OS_WIN32
    , updateTimer(0)
#endif
{
    m_data.insert(g_recent, Palette(QmlDesigner::DesignerSettingsKey::COLOR_PALETTE_RECENT));
    m_data.insert(g_favorite, Palette(QmlDesigner::DesignerSettingsKey::COLOR_PALETTE_FAVORITE));

    readPalettes();

    // Set recent color palette by default
    setCurrentPalette(g_recent);

#ifdef Q_OS_WIN32
    dummyTransparentWindow.resize(1, 1);
    dummyTransparentWindow.setFlags(Qt::Tool | Qt::FramelessWindowHint);
    updateTimer = new QTimer(this);
    connect(updateTimer, &QTimer::timeout, this, &ColorPaletteBackend::updateEyeDropper);
#endif
}

ColorPaletteBackend::~ColorPaletteBackend()
{
    //writePalettes(); // TODO crash on QtDS close
}

void ColorPaletteBackend::readPalettes()
{
    QHash<QString, Palette>::iterator i = m_data.begin();
    while (i != m_data.end()) {
        i.value().read();
        ++i;
    }
}

void ColorPaletteBackend::writePalettes()
{
    QHash<QString, Palette>::iterator i = m_data.begin();
    while (i != m_data.end()) {
        i.value().write();
        ++i;
    }
}

void ColorPaletteBackend::addColor(const QString &color, const QString &palette)
{
    if (!m_data.contains(palette)) {
        qWarning() << Q_FUNC_INFO << "Unknown palette: " << palette;
        return;
    }

    // If palette is currently active palette also add it to the local color list
    if (palette == m_currentPalette) {
        if (m_currentPaletteColors.size() + 1 > g_maxPaletteSize)
            m_currentPaletteColors.removeLast();

        m_currentPaletteColors.prepend(color);
        emit currentPaletteColorsChanged();
    }

    if (m_data[palette].m_colors.size() + 1 > g_maxPaletteSize)
        m_data[palette].m_colors.removeLast();

    m_data[palette].m_colors.prepend(color);
    m_data[palette].write();
}

void ColorPaletteBackend::removeColor(int id, const QString &palette)
{
    if (!m_data.contains(palette)) {
        qWarning() << Q_FUNC_INFO << "Unknown palette: " << palette;
        return;
    }

    if (id >= m_data[palette].m_colors.size()) {
        qWarning() << Q_FUNC_INFO << "Id(" << id << ") is out of bounds for palette " << palette;
        return;
    }

    // If palette is currently active palette also add it to the local color list
    if (palette == m_currentPalette) {
        m_currentPaletteColors.removeAt(id);

        // Fill up with empty strings
        while (m_currentPaletteColors.size() < g_maxPaletteSize)
            m_currentPaletteColors.append("");

        emit currentPaletteColorsChanged();
    }

    m_data[palette].m_colors.removeAt(id);
    m_data[palette].write();
}

void ColorPaletteBackend::addRecentColor(const QString &item)
{
    if (m_data[g_recent].m_colors.isEmpty()) {
        addColor(item, g_recent);
        return;
    }

    // Don't add recent color if the first one is the same
    if (m_data[g_recent].m_colors.constFirst() != item)
        addColor(item, g_recent);
}

void ColorPaletteBackend::addFavoriteColor(const QString &item)
{
    addColor(item, g_favorite);
}

void ColorPaletteBackend::removeFavoriteColor(int id)
{
    removeColor(id, g_favorite);
}

QStringList ColorPaletteBackend::palettes() const
{
    return m_data.keys();
}

const QString &ColorPaletteBackend::currentPalette() const
{
    return m_currentPalette;
}

void ColorPaletteBackend::setCurrentPalette(const QString &palette)
{
    if (!m_data.contains(palette)) {
        qWarning() << Q_FUNC_INFO << "Unknown palette: " << palette;
        return;
    }

    if (m_currentPalette == palette)
        return;

    // Store the current palette in settings
    if (!m_currentPalette.isEmpty() && m_currentPalette != palette)
        m_data[m_currentPalette].write();

    m_currentPalette = palette;
    m_currentPaletteColors.clear();

    for (const QString &color : m_data[m_currentPalette].m_colors)
        m_currentPaletteColors.append(color);

    // Prune to max palette size
    while (m_currentPaletteColors.size() > g_maxPaletteSize)
        m_currentPaletteColors.removeLast();

    // Fill up with empty strings
    while (m_currentPaletteColors.size() < g_maxPaletteSize)
        m_currentPaletteColors.append("");

    emit currentPaletteChanged(m_currentPalette);
    emit currentPaletteColorsChanged();
}

const QStringList &ColorPaletteBackend::currentPaletteColors() const
{
    return m_currentPaletteColors;
}

void ColorPaletteBackend::registerDeclarativeType()
{
    [[maybe_unused]] static const int typeIndex = qmlRegisterSingletonType<ColorPaletteBackend>(
        "QtQuickDesignerColorPalette", 1, 0, "ColorPaletteBackend", [](QQmlEngine *, QJSEngine *) {
            return new ColorPaletteBackend();
        });
}

void ColorPaletteBackend::showDialog(QColor color)
{
    auto colorDialog = new QColorDialog(Core::ICore::dialogParent());
    colorDialog->setCurrentColor(color);
    colorDialog->setAttribute(Qt::WA_DeleteOnClose);

    connect(colorDialog, &QDialog::rejected,
            this, &ColorPaletteBackend::colorDialogRejected);
    connect(colorDialog, &QColorDialog::currentColorChanged,
            this, &ColorPaletteBackend::currentColorChanged);

    QTimer::singleShot(0, [colorDialog](){ colorDialog->exec(); });
}

void ColorPaletteBackend::eyeDropper()
{
    QWidget *widget = QApplication::activeWindow();
    if (!widget)
        return;

    if (!m_colorPickingEventFilter)
        m_colorPickingEventFilter = new QColorPickingEventFilter(this);

    widget->installEventFilter(m_colorPickingEventFilter);

#ifndef QT_NO_CURSOR
    widget->grabMouse(/*Qt::CrossCursor*/);
#else
    w->grabMouse();
#endif
#ifdef Q_OS_WIN32 // excludes WinRT
    // On Windows mouse tracking doesn't work over other processes's windows
    updateTimer->start(30);
    // HACK: Because mouse grabbing doesn't work across processes, we have to have a dummy,
    // invisible window to catch the mouse click, otherwise we will click whatever we clicked
    // and loose focus.
    dummyTransparentWindow.show();
#endif
    widget->grabKeyboard();
    /* With setMouseTracking(true) the desired color can be more precisely picked up,
     * and continuously pushing the mouse button is not necessary.
     */
    widget->setMouseTracking(true);
    updateEyeDropperPosition(QCursor::pos());
}

const int g_cursorWidth = 64;
const int g_cursorHeight = 64;
const int g_screenGrabWidth = 7;
const int g_screenGrabHeight = 7;
const int g_pixelX = 3;
const int g_pixelY = 3;

QColor ColorPaletteBackend::grabScreenColor(const QPoint &p)
{
    return grabScreenRect(p).pixel(g_pixelX, g_pixelY);
}

QImage ColorPaletteBackend::grabScreenRect(const QPoint &p)
{
    QScreen *screen = QGuiApplication::screenAt(p);
    if (!screen)
        screen = QGuiApplication::primaryScreen();

    const QPixmap pixmap = screen->grabWindow(0, p.x(), p.y(), g_screenGrabWidth, g_screenGrabHeight);
    return pixmap.toImage();
}

void ColorPaletteBackend::updateEyeDropper()
{
#ifndef QT_NO_CURSOR
    static QPoint lastGlobalPos;
    QPoint newGlobalPos = QCursor::pos();
    if (lastGlobalPos == newGlobalPos)
        return;

    lastGlobalPos = newGlobalPos;

    updateEyeDropperPosition(newGlobalPos);
#ifdef Q_OS_WIN32
    dummyTransparentWindow.setPosition(newGlobalPos);
#endif
#endif // ! QT_NO_CURSOR
}

void ColorPaletteBackend::updateEyeDropperPosition(const QPoint &globalPos)
{
    updateCursor(grabScreenRect(globalPos));
}

void ColorPaletteBackend::updateCursor(const QImage &image)
{
    QWidget *widget = QApplication::activeWindow();
    if (!widget)
        return;

    QPixmap pixmap(QSize(g_cursorWidth, g_cursorHeight));
    QPainter painter(&pixmap);
    // Draw the magnified image/screen grab
    QRect r(QPoint(), pixmap.size());
    painter.drawImage(r, image, QRect(0, 0, g_screenGrabWidth, g_screenGrabHeight));

    const int pixelWidth = (g_cursorWidth - 1) / g_screenGrabWidth;
    const int pixelHeight = (g_cursorHeight - 1) / g_screenGrabHeight;
    // Draw the pixel lines
    painter.setPen(QPen(QColor(192, 192, 192, 150), 1.0, Qt::SolidLine));
    for (int i = 1; i != g_screenGrabWidth; ++i) {
        int x = pixelWidth * i;
        painter.drawLine(x, 0, x, g_cursorHeight);
    }

    for (int i = 1; i != g_screenGrabHeight; ++i) {
        int y = pixelHeight * i;
        painter.drawLine(0, y, g_cursorWidth, y);
    }
    // Draw the sorounding border
    painter.setPen(QPen(Qt::black, 1.0, Qt::SolidLine));
    painter.drawRect(r.adjusted(0, 0, -1, -1));

    const QColor color = image.pixel(g_pixelX, g_pixelY);
    QRect centerRect = QRect(2 * pixelWidth, 2 * pixelHeight, 3 * pixelWidth, 3 * pixelHeight);
    // Draw the center rectangle with the current eye dropper color
    painter.setBrush(QBrush(color, Qt::SolidPattern));
    painter.drawRect(centerRect);

    painter.end();
    QCursor cursor(pixmap);
    widget->setCursor(cursor);
}

void ColorPaletteBackend::releaseEyeDropper()
{
    QWidget *widget = QApplication::activeWindow();
    if (!widget)
        return;

    widget->removeEventFilter(m_colorPickingEventFilter);
    widget->releaseMouse();
#ifdef Q_OS_WIN32
    updateTimer->stop();
    dummyTransparentWindow.setVisible(false);
#endif
    widget->releaseKeyboard();
    widget->setMouseTracking(false);

    widget->unsetCursor();
}

bool ColorPaletteBackend::handleEyeDropperMouseMove(QMouseEvent *e)
{
    updateEyeDropperPosition(e->globalPos());
    return true;
}

bool ColorPaletteBackend::handleEyeDropperMouseButtonRelease(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton)
        emit currentColorChanged(grabScreenColor(e->globalPos()));
    else
        emit eyeDropperRejected();

    releaseEyeDropper();
    return true;
}

bool ColorPaletteBackend::handleEyeDropperKeyPress(QKeyEvent *e)
{
#if QT_CONFIG(shortcut)
    if (e->matches(QKeySequence::Cancel)) {
        emit eyeDropperRejected();
        releaseEyeDropper();
    } //else
#endif
    //if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
    //    emit currentColorChanged(grabScreenColor(e->globalPos()));
    //    releaseEyeDropper();
    //}
    e->accept();
    return true;
}

/// EYE DROPPER


} // namespace QmlDesigner