summaryrefslogtreecommitdiff
path: root/plugin/src/Caelestia/cutils.cpp
blob: 0e0ded5ef0805c5861d128304288a11d7039f12d (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
#include "cutils.hpp"

#include <QtQuick/qquickitemgrabresult.h>
#include <QtQuick/qquickwindow.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qqmlengine.h>
#include <qthreadpool.h>

namespace caelestia {

void CUtils::saveItem(QQuickItem* target, const QUrl& path) {
    this->saveItem(target, path, QRect(), QJSValue(), QJSValue());
}

void CUtils::saveItem(QQuickItem* target, const QUrl& path, const QRect& rect) {
    this->saveItem(target, path, rect, QJSValue(), QJSValue());
}

void CUtils::saveItem(QQuickItem* target, const QUrl& path, QJSValue onSaved) {
    this->saveItem(target, path, QRect(), onSaved, QJSValue());
}

void CUtils::saveItem(QQuickItem* target, const QUrl& path, QJSValue onSaved, QJSValue onFailed) {
    this->saveItem(target, path, QRect(), onSaved, onFailed);
}

void CUtils::saveItem(QQuickItem* target, const QUrl& path, const QRect& rect, QJSValue onSaved) {
    this->saveItem(target, path, rect, onSaved, QJSValue());
}

void CUtils::saveItem(QQuickItem* target, const QUrl& path, const QRect& rect, QJSValue onSaved, QJSValue onFailed) {
    if (!target) {
        qWarning() << "CUtils::saveItem: a target is required";
        return;
    }

    if (!path.isLocalFile()) {
        qWarning() << "CUtils::saveItem:" << path << "is not a local file";
        return;
    }

    if (!target->window()) {
        qWarning() << "CUtils::saveItem: unable to save target" << target << "without a window";
        return;
    }

    auto scaledRect = rect;
    const qreal scale = target->window()->devicePixelRatio();
    if (rect.isValid() && scale != 1.0) {
        scaledRect =
            QRectF(rect.left() * scale, rect.top() * scale, rect.width() * scale, rect.height() * scale).toRect();
    }

    const QSharedPointer<const QQuickItemGrabResult> grabResult = target->grabToImage();

    QObject::connect(grabResult.data(), &QQuickItemGrabResult::ready, this,
        [grabResult, scaledRect, path, onSaved, onFailed, this]() {
            QThreadPool::globalInstance()->start([grabResult, scaledRect, path, onSaved, onFailed, this] {
                QImage image = grabResult->image();

                if (scaledRect.isValid()) {
                    image = image.copy(scaledRect);
                }

                const QString file = path.toLocalFile();
                const QString parent = QFileInfo(file).absolutePath();
                const bool success = QDir().mkpath(parent) && image.save(file);

                QMetaObject::invokeMethod(
                    this,
                    [file, success, path, onSaved, onFailed, this]() {
                        if (success) {
                            if (onSaved.isCallable()) {
                                onSaved.call(
                                    { QJSValue(file), qmlEngine(this)->toScriptValue(QVariant::fromValue(path)) });
                            }
                        } else {
                            qWarning() << "CUtils::saveItem: failed to save" << path;
                            if (onFailed.isCallable()) {
                                onFailed.call({ qmlEngine(this)->toScriptValue(QVariant::fromValue(path)) });
                            }
                        }
                    },
                    Qt::QueuedConnection);
            });
        });
}

bool CUtils::copyFile(const QUrl& source, const QUrl& target) const {
    return this->copyFile(source, target, true);
}

bool CUtils::copyFile(const QUrl& source, const QUrl& target, bool overwrite) const {
    if (!source.isLocalFile()) {
        qWarning() << "CUtils::copyFile: source" << source << "is not a local file";
        return false;
    }
    if (!target.isLocalFile()) {
        qWarning() << "CUtils::copyFile: target" << target << "is not a local file";
        return false;
    }

    if (overwrite) {
        QFile::remove(target.toLocalFile());
    }

    return QFile::copy(source.toLocalFile(), target.toLocalFile());
}

void CUtils::getDominantColour(QQuickItem* item, QJSValue callback) {
    this->getDominantColour(item, 128, callback);
}

void CUtils::getDominantColour(QQuickItem* item, int rescaleSize, QJSValue callback) {
    if (!item) {
        qWarning() << "CUtils::getDominantColour: an item is required";
        return;
    }

    if (!item->window()) {
        // Fail silently to avoid warning
        return;
    }

    const QSharedPointer<const QQuickItemGrabResult> grabResult = item->grabToImage();

    QObject::connect(
        grabResult.data(), &QQuickItemGrabResult::ready, this, [grabResult, rescaleSize, callback, this]() {
            const QImage image = grabResult->image();

            QThreadPool::globalInstance()->start([grabResult, image, rescaleSize, callback, this]() {
                const QColor color = this->findDominantColour(image, rescaleSize);

                if (callback.isCallable()) {
                    QMetaObject::invokeMethod(
                        this,
                        [color, callback, this]() {
                            callback.call({ qmlEngine(this)->toScriptValue(QVariant::fromValue(color)) });
                        },
                        Qt::QueuedConnection);
                }
            });
        });
}

void CUtils::getDominantColour(const QString& path, QJSValue callback) {
    this->getDominantColour(path, 128, callback);
}

void CUtils::getDominantColour(const QString& path, int rescaleSize, QJSValue callback) {
    if (path.isEmpty()) {
        qWarning() << "CUtils::getDominantColour: given path is empty";
        return;
    }

    QThreadPool::globalInstance()->start([path, rescaleSize, callback, this]() {
        const QImage image(path);

        if (image.isNull()) {
            qWarning() << "CUtils::getDominantColour: failed to load image" << path;
            return;
        }

        const QColor color = this->findDominantColour(image, rescaleSize);

        if (callback.isCallable()) {
            QMetaObject::invokeMethod(
                this,
                [color, callback, this]() {
                    callback.call({ qmlEngine(this)->toScriptValue(QVariant::fromValue(color)) });
                },
                Qt::QueuedConnection);
        }
    });
}

QColor CUtils::findDominantColour(const QImage& image, int rescaleSize) const {
    if (image.isNull()) {
        qWarning() << "CUtils::findDominantColour: image is null";
        return QColor();
    }

    QImage img = image;

    if (rescaleSize > 0 && (img.width() > rescaleSize || img.height() > rescaleSize)) {
        img = img.scaled(rescaleSize, rescaleSize, Qt::KeepAspectRatio, Qt::FastTransformation);
    }

    if (img.format() != QImage::Format_ARGB32) {
        img = img.convertToFormat(QImage::Format_ARGB32);
    }

    std::unordered_map<uint32_t, int> colours;
    const uchar* data = img.bits();
    const int width = img.width();
    const int height = img.height();
    const qsizetype bytesPerLine = img.bytesPerLine();

    for (int y = 0; y < height; ++y) {
        const uchar* line = data + y * bytesPerLine;
        for (int x = 0; x < width; ++x) {
            const uchar* pixel = line + x * 4;

            if (pixel[3] == 0) {
                continue;
            }

            uint32_t r = static_cast<uint32_t>(pixel[0] & 0xF8);
            uint32_t g = static_cast<uint32_t>(pixel[1] & 0xF8);
            uint32_t b = static_cast<uint32_t>(pixel[2] & 0xF8);

            uint32_t colour = (r << 16) | (g << 8) | b;
            ++colours[colour];
        }
    }

    uint32_t dominantColour = 0;
    int maxCount = 0;
    for (const auto& [colour, count] : colours) {
        if (count > maxCount) {
            dominantColour = colour;
            maxCount = count;
        }
    }

    return QColor((0xFFu << 24) | dominantColour);
}

void CUtils::getAverageLuminance(QQuickItem* item, QJSValue callback) {
    this->getAverageLuminance(item, 128, callback);
}

void CUtils::getAverageLuminance(QQuickItem* item, int rescaleSize, QJSValue callback) {
    if (!item) {
        qWarning() << "CUtils::getAverageLuminance: an item is required";
        return;
    }

    if (!item->window()) {
        // Fail silently to avoid warning
        return;
    }

    const QSharedPointer<const QQuickItemGrabResult> grabResult = item->grabToImage();

    QObject::connect(
        grabResult.data(), &QQuickItemGrabResult::ready, this, [grabResult, rescaleSize, callback, this]() {
            const QImage image = grabResult->image();

            QThreadPool::globalInstance()->start([grabResult, image, rescaleSize, callback, this]() {
                const qreal luminance = this->findAverageLuminance(image, rescaleSize);

                if (callback.isCallable()) {
                    QMetaObject::invokeMethod(
                        this,
                        [luminance, callback]() {
                            callback.call({ QJSValue(luminance) });
                        },
                        Qt::QueuedConnection);
                }
            });
        });
}

void CUtils::getAverageLuminance(const QString& path, QJSValue callback) {
    this->getAverageLuminance(path, 128, callback);
}

void CUtils::getAverageLuminance(const QString& path, int rescaleSize, QJSValue callback) {
    if (path.isEmpty()) {
        qWarning() << "CUtils::getAverageLuminance: given path is empty";
        return;
    }

    QThreadPool::globalInstance()->start([path, rescaleSize, callback, this]() {
        const QImage image(path);

        if (image.isNull()) {
            qWarning() << "CUtils::getAverageLuminance: failed to load image" << path;
            return;
        }

        const qreal luminance = this->findAverageLuminance(image, rescaleSize);

        if (callback.isCallable()) {
            QMetaObject::invokeMethod(
                this,
                [luminance, callback]() {
                    callback.call({ QJSValue(luminance) });
                },
                Qt::QueuedConnection);
        }
    });
}

qreal CUtils::findAverageLuminance(const QImage& image, int rescaleSize) const {
    if (image.isNull()) {
        qWarning() << "CUtils::findAverageLuminance: image is null";
        return 0.0;
    }

    QImage img = image;

    if (rescaleSize > 0 && (img.width() > rescaleSize || img.height() > rescaleSize)) {
        img = img.scaled(rescaleSize, rescaleSize, Qt::KeepAspectRatio, Qt::FastTransformation);
    }

    if (img.format() != QImage::Format_ARGB32) {
        img = img.convertToFormat(QImage::Format_ARGB32);
    }

    const uchar* data = img.bits();
    const int width = img.width();
    const int height = img.height();
    const qsizetype bytesPerLine = img.bytesPerLine();

    qreal totalLuminance = 0.0;
    int count = 0;

    for (int y = 0; y < height; ++y) {
        const uchar* line = data + y * bytesPerLine;
        for (int x = 0; x < width; ++x) {
            const uchar* pixel = line + x * 4;

            if (pixel[3] == 0) {
                continue;
            }

            const qreal r = pixel[0] / 255.0;
            const qreal g = pixel[1] / 255.0;
            const qreal b = pixel[2] / 255.0;

            totalLuminance += std::sqrt(0.299 * r * r + 0.587 * g * g + 0.114 * b * b);
            ++count;
        }
    }

    return count == 0 ? 0.0 : totalLuminance / count;
}

QString CUtils::toLocalFile(const QUrl& url) const {
    if (!url.isLocalFile()) {
        qWarning() << "CUtils::toLocalFile: given url is not a local file" << url;
        return QString();
    }

    return url.toLocalFile();
}

} // namespace caelestia