2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
5 Jussi Laitinen - jussi.laitinen@ixonos.com
7 Situare is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License
9 version 2 as published by the Free Software Foundation.
11 Situare is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Situare; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22 #include <QNetworkAccessManager>
23 #include <QNetworkRequest>
24 #include <QNetworkReply>
28 #include <QNetworkDiskCache>
29 #include <QDesktopServices>
31 #include "mapfetcher.h"
33 static int MAX_PARALLEL_DOWNLOADS = 2;
34 static int DOWNLOAD_QUEUE_SIZE = 50;
36 MapFetcher::MapFetcher(QNetworkAccessManager *manager, QObject *parent)
37 : QObject(parent), m_manager(manager)
39 QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
40 diskCache->setCacheDirectory(QDesktopServices::storageLocation(
41 QDesktopServices::CacheLocation));
42 m_manager->setCache(diskCache);
44 connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(
45 downloadFinished(QNetworkReply*)));
48 void MapFetcher::fetchMapImage(const QUrl &url)
50 //qDebug() << __PRETTY_FUNCTION__;
52 if (url.isEmpty() || !url.isValid())
55 if (loadImageFromCache(url))
58 if (m_downloadQueue.size() >= DOWNLOAD_QUEUE_SIZE)
59 m_downloadQueue.dequeue();
61 m_downloadQueue.enqueue(url);
63 if (m_currentDownloads.size() < MAX_PARALLEL_DOWNLOADS)
67 bool MapFetcher::loadImageFromCache(const QUrl &url)
69 //qDebug() << __PRETTY_FUNCTION__;
71 bool imageFound = false;
73 if (m_manager->cache()) {
74 QIODevice *cacheImage = m_manager->cache()->data(url);
79 if (image.load(cacheImage, 0)) {
81 emit mapImageReceived(url, QPixmap::fromImage(image));
91 void MapFetcher::startNextDownload()
93 //qDebug() << __PRETTY_FUNCTION__;
95 if (m_downloadQueue.isEmpty())
98 QUrl url = m_downloadQueue.dequeue();
100 QNetworkRequest request(url);
101 request.setRawHeader("User-Agent", "Map Test");
102 QNetworkReply *reply = m_manager->get(request);
104 m_currentDownloads.append(reply);
107 void MapFetcher::downloadFinished(QNetworkReply *reply)
109 //qDebug() << __PRETTY_FUNCTION__;
111 if (reply->error() == QNetworkReply::NoError) {
113 QUrl url = reply->url();
115 if (!image.load(reply, 0)) {
116 qDebug() << "Could not load image";
120 emit mapImageReceived(url, QPixmap::fromImage(image));
123 emit error(reply->errorString());
126 m_currentDownloads.removeAll(reply);
127 reply->deleteLater();
131 MapFetcher::~MapFetcher()