diff options
Diffstat (limited to 'imageprovider.cpp')
-rw-r--r-- | imageprovider.cpp | 110 |
1 files changed, 110 insertions, 0 deletions
diff --git a/imageprovider.cpp b/imageprovider.cpp new file mode 100644 index 0000000..6fb2807 --- /dev/null +++ b/imageprovider.cpp @@ -0,0 +1,110 @@ +#include <QtCore/QCryptographicHash> +#include <QtCore/QDir> +#include <QtCore/QEventLoop> +#include <QtCore/QUrl> +#include <QtCore/QDebug> +#include <QtNetwork/QNetworkRequest> +#include <QtNetwork/QNetworkReply> + +#include "global.h" +#include "imageprovider.h" + +// Warning: QML might call requestImage() from another thread. Be careful. + +ImageProvider::ImageProvider() : + QDeclarativeImageProvider(Image), + _cachePath(board_manager->getCachePath() + "/images"), + _manager(new QNetworkAccessManager) +{ + QDir dir; + if (!dir.mkpath(_cachePath)) { + qWarning() << "Could not create image cache path"; + } +} + +ImageProvider::~ImageProvider() +{ + delete _manager; +} + +QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) +{ + QString remoteUrl = QUrl::fromPercentEncoding(id.toUtf8()); + QString localPath = getCachedImagePath(remoteUrl); + + qDebug() << "Loading image for " << remoteUrl; + + if (!QFile::exists(localPath)) { + if (!fetchImage(remoteUrl)) { + qWarning() << "Failed to fetch remote image" << remoteUrl; + } + } else { + qDebug() << "Local file exists" << localPath; + } + + QImage image(localPath); + QImage result; + + if (image.isNull()) { + qWarning() << "Failed to load local image" << localPath; + } + + if (requestedSize.isValid()) { + result = image.scaled(requestedSize, Qt::KeepAspectRatio); + } else { + result = image; + } + if (size) { + *size = result.size(); + } + + return result; +} + +QString ImageProvider::getProviderImageUrl(const QString &remoteUrl) +{ + return "image://tapasboard/" + QString::fromUtf8(QUrl::toPercentEncoding(remoteUrl)); +} + +QString ImageProvider::getCachedImagePath(const QString &remoteUrl) +{ + static const QRegExp regexp("[^a-z0-9]+"); + QString url = remoteUrl.toLower(); + + // Grab the extension before applying the regexp + QString extension; + int dot_pos = url.lastIndexOf('.'); + + if (dot_pos != -1) { + extension = url.mid(dot_pos); + } + + url.replace(regexp, "_"); + + return _cachePath + "/" + url + extension; +} + +bool ImageProvider::fetchImage(const QString &remoteUrl) +{ + QString localPath = getCachedImagePath(remoteUrl); + + QNetworkRequest request(remoteUrl); + QNetworkReply *reply = _manager->get(request); + qDebug() << "Start download of" << remoteUrl; + + QEventLoop loop; + loop.connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); + + loop.exec(); + + qDebug() << "End download of" << remoteUrl; + QFile localFile(localPath); + if (localFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + localFile.write(reply->readAll()); + localFile.close(); + } + + reply->deleteLater(); + + return true; +} |