QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
TileImageSource.cc
Go to the documentation of this file.
1/****************************************************************************
2 *
3 * (c) 2009-2024 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 *
5 * QGroundControl is licensed according to the terms in the file
6 * COPYING.md in the root of the source code directory.
7 *
8 ****************************************************************************/
9
10#include "TileImageSource.h"
11
12#include <QtCore/QFile>
13#include <QtNetwork/QNetworkAccessManager>
14#include <QtNetwork/QNetworkReply>
15
16#include <memory>
17
18#include "MapProvider.h"
19#include "QGCCacheTile.h"
20#include "QGCLoggingCategory.h"
21#include "QGCMapEngine.h"
22#include "QGCMapTasks.h"
23#include "QGCMapUrlEngine.h"
25#include "QGeoTileFetcherQGC.h"
26
27QGC_LOGGING_CATEGORY(GeoMapTileImageSourceLog, "GeoMap.TileImageSource")
28QGC_LOGGING_CATEGORY(GeoMapTileImageSourceVerboseLog, "GeoMap.TileImageSource.Verbose")
29
30namespace {
31
32// Bing serves a placeholder image instead of an HTTP error where it has no
33// imagery; delivering or caching it as a tile would drape it onto patches
34bool isBingEmptyTile(int mapId, const QByteArray& data)
35{
36 static const QByteArray bingNoTileImage = [] {
37 QFile file(QStringLiteral(":/res/BingNoTileBytes.dat"));
38 return file.open(QFile::ReadOnly) ? file.readAll() : QByteArray();
39 }();
40
41 if (bingNoTileImage.isEmpty() || (data != bingNoTileImage)) {
42 return false;
43 }
45 return provider && provider->isBingProvider();
46}
47
48} // namespace
49
50TileImageSource::TileImageSource(const QString& mapType, QObject* parent, QNetworkAccessManager* networkManager)
51 : QObject(parent),
52 _mapType(mapType),
53 _mapId(UrlFactory::getQtMapIdFromProviderType(mapType)),
54 _networkManager(networkManager ? networkManager : new QNetworkAccessManager(this))
55{
56 // Only a QtLocation map initializes the shared tile cache on its own
58
59 if (_mapId < 0) {
60 qCWarning(GeoMapTileImageSourceLog) << "unknown map type" << _mapType << "- all tile requests will fail";
61 }
62}
63
65{
66 const int requestId = ++_requestIdCounter;
67 _pending.insert(requestId);
68
69 if (_mapId < 0) {
70 _failAsync(requestId); // unknown provider: don't spam the cache/URL factory per request
71 return requestId;
72 }
73 qCDebug(GeoMapTileImageSourceVerboseLog) << "requestTileImage: key" << key << "requestId" << requestId;
74
75 QGCFetchTileTask* const task = QGeoFileTileCacheQGC::createFetchTileTask(_mapType, key.x, key.y, key.zoom);
76 connect(task, &QGCFetchTileTask::tileFetched, this, [this, requestId, key](QGCCacheTile* tile) {
77 const std::unique_ptr<QGCCacheTile> guard(tile); // caller-owned per task contract
78 if (!_pending.contains(requestId)) {
79 return; // cancelled while the lookup was in flight
80 }
81 if (!tile || tile->img.isEmpty()) {
82 qCDebug(GeoMapTileImageSourceLog) << "tile" << key << "cache returned empty tile, fetching from network";
83 _fetchFromNetwork(requestId, key);
84 return;
85 }
86 _deliver(requestId, key, tile->img);
87 });
88 connect(task, &QGCMapTask::error, this, [this, requestId, key](QGCMapTask::TaskType, const QString&) {
89 if (!_pending.contains(requestId)) {
90 return;
91 }
92 qCDebug(GeoMapTileImageSourceVerboseLog) << "tile" << key << "not cached, fetching from network";
93 _fetchFromNetwork(requestId, key);
94 });
95
96 if (!getQGCMapEngine()->addTask(task)) {
97 qCDebug(GeoMapTileImageSourceLog) << "could not queue cache lookup for" << key;
98 task->deleteLater(); // never enqueued: the worker will not clean it up
99 _failAsync(requestId);
100 }
101 return requestId;
102}
103
104void TileImageSource::_failAsync(int requestId)
105{
106 // Deliver asynchronously so callers see one consistent flow
107 QMetaObject::invokeMethod(
108 this,
109 [this, requestId] {
110 if (_pending.contains(requestId)) {
111 _finishFailed(requestId);
112 }
113 },
114 Qt::QueuedConnection);
115}
116
118{
119 if (!_pending.remove(requestId)) {
120 return;
121 }
122 QNetworkReply* const reply = _activeReplies.take(requestId);
123 if (reply) {
124 reply->abort(); // finished handler is a no-op once the id is not pending
125 }
126}
127
128void TileImageSource::_fetchFromNetwork(int requestId, const TileMath::TileKey& key)
129{
130 const QNetworkRequest request = QGeoTileFetcherQGC::getNetworkRequest(_mapId, key.x, key.y, key.zoom);
131 QNetworkReply* const reply = _networkManager->get(request);
132 _activeReplies.insert(requestId, reply);
133
134 connect(reply, &QNetworkReply::finished, this, [this, requestId, key, reply] {
135 reply->deleteLater();
136 _activeReplies.remove(requestId);
137 if (!_pending.contains(requestId)) {
138 return; // cancelled (abort also lands here)
139 }
140 if (reply->error() != QNetworkReply::NoError) {
141 _warnFailure(key, QStringLiteral("network error: %1 (http %2)")
142 .arg(reply->errorString())
143 .arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()));
144 _finishFailed(requestId);
145 return;
146 }
147 const QByteArray data = reply->readAll();
148 if (data.isEmpty() || isBingEmptyTile(_mapId, data)) {
149 _warnFailure(key, data.isEmpty() ? QStringLiteral("network fetch returned empty body")
150 : QStringLiteral("network fetch returned Bing no-tile placeholder"));
151 _finishFailed(requestId);
152 return;
153 }
154 QImage image;
155 if (!image.loadFromData(data)) {
156 _warnFailure(key, QStringLiteral("network body failed to decode, %1 bytes").arg(data.size()));
157 _finishFailed(requestId); // never cache undecodable bodies (e.g. HTTP-200 error pages)
158 return;
159 }
160 // Store back so the shared cache serves this tile from now on
161 qCDebug(GeoMapTileImageSourceVerboseLog) << "tile" << key << "fetched from network, caching";
162 QGeoFileTileCacheQGC::cacheTile(_mapType, key.x, key.y, key.zoom, data,
163 UrlFactory::getImageFormat(_mapType, data));
164 _finishSucceeded(requestId, image);
165 });
166}
167
168void TileImageSource::_deliver(int requestId, const TileMath::TileKey& key, const QByteArray& data)
169{
170 QImage image;
171 if (isBingEmptyTile(_mapId, data) || !image.loadFromData(data)) {
172 // An unusable cached body (placeholder or corrupt) is a miss, not a
173 // failure: failing here would re-read the same bytes on every paced
174 // retry, blocking the network fallback until cache eviction
175 qCDebug(GeoMapTileImageSourceLog) << "tile" << key << "cached entry unusable, fetching from network";
176 _fetchFromNetwork(requestId, key);
177 return;
178 }
179 qCDebug(GeoMapTileImageSourceVerboseLog) << "tile" << key << "served from cache";
180 _finishSucceeded(requestId, image);
181}
182
183void TileImageSource::_finishSucceeded(int requestId, const QImage& image)
184{
185 _pending.remove(requestId);
186 emit tileImageReady(requestId, image);
187}
188
189void TileImageSource::_finishFailed(int requestId)
190{
191 _pending.remove(requestId);
192 emit tileImageFailed(requestId);
193}
194
195void TileImageSource::_warnFailure(const TileMath::TileKey& key, const QString& reason)
196{
197 // Fetch failures must be visible without logging configuration (matches
198 // the map tile / terrain query convention), but repeats are throttled so
199 // an outage doesn't flood the log
200 if (!_failureWarnTimer.isValid() || (_failureWarnTimer.elapsed() >= kFailureWarnIntervalMs)) {
201 _failureWarnTimer.restart();
202 qCWarning(GeoMapTileImageSourceLog) << "tile" << key << "failed:" << reason;
203 } else {
204 qCDebug(GeoMapTileImageSourceLog) << "tile" << key << "failed:" << reason << "(warning suppressed)";
205 }
206}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QGCMapEngine * getQGCMapEngine()
std::shared_ptr< const MapProvider > SharedMapProvider
void tileFetched(QGCCacheTile *tile)
void ensureInitialized()
void error(QGCMapTask::TaskType type, const QString &errorString)
static QGCFetchTileTask * createFetchTileTask(const QString &type, int x, int y, int z)
static void cacheTile(const QString &type, int x, int y, int z, const QByteArray &image, const QString &format, qulonglong set=UINT64_MAX)
static QNetworkRequest getNetworkRequest(int mapId, int x, int y, int zoom)
void tileImageFailed(int requestId)
void cancelRequest(int requestId)
Cancel a pending request, aborting any in-flight network fetch.
int requestTileImage(const TileMath::TileKey &key)
Request the image for a tile. Returns a request id (> 0).
TileImageSource(const QString &mapType, QObject *parent=nullptr, QNetworkAccessManager *networkManager=nullptr)
void tileImageReady(int requestId, const QImage &image)
QString mapType() const
static QString getImageFormat(QStringView type, QByteArrayView image)
static std::shared_ptr< const MapProvider > getMapProviderFromQtMapId(int qtMapId)
QByteArray img