on 47d4646 help sign in
unity8/plugins/Dash/croppedimagesizerasyncworker.cpp
84 lines 2.7 kB history raw
1/*
2 * Copyright (C) 2014 Canonical, Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
17#include "croppedimagesizerasyncworker.h"
19#include "croppedimagesizer.h"
21#include <QNetworkReply>
22#include <QtConcurrentRun>
24CroppedImageSizerAsyncWorker::CroppedImageSizerAsyncWorker(CroppedImageSizer *sizer, QNetworkReply *reply)
25 : m_sizer(sizer),
26 m_reply(reply),
27 m_ignoreAbort(false)
29 connect(m_reply, &QNetworkReply::finished, this, &CroppedImageSizerAsyncWorker::requestFinished);
32void CroppedImageSizerAsyncWorker::abort()
34 QMutexLocker locker(&m_mutex);
35 m_sizer = nullptr;
36 // If we already started the future run we can't abort the reply
37 // since we don't know at which stage the future is, just let it finish
38 if (!m_ignoreAbort) {
39 m_reply->abort();
40 }
43void CroppedImageSizerAsyncWorker::requestFinished()
45 QMutexLocker locker(&m_mutex);
46 if (m_sizer) {
47 m_ignoreAbort = true;
48 QtConcurrent::run(processRequestFinished, m_sizer->width(), m_sizer->height(), m_sizer->source(), this);
49 } else {
50 // We were aborted delete ourselves
51 m_reply->deleteLater();
52 deleteLater();
53 }
56void CroppedImageSizerAsyncWorker::processRequestFinished(qreal width, qreal height, QUrl source, CroppedImageSizerAsyncWorker *worker)
58 QImageReader reader(worker->m_reply);
59 const QSize imageSize = reader.size();
60 QSize sourceSize = QSize(0, 0);
61 if (imageSize.isValid()) {
62 if (height > 0 && imageSize.height() > 0) {
63 const qreal ar = width / height;
64 const qreal ssar = imageSize.width() / (qreal)imageSize.height();
65 if (ar > ssar) {
66 sourceSize = QSize(width, 0);
67 } else {
68 sourceSize = QSize(0, height);
69 }
70 }
71 } else {
72 qWarning() << "Could not find size of" << source << worker;
73 }
75 worker->m_mutex.lock();
76 if (worker->m_sizer) {
77 worker->m_sizer->setSourceSize(sourceSize);
78 }
79 worker->m_mutex.unlock();
81 // All work is done, delete ourselves
82 worker->m_reply->deleteLater();
83 worker->deleteLater();