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

#include <qobject.h>
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickItemGrabResult>
#include <QThreadPool>
#include <QQmlEngine>
#include <QDir>

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

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

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

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

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

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

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

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

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

                if (!rect.isEmpty()) {
                    image = image.copy(rect);
                }

                const QString file = path.toLocalFile();
                const QString parent = QFileInfo(file).absolutePath();
                if (QDir().mkpath(parent) && image.save(file)) {
                    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)) });
                    }
                }
            });
        }
    );
}