summary refs log tree commit diff
path: root/src/BlurhashProvider.h
blob: bbe28c2cf21aa284a83224b48b9843875e2d4d4e (plain) (blame)
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
// SPDX-FileCopyrightText: 2021 Nheko Contributors
// SPDX-FileCopyrightText: 2022 Nheko Contributors
//
// SPDX-License-Identifier: GPL-3.0-or-later

#pragma once

#include <QQuickAsyncImageProvider>
#include <QQuickImageResponse>

#include <QImage>
#include <QThreadPool>

class BlurhashRunnable
  : public QObject
  , public QRunnable
{
    Q_OBJECT
public:
    BlurhashRunnable(const QString &id, const QSize &requestedSize)
      : m_id(id)
      , m_requestedSize(requestedSize)
    {}

    void run() override;
signals:
    void done(QImage);
    void error(QString);

private:
    QString m_id;
    QSize m_requestedSize;
};

class BlurhashResponse : public QQuickImageResponse
{
public:
    BlurhashResponse(const QString &id, const QSize &requestedSize)
    {
        auto runnable = new BlurhashRunnable(id, requestedSize);
        connect(runnable, &BlurhashRunnable::done, this, &BlurhashResponse::handleDone);
        connect(runnable, &BlurhashRunnable::error, this, &BlurhashResponse::handleError);
        QThreadPool::globalInstance()->start(runnable);
    }

    QQuickTextureFactory *textureFactory() const override
    {
        return QQuickTextureFactory::textureFactoryForImage(m_image);
    }
    QString errorString() const override { return m_error; }

    void handleDone(QImage image)
    {
        m_image = std::move(image);
        emit finished();
    }
    void handleError(QString error)
    {
        m_error = error;
        emit finished();
    }

    QString m_error;
    QImage m_image;
};

class BlurhashProvider
  :
#if QT_VERSION < 0x60000
  public QObject
  ,
#endif
  public QQuickAsyncImageProvider
{
    Q_OBJECT
public slots:
    QQuickImageResponse *
    requestImageResponse(const QString &id, const QSize &requestedSize) override
    {
        return new BlurhashResponse(id, requestedSize);
    }
};