blob: 6fb2807d22bc85c96c150209bed3f41db05c293d (
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
|
#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;
}
|