2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
5 Jussi Laitinen - jussi.laitinen@ixonos.com
6 Sami Rämö - sami.ramo@ixonos.com
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.
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.
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,
23 #include <QNetworkAccessManager>
24 #include <QNetworkRequest>
25 #include <QNetworkReply>
29 #include <QNetworkDiskCache>
30 #include <QDesktopServices>
32 #include "mapfetcher.h"
33 #include "mapcommon.h"
35 #include "network/networkaccessmanager.h"
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
40 MapFetcher::MapFetcher(NetworkAccessManager *manager, QObject *parent)
42 , m_pendingRequestsSize(0)
43 , m_fetchMapImagesTimerRunning(false)
46 qDebug() << __PRETTY_FUNCTION__;
48 QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
49 diskCache->setCacheDirectory(QDesktopServices::storageLocation(
50 QDesktopServices::CacheLocation));
51 m_manager->setCache(diskCache);
53 connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(
54 downloadFinished(QNetworkReply*)));
57 QUrl MapFetcher::buildURL(int zoomLevel, QPoint tileNumbers)
59 qDebug() << __PRETTY_FUNCTION__;
62 * @brief Map server string for building actual URL
68 * NOTE: If the URL is changed, then the parseURL method must be changed to match
69 * the new URL structure
73 const QString MAP_SERVER_URL = QString("http://tile.openstreetmap.org/mapnik/%1/%2/%3.png");
75 return QString(MAP_SERVER_URL)
76 .arg(zoomLevel).arg(tileNumbers.x()).arg(tileNumbers.y());
79 void MapFetcher::checkNextRequestFromCache()
81 qDebug() << __PRETTY_FUNCTION__;
83 int i = newestRequestIndex(false);
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);
93 // didn't found from cache so mark cache checked and leave to queue
94 m_pendingRequests[i].cacheChecked = true;
96 if (m_currentDownloads.size() < MAX_PARALLEL_DOWNLOADS)
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()));
106 m_fetchMapImagesTimerRunning = false;
109 void MapFetcher::downloadFinished(QNetworkReply *reply)
111 qDebug() << __PRETTY_FUNCTION__;
113 if (m_currentDownloads.contains(reply)) {
115 if (reply->error() == QNetworkReply::NoError) {
117 QUrl url = reply->url();
119 if (!image.load(reply, 0))
125 parseURL(url, &zoomLevel, &x, &y);
127 emit mapImageReceived(zoomLevel, x, y, QPixmap::fromImage(image));
130 emit error(DOWNLOAD_FAILED);
133 m_currentDownloads.removeAll(reply);
134 reply->deleteLater();
139 void MapFetcher::enqueueFetchMapImage(int zoomLevel, int x, int y)
141 qDebug() << __PRETTY_FUNCTION__;
143 QUrl url = buildURL(zoomLevel, QPoint(x, y));
145 // check if new request is already in the list and move it to the begin of the list...
147 for (int i = 0; i < m_pendingRequests.size(); i++) {
148 if (m_pendingRequests[i].url == url) {
149 m_pendingRequests.move(i, 0);
154 // ...or add new request to the begining of the list
156 MapTileRequest request(url);
157 m_pendingRequests.prepend(request);
160 limitPendingRequestsListSize();
162 if (!m_fetchMapImagesTimerRunning) {
163 m_fetchMapImagesTimerRunning = true;
164 QTimer::singleShot(0, this, SLOT(checkNextRequestFromCache()));
168 void MapFetcher::limitPendingRequestsListSize()
170 qDebug() << __PRETTY_FUNCTION__;
172 while (m_pendingRequests.size() > m_pendingRequestsSize) {
173 m_pendingRequests.removeLast();
177 bool MapFetcher::loadImageFromCache(const QUrl &url)
179 qDebug() << __PRETTY_FUNCTION__;
181 bool imageFound = false;
183 QAbstractNetworkCache *cache = m_manager->cache();
190 parseURL(url, &zoomLevel, &x, &y);
191 int originalZoomLevel = zoomLevel;
193 // try to fetch requested and upper level images until found or all levels tried
195 QIODevice *cacheImage = cache->data(buildURL(zoomLevel, QPoint(x, y)));
198 if (pixmap.loadFromData(cacheImage->readAll())) {
200 emit mapImageReceived(zoomLevel, x, y, pixmap);
205 } while (!imageFound && translateIndexesToUpperLevel(zoomLevel, x, y));
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())) {
213 if (metaData.expirationDate() < QDateTime::currentDateTime()) {
220 // if image was found, but from upper level, return false
221 if (imageFound && (originalZoomLevel != zoomLevel))
228 bool MapFetcher::translateIndexesToUpperLevel(int &zoomLevel, int &x, int &y)
230 qDebug() << __PRETTY_FUNCTION__;
232 if (zoomLevel > MIN_MAP_ZOOM_LEVEL) {
243 int MapFetcher::newestRequestIndex(bool cacheChecked)
245 qDebug() << __PRETTY_FUNCTION__;
247 for (int i = 0; i < m_pendingRequests.size(); i++) {
248 if (m_pendingRequests[i].cacheChecked == cacheChecked) {
256 void MapFetcher::parseURL(const QUrl &url, int *zoom, int *x, int *y)
258 qDebug() << __PRETTY_FUNCTION__;
260 QString path = url.path();
261 QStringList pathParts = path.split("/", QString::SkipEmptyParts);
263 int size = pathParts.size();
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;
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();
281 void MapFetcher::setDownloadQueueSize(int size)
283 qDebug() << __PRETTY_FUNCTION__ << "size:" << size;
285 m_pendingRequestsSize = size;
286 limitPendingRequestsListSize();
289 void MapFetcher::startNextDownload()
291 qDebug() << __PRETTY_FUNCTION__;
293 int i = newestRequestIndex(true);
295 if (i != NOT_FOUND) {
296 QUrl url = m_pendingRequests.takeAt(i).url;
298 QNetworkRequest request(url);
299 request.setRawHeader("User-Agent", "Situare");
300 QNetworkReply *reply = m_manager->get(request);
302 m_currentDownloads.append(reply);