9d3cc9d6922da87ed305116fcf36561b4dda49b3
[situare] / src / map / mapfetcher.cpp
1 #include <QNetworkAccessManager>
2 #include <QNetworkRequest>
3 #include <QNetworkReply>
4 #include <QUrl>
5 #include <QDebug>
6 #include <QPixmap>
7 #include <QNetworkDiskCache>
8 #include <QDesktopServices>
9
10 #include "mapfetcher.h"
11
12 static int MAX_PARALLEL_DOWNLOADS = 2;
13
14 MapFetcher::MapFetcher(QObject *parent)
15     : QObject(parent)
16 {
17     QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
18     diskCache->setCacheDirectory(QDesktopServices::storageLocation(
19             QDesktopServices::CacheLocation));
20     m_manager.setCache(diskCache);
21
22     connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
23 }
24
25 void MapFetcher::fetchMapImage(const QUrl &url)
26 {
27     qDebug() << "fetchMapImage()";
28     if (url.isEmpty())
29         return;
30
31     //Limit parallel downloads
32     if (downloadQueue.length() < MAX_PARALLEL_DOWNLOADS)
33         QTimer::singleShot(0, this, SLOT(startNextDownload()));
34
35     downloadQueue.enqueue(url);
36 }
37
38 void MapFetcher::startNextDownload()
39 {
40     qDebug() << "startNextDownload()";
41     if (downloadQueue.isEmpty())
42         return;
43
44     QUrl url = downloadQueue.dequeue();
45     QNetworkRequest request(url);
46     request.setRawHeader("User-Agent", "Map Test");
47     request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
48                                               QNetworkRequest::PreferCache);
49
50     QNetworkReply *reply = m_manager.get(request);
51
52     currentDownloads.append(reply);
53 }
54
55 void MapFetcher::downloadFinished(QNetworkReply *reply)
56 {
57     qDebug() << "downloadFinished()";
58     if (reply->error()) {
59         emit error(reply->errorString());
60     }
61     else {
62         QImage image;
63         QUrl url = reply->url();
64         if (!image.load(reply, 0))
65             image = QImage();
66
67         emit mapImageReceived(url, QPixmap::fromImage(image));
68     }
69
70     currentDownloads.removeAll(reply);
71     reply->deleteLater();
72     startNextDownload();
73 }
74
75 MapFetcher::~MapFetcher()
76 {
77
78 }