This repository was archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebImageView.cpp
213 lines (188 loc) · 5.82 KB
/
WebImageView.cpp
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
/*
* This file is forked from https://github.com/RodgerLeblanc/WebImageView , the original repo is too big so I created
* this tiny repo to save mine.
* Please keep this comment paragraph.
*
* Merrick Zhang ( [email protected] ) 2015.5.27
*/
#include "WebImageView.h"
#include <QNetworkReply>
#include <bb/cascades/Image>
#include <QCryptographicHash>
#include <QFile>
#include <QDir>
#include <QFileInfo>
using namespace bb::cascades;
QNetworkAccessManager * WebImageView::mNetManager = new QNetworkAccessManager();
QNetworkDiskCache * WebImageView::mNetworkDiskCache = new QNetworkDiskCache();
WebImageView::WebImageView()
{
/*
* Creates a folder, could be used when you want to get an absolute path of the image.
* @author Merrick Zhang
*/
QFileInfo imageDir(QDir::homePath() + "/images/");
if (!imageDir.exists()) {
QDir().mkdir(imageDir.path());
}
/*
* This is used to fix the ListView Control ReUse problem, sometimes if you flip fingers fast,
* this control will show mistaken images.
*/
//connect(this,SIGNAL(creationCompleted()),this,SLOT(resetControl()));
/*
* Initialize network cache
* use QNetworksDiskCache to automatically cache images.
*/
mNetworkDiskCache->setCacheDirectory(QDir::homePath() + "/cache/");
mNetworkDiskCache->setMaximumCacheSize(100 * 1024 * 1024);
// Set cache in manager
mNetManager->setCache(mNetworkDiskCache);
// Set defaults
mLoading = 0;
}
const QUrl& WebImageView::url() const
{
return mUrl;
}
void WebImageView::setUrl(QUrl url)
{
/*
* bypass null url values.
*/
if (url.scheme() == "") {
return;
}
/*
* deal with "asset://" and relative image path
*/
if (url.scheme() != "http") {
resetImage();
setImageSource(url);
return;
}
mUrl = url;
mLoading = 0;
// Reset the image
resetImage();
// Create request
QNetworkRequest request;
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
request.setUrl(url);
// Create reply
QNetworkReply * reply = mNetManager->get(request);
// QTimer().singleShot(15000,this,SLOT(cancelDownload(reply)));
// Connect to signals
QObject::connect(reply, SIGNAL(finished()), this, SLOT(imageLoaded()));
QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this,
SLOT(dowloadProgressed(qint64,qint64)));
QObject::connect(this, SIGNAL(cancel()), reply, SLOT(deleteLater()));
emit urlChanged();
}
/*
* I'm using md5(url) to generate a unique filename.
*/
QString WebImageView::md5(const QString key)
{
QString md5;
QByteArray ba, bb;
QCryptographicHash md(QCryptographicHash::Md5);
ba.append(key);
md.addData(ba);
bb = md.result();
md5.append(bb.toHex());
return md5;
}
double WebImageView::loading() const
{
return mLoading;
}
void WebImageView::imageLoaded()
{
// Get reply
QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());
QVariant fromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute);
// qDebug() << "page from cache?" << fromCache.toBool();
if (reply->error() == QNetworkReply::NoError) {
if (isARedirectedUrl(reply)) {
setURLToRedirectedUrl(reply);
return;
} else {
imageData = reply->readAll();
/*
* since blackberry cascades's Image class doesn't provide any abilities to
* extract data from it, I'd like to keep imageData in Memory for future use.
* this is why I use global variant instead of local one.
*/
setImage(Image(imageData));
}
}
emit loadComplete();
// Memory management
reply->deleteLater();
}
bool WebImageView::isARedirectedUrl(QNetworkReply *reply)
{
QUrl redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
return !redirection.isEmpty();
}
void WebImageView::setURLToRedirectedUrl(QNetworkReply *reply)
{
QUrl redirectionUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
QUrl baseUrl = reply->url();
QUrl resolvedUrl = baseUrl.resolved(redirectionUrl);
setUrl(resolvedUrl.toString());
}
void WebImageView::clearCache()
{
/*
* This is a INVOCABLE function so you can call it from QML.
*/
mNetworkDiskCache->clear();
QDir imageDir(QDir::homePath() + "/images");
imageDir.setFilter(QDir::NoDotAndDotDot | QDir::Files);
foreach(const QString& file, imageDir.entryList()){
imageDir.remove(file);
}
}
QString WebImageView::getCachedPath()
{
/*
* This function will save the image to /images/ folder and return its path.
* very useful for invoking system picture viewer.
*/
if (imageData.isEmpty()) {
qDebug() << "imageData is empty.";
return "";
} else {
QString str_url = mUrl.toString();
QString fileName = md5(str_url);
int extdot = str_url.lastIndexOf(".");
QString ext = str_url.mid(extdot, str_url.length());
QString filepath = QDir::homePath() + "/images/" + fileName + ext; //in my app this can only be jpg. you'd change it from mUrl.
QFile imageFile(filepath);
if (imageFile.open(QIODevice::WriteOnly)) {
imageFile.write(imageData);
imageFile.close();
return "file://" + filepath;
} else {
qDebug() << "Can't open file to write.";
return "";
}
}
}
void WebImageView::dowloadProgressed(qint64 bytes, qint64 total)
{
mLoading = double(bytes) / double(total);
emit loadingChanged();
}
void WebImageView::resetControl()
{
emit cancel();
// reset everything to default.
resetImage();
resetImageSource();
mUrl = NULL;
mLoading = 0;
imageData.clear();
}