#include #include #include #include #include #include #include #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; }