Debian Codegraph @

src/QMapControl/browserimagemanager.cpp

raw symbols SCIP
1 /***************************************************************************
2 * Copyright (C) 2008 by Chris Browet *
3 * [email protected] *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
20 #include "browserimagemanager.h"
21 #include "MerkaartorPreferences.h"
22
23 #include <QApplication>
24 #include <QDateTime>
25 #include <QPixmapCache>
26 #include <QPainter>
27 #include <QMessageBox>
28 #include <QCryptographicHash>
29 #include <QTimer>
30 #include <QMutex>
31 #include <QNetworkProxy>
32 #include <QNetworkAccessManager>
33
34 #include "IMapAdapter.h"
35
36 #define MAX_REQ 1
37 #define BROWSER_TILE_SIZE 512
38 #define str(x) # x
39
40 void BrowserWebPage::javaScriptConsoleMessage ( const QString & message, int lineNumber, const QString & sourceID )
41 {
42 Q_UNUSED(message)
43 Q_UNUSED(lineNumber)
44 Q_UNUSED(sourceID)
45 // FIXME Seems to crash at times (see http://trac.openstreetmap.org/ticket/1194)
46 //QString s = QString("%1 at %2, %3").arg(message).arg(QString::number(lineNumber)).arg(sourceID);
47 //printf("%s\n", s);
48 }
49
50 void BrowserWebPage::javaScriptAlert ( const QString & msg )
51 {
52 //QMessageBox::information(NULL, tr("Javascript alert"), msg);
53
54 if (msg.startsWith("Coord")) {
55
56 tllat = 90.0;
57 tllon = -180.0;
58 brlat = -90.0;
59 brlon = 180.0;
60
61 QStringList tokens = msg.split(" ");
62 Q_ASSERT(tokens.size() == 5);
63
64 tllat = tokens[1].toDouble();
65 tllon = tokens[2].toDouble();
66 brlat = tokens[3].toDouble();
67 brlon = tokens[4].toDouble();
68
69 qDebug() << "Coord:" << tllat << "," << tllon << "," << brlat << "," << brlon;
70 } else
71 if (msg.startsWith("Size")) {
72
73 sw = BROWSER_TILE_SIZE;
74 sh = BROWSER_TILE_SIZE;
75
76 QStringList tokens = msg.split(" ");
77 Q_ASSERT(tokens.size() == 5);
78
79 int ox, oy, x1, y1;
80 ox = int(tokens[1].toDouble());
81 oy = int(tokens[2].toDouble());
82 x1 = int(tokens[3].toDouble());
83 y1 = int(tokens[4].toDouble());
84
85 qDebug() << "Size:" << ox << "," << oy << "," << x1 << "," << y1;
86
87 sw = x1 - ox;
88 sh = y1 - oy;
89
90 qDebug() << "----" << sw << "," << sh;
91
92 }
93 if (msg.startsWith("ReqSize")) {
94 QStringList tokens = msg.split(" ");
95 Q_ASSERT(tokens.size() == 3);
96
97 int w, h;
98 w = int(tokens[1].toDouble());
99 h = int(tokens[2].toDouble());
100
101 qDebug() << "ReqSize:" << w << "," << h ;
102 }
103 }
104
105 void BrowserWebPage::launchRequest ( const QUrl & url )
106 {
107 qDebug() << "Warning: you are using BrowserWebPage to render background imagery. "
108 "This code is not tested and may not work as expected. If you experience issues, please let us know.";
109 sw = sh = 0;
110 load(url);
111 }
112
113 BrowserImageManager* BrowserImageManager::m_BrowserImageManagerInstance = 0;
114 QMutex mutex;
115
116 #ifdef BROWSERIMAGEMANAGER_IS_THREADED
117 BrowserImageManager::BrowserImageManager(QObject* parent)
118 :QThread(parent), emptyPixmap(QPixmap(1,1)), requestActive(false), page(0)
119 {
120 emptyPixmap.fill(Qt::transparent);
121
122 if (QPixmapCache::cacheLimit() <= 20000)
123 {
124 QPixmapCache::setCacheLimit(20000); // in kb
125 }
126 }
127 #else
128 BrowserImageManager::BrowserImageManager(QObject* parent)
129 :QObject(parent), emptyPixmap(QPixmap(1,1)), errorPixmap(QPixmap(512,512)), page(0), timeoutTimer(new QTimer(this))
130 {
131 errorPixmap.fill(Qt::gray);
132 QPainter P(&errorPixmap);
133 P.fillRect(0, 0, 511, 511, QBrush(Qt::red, Qt::DiagCrossPattern));
134 emptyPixmap.fill(Qt::transparent);
135
136 if (QPixmapCache::cacheLimit() <= 20000)
137 {
138 QPixmapCache::setCacheLimit(20000); // in kb
139 }
140
141 page = new BrowserWebPage();
142
143 connect(page, SIGNAL(loadFinished(bool)), this, SLOT(pageLoadFinished(bool)));
144
145 connect(timeoutTimer, SIGNAL(timeout()), this, SLOT(timeout()));
146 timeoutTimer->setInterval(M_PREFS->getNetworkTimeout());
147
148 // QWebView* theVw = new QWebView((QWidget*)parent);
149 // theVw->setPage(page);
150 // theVw->show();
151 }
152 #endif // BROWSERIMAGEMANAGER_IS_THREADED
153
154
155 BrowserImageManager::~BrowserImageManager()
156 {
157 }
158
159 QByteArray BrowserImageManager::getData(IMapAdapter* anAdapter, const QString &url)
160 {
161 QImage pm = getImage(anAdapter, url);
162 QBuffer buf;
163 pm.save(&buf);
164 return buf.buffer();
165 }
166
167 QImage BrowserImageManager::getImage(IMapAdapter* anAdapter, const QString &url)
168 {
169 // QPixmap pm(emptyPixmap);
170 QPixmap pm;
171
172 QString host = anAdapter->getHost();
173 QString strHash = anAdapter->getName() + url;
174 QString hash = QString(strHash.toLatin1().toBase64());
175 if (hash.size() > 255) {
176 QCryptographicHash crypt(QCryptographicHash::Md5);
177 crypt.addData(hash.toLatin1());
178 hash = QString(crypt.result().toHex());
179 }
180
181 // is image in picture cache
182 if (QPixmapCache::find(hash, pm)) {
183 qDebug() << "BrowserImageManager::QPixmapCache hit!";
184 return pm.toImage();
185 }
186
187 // disk cache?
188 if (anAdapter->isTiled() && useDiskCache(hash + ".png")) {
189 if (pm.load(cacheDir.absolutePath() + "/" + hash + ".png")) {
190 QPixmapCache::insert(hash, pm);
191 return pm.toImage();
192 }
193 }
194 if (M_PREFS->getOfflineMode())
195 return pm.toImage();
196
197 LoadingRequest LR(hash, host, url);
198 if (loadingRequests.contains(LR))
199 return pm.toImage();
200
201 loadingRequests.enqueue(LR);
202 emit(dataRequested());
203
204 #ifndef BROWSERIMAGEMANAGER_IS_THREADED
205 if (loadingRequests.size() <= MAX_REQ)
206 launchRequest();
207 #endif
208
209 return pm.toImage();
210 }
211
212 void BrowserImageManager::launchRequest()
213 {
214 if (loadingRequests.isEmpty())
215 return;
216 // LoadingRequest* R = loadingRequests.dequeue();
217 LoadingRequest R = loadingRequests.head();
218 qDebug() << "BrowserImageManager::launchRequest:" << QString(R.host).append(R.url) << "Hash:" << R.hash;
219
220 QUrl u = QUrl( R.url);
221
222 page->launchRequest(u);
223 requestActive = true;
224 #ifndef BROWSERIMAGEMANAGER_IS_THREADED
225 timeoutTimer->start();
226 #endif
227 }
228
229 void BrowserImageManager::pageLoadFinished(bool ok)
230 {
231 mutex.lock();
232
233 timeoutTimer->stop();
234
235 if (loadingRequests.isEmpty()) {
236 mutex.unlock();
237 return;
238 }
239
240 LoadingRequest R = loadingRequests.dequeue();
241 requestActive = false;
242
243 if (ok && page->sw && page->sh) {
244 qDebug() << "BrowserImageManager::pageLoadFinished:" << " Hash:" << R.hash;
245 QPixmap pt(page->sw, page->sh);
246 QPainter P(&pt);
247 page->view()->render(&P, QPoint(), QRegion(0,0,page->sw,page->sh));
248 P.end();
249
250 // if (page->sw != BROWSER_TILE_SIZE || page->sh != BROWSER_TILE_SIZE) {
251 // QPixmap tmpPx = pt.scaled(QSize(BROWSER_TILE_SIZE, BROWSER_TILE_SIZE));
252 // pt = tmpPx;
253 // }
254
255 if (!(pt.isNull())) {
256 QPixmapCache::insert(R.hash, pt);
257 QString strHash = QByteArray::fromBase64(R.hash.toLatin1());
258
259 if (cacheMaxSize && !strHash.startsWith("Yahoo")) {
260 pt.save(cacheDir.absolutePath() + "/" + R.hash + ".png");
261 QFileInfo info(cacheDir.absolutePath() + "/" + R.hash + ".png");
262 cacheInfo.append(info);
263 cacheSize += info.size();
264
265 adaptCache();
266 }
267 }
268
269 QByteArray ba;
270 QHash<QString, QString> headers;
271
272 receivedData(ba, headers, R.hash);
273 } else {
274 loadingRequests.enqueue(R);
275 qDebug() << "BrowserImageManager::pageLoadFinished - Error:" << "Hash:" << R.hash;
276 }
277
278 mutex.unlock();
279
280 if (loadingRequests.isEmpty())
281 loadingQueueEmpty();
282 #ifndef BROWSERIMAGEMANAGER_IS_THREADED
283 else
284 launchRequest();
285 #endif
286 }
287
288 void BrowserImageManager::slotLoadProgress(int p)
289 {
290 if (!(p < 100)) {
291 }
292 }
293
294 //QPixmap BrowserImageManager::prefetchImage(const QString& host, const QString& url)
295 QImage BrowserImageManager::prefetchImage(IMapAdapter* anAdapter, int x, int y, int z)
296 {
297 QString host = anAdapter->getHost();
298 QString url = anAdapter->getQuery(x, y, z);
299 QString strHash = QString("%1;%2;%3;%4;%5").arg(anAdapter->getName()).arg(QString::number(x)).arg(QString::number(y)).arg(QString::number(z)).arg(anAdapter->getTileSizeW());
300 QString hash = QString(strHash.toLatin1().toBase64());
301
302 prefetch.append(hash);
303 return getImage(anAdapter, anAdapter->getQuery(x, y, z));
304 }
305
306 void BrowserImageManager::receivedData(const QByteArray& /* ba */, const QHash<QString, QString>& /* headers */, const QString& hash)
307 {
308 prefetch.removeOne(hash);
309 emit(dataReceived());
310 }
311
312 void BrowserImageManager::loadingQueueEmpty()
313 {
314 emit(loadingFinished());
315 }
316
317 void BrowserImageManager::abortLoading()
318 {
319 //qDebug() << "BrowserImageManager::abortLoading";
320 page->triggerAction(QWebEnginePage::Stop);
321 if (!loadingRequests.isEmpty()) {
322 LoadingRequest R = loadingRequests.dequeue();
323 loadingRequests.clear();
324 loadingRequests.enqueue(R);
325 }
326 loadingQueueEmpty();
327 }
328
329 #ifdef BROWSERIMAGEMANAGER_IS_THREADED
330 void BrowserImageManager::run()
331 {
332 page = new BrowserWebEnginePage();
333 page->setViewportSize(QSize(1024, 1024));
334
335 QTimer theTimer;
336 theTimer.start(100);
337 connect(page, SIGNAL(loadFinished(bool)), this, SLOT(pageLoadFinished(bool)));
338 connect (&theTimer, SIGNAL(timeout()), this, SLOT(checkRequests()), Qt::DirectConnection);
339
340 exec();
341
342 delete page;
343 }
344
345 void BrowserImageManager::checkRequests()
346 {
347 mutex.lock();
348
349 if (!requestActive) {
350 requestDuration = 0;
351 launchRequest();
352 } else {
353 if ((requestDuration++) > 100) {
354 requestDuration = 0;
355 page->triggerAction(QWebEnginePage::Stop);
356 qDebug() << "BrowserImageManager Timeout";
357 }
358 }
359
360 mutex.unlock();
361 }
362 #else
363 void BrowserImageManager::timeout()
364 {
365 qDebug() << "BrowserImageManager::timeout";
366 page->triggerAction(QWebEnginePage::Stop);
367 pageLoadFinished(false);
368 }
369 #endif // BROWSERIMAGEMANAGER_IS_THREADED
370
371 void BrowserImageManager::setCacheDir(const QDir& path)
372 {
373 cacheDir = path;
374 cacheSize = 0;
375 if (!cacheDir.exists()) {
376 cacheDir.mkpath(cacheDir.absolutePath());
377 } else {
378 cacheInfo = cacheDir.entryInfoList(QDir::Files, QDir::Time | QDir::Reversed);
379 for (int i=0; i<cacheInfo.size(); i++) {
380 cacheSize += cacheInfo[i].size();
381 }
382 }
383 }
384
385 QDir BrowserImageManager::getCacheDir()
386 {
387 return cacheDir;
388 }
389
390 void BrowserImageManager::setCacheMaxSize(int max)
391 {
392 cacheMaxSize = max*1024*1024;
393 }