summaryrefslogtreecommitdiffstats
path: root/examples/qtconcurrent/imagescaling/imagescaling.cpp
blob: fca9291e8b7db67f177f38488832fe730a6fde51 (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
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "imagescaling.h"
#include "downloaddialog.h"

#include <QNetworkReply>

#include <qmath.h>

#include <functional>

Images::Images(QWidget *parent) : QWidget(parent), downloadDialog(new DownloadDialog())
{
    setWindowTitle(tr("Image downloading and scaling example"));
    resize(800, 600);

    addUrlsButton = new QPushButton(tr("Add URLs"));
//! [1]
    connect(addUrlsButton, &QPushButton::clicked, this, &Images::process);
//! [1]

    cancelButton = new QPushButton(tr("Cancel"));
    cancelButton->setEnabled(false);
//! [2]
    connect(cancelButton, &QPushButton::clicked, this, &Images::cancel);
//! [2]

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(addUrlsButton);
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addStretch();

    statusBar = new QStatusBar();

    imagesLayout = new QGridLayout();

    mainLayout = new QVBoxLayout();
    mainLayout->addLayout(buttonLayout);
    mainLayout->addLayout(imagesLayout);
    mainLayout->addStretch();
    mainLayout->addWidget(statusBar);
    setLayout(mainLayout);
}

Images::~Images()
{
    cancel();
}

//! [3]
void Images::process()
{
    // Clean previous state
    replies.clear();

    if (downloadDialog->exec() == QDialog::Accepted) {

        const auto urls = downloadDialog->getUrls();
        if (urls.empty())
            return;

        cancelButton->setEnabled(true);

        initLayout(urls.size());

        downloadFuture = download(urls);
        statusBar->showMessage(tr("Downloading..."));
//! [3]

//! [4]
        downloadFuture.then([this](auto) { cancelButton->setEnabled(false); })
                .then(QtFuture::Launch::Async,
                      [this] {
                          QMetaObject::invokeMethod(this,
                                                    [this] { updateStatus(tr("Scaling...")); });
                          return scaled();
                      })
//! [4]
//! [5]
                .then(this, [this](const QList<QImage> &scaled) {
                    showImages(scaled);
                    updateStatus(tr("Finished"));
                })
//! [5]
//! [6]
                .onCanceled([this] { updateStatus(tr("Download has been canceled.")); })
                .onFailed([this](QNetworkReply::NetworkError error) {
                    updateStatus(tr("Download finished with error: %1").arg(error));

                    // Abort all pending requests
                    abortDownload();
                })
                .onFailed([this](const std::exception& ex) {
                    updateStatus(tr(ex.what()));
                });
//! [6]
    }
}

//! [7]
void Images::cancel()
{
    statusBar->showMessage(tr("Canceling..."));

    downloadFuture.cancel();
    abortDownload();
}
//! [7]

//! [8]
QFuture<QByteArray> Images::download(const QList<QUrl> &urls)
//! [8]
{
//! [9]
    QSharedPointer<QPromise<QByteArray>> promise(new QPromise<QByteArray>());
    promise->start();
//! [9]

//! [10]
    for (auto url : urls) {
        QSharedPointer<QNetworkReply> reply(qnam.get(QNetworkRequest(url)));
        replies.push_back(reply);
//! [10]

//! [11]
        QtFuture::connect(reply.get(), &QNetworkReply::finished).then([=] {
            if (promise->isCanceled()) {
                if (!promise->future().isFinished())
                    promise->finish();
                return;
            }

            if (reply->error() != QNetworkReply::NoError) {
                if (!promise->future().isFinished())
                    throw reply->error();
            }
//! [12]
            promise->addResult(reply->readAll());

            // Report finished on the last download
            if (promise->future().resultCount() == urls.size()) {
                promise->finish();
            }
//! [12]
        }).onFailed([=] (QNetworkReply::NetworkError error) {
            promise->setException(std::make_exception_ptr(error));
            promise->finish();
        }).onFailed([=] {
            const auto ex = std::make_exception_ptr(
                        std::runtime_error("Unknown error occurred while downloading."));
            promise->setException(ex);
            promise->finish();
        });
    }
//! [11]

//! [13]
    return promise->future();
}
//! [13]

//! [14]
QList<QImage> Images::scaled() const
{
    QList<QImage> scaled;
    const auto data = downloadFuture.results();
    for (auto imgData : data) {
        QImage image;
        image.loadFromData(imgData);
        if (image.isNull())
            throw std::runtime_error("Failed to load image.");

        scaled.push_back(image.scaled(100, 100, Qt::KeepAspectRatio));
    }

    return scaled;
}
//! [14]

void Images::showImages(const QList<QImage> &images)
{
    for (int i = 0; i < images.size(); ++i) {
        labels[i]->setAlignment(Qt::AlignCenter);
        labels[i]->setPixmap(QPixmap::fromImage(images[i]));
    }
}

void Images::initLayout(qsizetype count)
{
    // Clean old images
    QLayoutItem *child;
    while ((child = imagesLayout->takeAt(0)) != nullptr) {
        child->widget()->setParent(nullptr);
        delete child;
    }
    labels.clear();

    // Init the images layout for the new images
    const auto dim = int(qSqrt(qreal(count))) + 1;
    for (int i = 0; i < dim; ++i) {
        for (int j = 0; j < dim; ++j) {
            QLabel *imageLabel = new QLabel;
            imageLabel->setFixedSize(100, 100);
            imagesLayout->addWidget(imageLabel, i, j);
            labels.append(imageLabel);
        }
    }
}

void Images::updateStatus(const QString &msg)
{
    statusBar->showMessage(msg);
}

void Images::abortDownload()
{
    for (auto reply : replies)
        reply->abort();
}