Merge branch 'master' into settings_auto_update
[situare] / src / map / mapfetcher.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Jussi Laitinen - jussi.laitinen@ixonos.com
6        Sami Rämö - sami.ramo@ixonos.com
7
8    Situare is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License
10    version 2 as published by the Free Software Foundation.
11
12    Situare is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Situare; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
20    USA.
21 */
22
23 #include <QNetworkAccessManager>
24 #include <QNetworkRequest>
25 #include <QNetworkReply>
26 #include <QUrl>
27 #include <QDebug>
28 #include <QPixmap>
29 #include <QNetworkDiskCache>
30 #include <QDesktopServices>
31
32 #include "mapfetcher.h"
33 #include "mapcommon.h"
34 #include "common.h"
35 #include "network/networkaccessmanager.h"
36
37 const int MAX_PARALLEL_DOWNLOADS = 2; ///< Max simultaneous parallel downloads
38 const int NOT_FOUND = -1; ///< Return value if matching request is not found from the list
39
40 MapFetcher::MapFetcher(NetworkAccessManager *manager, QObject *parent)
41     : QObject(parent)
42     , m_pendingRequestsSize(0)
43     , m_fetchMapImagesTimerRunning(false)
44     , m_manager(manager)
45 {
46     qDebug() << __PRETTY_FUNCTION__;
47
48     QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
49     diskCache->setCacheDirectory(QDesktopServices::storageLocation(
50             QDesktopServices::CacheLocation));
51     m_manager->setCache(diskCache);
52
53     connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(
54             downloadFinished(QNetworkReply*)));
55 }
56
57 QUrl MapFetcher::buildURL(int zoomLevel, QPoint tileNumbers)
58 {
59     qDebug() << __PRETTY_FUNCTION__;
60
61     /**
62     * @brief Map server string for building actual URL
63     *
64     * %1 zoom level
65     * %2 x index
66     * %3 y index
67     *
68     * NOTE: If the URL is changed, then the parseURL method must be changed to match
69     *       the new URL structure
70     *
71     * @var MAP_SERVER_URL
72     */
73     const QString MAP_SERVER_URL = QString("http://tile.openstreetmap.org/mapnik/%1/%2/%3.png");
74
75     return QString(MAP_SERVER_URL)
76             .arg(zoomLevel).arg(tileNumbers.x()).arg(tileNumbers.y());
77 }
78
79 void MapFetcher::checkNextRequestFromCache()
80 {
81     qDebug() << __PRETTY_FUNCTION__;
82
83     int i = newestRequestIndex(false);
84
85     if (i != NOT_FOUND) {
86         QUrl url = m_pendingRequests[i].url;
87         if (!url.isEmpty() && url.isValid()) {
88             if (loadImageFromCache(url)) {
89                 // was found, remove from the list
90                 m_pendingRequests.removeAt(i);
91             }
92             else {
93                 // didn't found from cache so mark cache checked and leave to queue
94                 m_pendingRequests[i].cacheChecked = true;
95
96                 if (m_currentDownloads.size() < MAX_PARALLEL_DOWNLOADS)
97                     startNextDownload();
98             }
99         }
100     }
101
102     // schedule checking of the next request if the list is not empty
103     if (newestRequestIndex(false) != NOT_FOUND)
104         QTimer::singleShot(0, this, SLOT(checkNextRequestFromCache()));
105     else
106         m_fetchMapImagesTimerRunning = false;
107 }
108
109 void MapFetcher::downloadFinished(QNetworkReply *reply)
110 {
111     qDebug() << __PRETTY_FUNCTION__;
112
113     if (m_currentDownloads.contains(reply)) {
114
115         if (reply->error() == QNetworkReply::NoError) {
116             QImage image;
117             QUrl url = reply->url();
118
119             if (!image.load(reply, 0))
120                 image = QImage();
121
122             int zoomLevel;
123             int x;
124             int y;
125             parseURL(url, &zoomLevel, &x, &y);
126
127             emit mapImageReceived(zoomLevel, x, y, QPixmap::fromImage(image));
128         }
129         else {
130             emit error(DOWNLOAD_FAILED);
131         }
132
133         m_currentDownloads.removeAll(reply);
134         reply->deleteLater();
135         startNextDownload();
136     }
137 }
138
139 void MapFetcher::enqueueFetchMapImage(int zoomLevel, int x, int y)
140 {
141     qDebug() << __PRETTY_FUNCTION__;
142
143     QUrl url = buildURL(zoomLevel, QPoint(x, y));
144
145     // check if new request is already in the list and move it to the begin of the list...
146     bool found = false;
147     for (int i = 0; i < m_pendingRequests.size(); i++) {
148         if (m_pendingRequests[i].url == url) {
149             m_pendingRequests.move(i, 0);
150             found = true;
151             break;
152         }
153     }
154     // ...or add new request to the begining of the list
155     if (!found) {
156         MapTileRequest request(url);
157         m_pendingRequests.prepend(request);
158     }
159
160     limitPendingRequestsListSize();
161
162     if (!m_fetchMapImagesTimerRunning) {
163         m_fetchMapImagesTimerRunning = true;
164         QTimer::singleShot(0, this, SLOT(checkNextRequestFromCache()));
165     }
166 }
167
168 void MapFetcher::limitPendingRequestsListSize()
169 {
170     qDebug() << __PRETTY_FUNCTION__;
171
172     while (m_pendingRequests.size() > m_pendingRequestsSize) {
173         m_pendingRequests.removeLast();
174     }
175 }
176
177 bool MapFetcher::loadImageFromCache(const QUrl &url)
178 {
179     qDebug() << __PRETTY_FUNCTION__;
180
181     bool imageFound = false;
182
183     QAbstractNetworkCache *cache = m_manager->cache();
184
185     if (cache) {
186
187         int zoomLevel;
188         int x;
189         int y;
190         parseURL(url, &zoomLevel, &x, &y);
191         int originalZoomLevel = zoomLevel;
192
193         // try to fetch requested and upper level images until found or all levels tried
194         do {
195             QIODevice *cacheImage = cache->data(buildURL(zoomLevel, QPoint(x, y)));
196             if (cacheImage) {
197                 QPixmap pixmap;
198                 if (pixmap.loadFromData(cacheImage->readAll())) {
199                     imageFound = true;
200                     emit mapImageReceived(zoomLevel, x, y, pixmap);
201                 }
202
203                 delete cacheImage;
204             }
205         } while (!imageFound && translateIndexesToUpperLevel(zoomLevel, x, y));
206
207         // check expiration if image was found from requested level
208         if (imageFound && (originalZoomLevel == zoomLevel)) {
209             // check if image is expired
210             QNetworkCacheMetaData metaData = cache->metaData(url);
211             if ((metaData.expirationDate().isValid()) && (url.isValid())) {
212
213                 if (metaData.expirationDate() < QDateTime::currentDateTime()) {
214                     cache->remove(url);
215                     return false;
216                 }
217             }
218         }
219
220         // if image was found, but from upper level, return false
221         if (imageFound && (originalZoomLevel != zoomLevel))
222             return false;
223     }
224
225     return imageFound;
226 }
227
228 bool MapFetcher::translateIndexesToUpperLevel(int &zoomLevel, int &x, int &y)
229 {
230     qDebug() << __PRETTY_FUNCTION__;
231
232     if (zoomLevel > MIN_MAP_ZOOM_LEVEL) {
233         zoomLevel--;
234         x /= 2;
235         y /= 2;
236
237         return true;
238     }
239
240     return false;
241 }
242
243 int MapFetcher::newestRequestIndex(bool cacheChecked)
244 {
245     qDebug() << __PRETTY_FUNCTION__;
246
247     for (int i = 0; i < m_pendingRequests.size(); i++) {
248         if (m_pendingRequests[i].cacheChecked == cacheChecked) {
249             return i;
250         }
251     }
252
253     return NOT_FOUND;
254 }
255
256 void MapFetcher::parseURL(const QUrl &url, int *zoom, int *x, int *y)
257 {
258     qDebug() << __PRETTY_FUNCTION__;
259
260     QString path = url.path();
261     QStringList pathParts = path.split("/", QString::SkipEmptyParts);
262
263     int size = pathParts.size();
264
265     // Example URL: "http://tile.openstreetmap.org/mapnik/14/9354/4263.png"
266     const int MIN_PATH_SPLITTED_PARTS = 4;
267     const int ZOOM_INDEX = size - 3;
268     const int X_INDEX = size - 2;
269     const int Y_INDEX = size - 1;
270     const int FILE_EXTENSION_LENGTH = 4;
271
272     if (size >= MIN_PATH_SPLITTED_PARTS) {
273         *zoom = (pathParts.at(ZOOM_INDEX)).toInt();
274         *x = (pathParts.at(X_INDEX)).toInt();
275         QString yString = pathParts.at(Y_INDEX);
276         yString.chop(FILE_EXTENSION_LENGTH);
277         *y = yString.toInt();
278     }
279 }
280
281 void MapFetcher::setDownloadQueueSize(int size)
282 {
283     qDebug() << __PRETTY_FUNCTION__ << "size:" << size;
284
285     m_pendingRequestsSize = size;
286     limitPendingRequestsListSize();
287 }
288
289 void MapFetcher::startNextDownload()
290 {
291     qDebug() << __PRETTY_FUNCTION__;
292
293     int i = newestRequestIndex(true);
294
295     if (i != NOT_FOUND) {
296         QUrl url = m_pendingRequests.takeAt(i).url;
297
298         QNetworkRequest request(url);
299         request.setRawHeader("User-Agent", "Situare");
300         QNetworkReply *reply = m_manager->get(request);
301
302         m_currentDownloads.append(reply);
303     }
304 }