QGCMapTileSet.cpp 12 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
dogmaphobic's avatar
dogmaphobic committed
9 10 11 12 13 14


/**
 * @file
 *   @brief Map Tile Set
 *
Gus Grubba's avatar
Gus Grubba committed
15
 *   @author Gus Grubba <gus@auterion.com>
dogmaphobic's avatar
dogmaphobic committed
16 17 18 19 20 21
 *
 */

#include "QGCMapEngine.h"
#include "QGCMapTileSet.h"
#include "QGCMapEngineManager.h"
22
#include "TerrainTile.h"
dogmaphobic's avatar
dogmaphobic committed
23

dogmaphobic's avatar
dogmaphobic committed
24 25 26
#include <QSettings>
#include <math.h>

dogmaphobic's avatar
dogmaphobic committed
27 28 29 30 31
QGC_LOGGING_CATEGORY(QGCCachedTileSetLog, "QGCCachedTileSetLog")

#define TILE_BATCH_SIZE      256

//-----------------------------------------------------------------------------
dogmaphobic's avatar
dogmaphobic committed
32
QGCCachedTileSet::QGCCachedTileSet(const QString& name)
dogmaphobic's avatar
dogmaphobic committed
33 34 35 36 37
    : _name(name)
    , _topleftLat(0.0)
    , _topleftLon(0.0)
    , _bottomRightLat(0.0)
    , _bottomRightLon(0.0)
dogmaphobic's avatar
dogmaphobic committed
38 39 40 41 42 43
    , _totalTileCount(0)
    , _totalTileSize(0)
    , _uniqueTileCount(0)
    , _uniqueTileSize(0)
    , _savedTileCount(0)
    , _savedTileSize(0)
dogmaphobic's avatar
dogmaphobic committed
44 45 46 47 48 49
    , _minZoom(3)
    , _maxZoom(3)
    , _defaultSet(false)
    , _deleting(false)
    , _downloading(false)
    , _id(0)
50
    , _type("Invalid")
51
    , _networkManager(nullptr)
dogmaphobic's avatar
dogmaphobic committed
52 53 54
    , _errorCount(0)
    , _noMoreTiles(false)
    , _batchRequested(false)
55
    , _manager(nullptr)
56
    , _selected(false)
dogmaphobic's avatar
dogmaphobic committed
57 58 59 60 61 62 63
{

}

//-----------------------------------------------------------------------------
QGCCachedTileSet::~QGCCachedTileSet()
{
64 65
    delete _networkManager;
    _networkManager = nullptr;
dogmaphobic's avatar
dogmaphobic committed
66 67 68 69 70 71 72 73 74 75 76
}

//-----------------------------------------------------------------------------
QString
QGCCachedTileSet::errorCountStr()
{
    return QGCMapEngine::numberToString(_errorCount);
}

//-----------------------------------------------------------------------------
QString
dogmaphobic's avatar
dogmaphobic committed
77
QGCCachedTileSet::totalTileCountStr()
dogmaphobic's avatar
dogmaphobic committed
78
{
dogmaphobic's avatar
dogmaphobic committed
79
    return QGCMapEngine::numberToString(_totalTileCount);
dogmaphobic's avatar
dogmaphobic committed
80 81 82 83
}

//-----------------------------------------------------------------------------
QString
dogmaphobic's avatar
dogmaphobic committed
84
QGCCachedTileSet::totalTilesSizeStr()
dogmaphobic's avatar
dogmaphobic committed
85
{
dogmaphobic's avatar
dogmaphobic committed
86
    return QGCMapEngine::bigSizeToString(_totalTileSize);
dogmaphobic's avatar
dogmaphobic committed
87 88 89 90
}

//-----------------------------------------------------------------------------
QString
dogmaphobic's avatar
dogmaphobic committed
91
QGCCachedTileSet::uniqueTileSizeStr()
dogmaphobic's avatar
dogmaphobic committed
92
{
dogmaphobic's avatar
dogmaphobic committed
93
    return QGCMapEngine::bigSizeToString(_uniqueTileSize);
dogmaphobic's avatar
dogmaphobic committed
94 95 96 97
}

//-----------------------------------------------------------------------------
QString
dogmaphobic's avatar
dogmaphobic committed
98
QGCCachedTileSet::uniqueTileCountStr()
dogmaphobic's avatar
dogmaphobic committed
99
{
dogmaphobic's avatar
dogmaphobic committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    return QGCMapEngine::numberToString(_uniqueTileCount);
}

//-----------------------------------------------------------------------------
QString
QGCCachedTileSet::savedTileCountStr()
{
    return QGCMapEngine::numberToString(_savedTileCount);
}

//-----------------------------------------------------------------------------
QString
QGCCachedTileSet::savedTileSizeStr()
{
    return QGCMapEngine::bigSizeToString(_savedTileSize);
dogmaphobic's avatar
dogmaphobic committed
115 116 117 118 119 120
}

//-----------------------------------------------------------------------------
QString
QGCCachedTileSet::downloadStatus()
{
121
    if(_defaultSet) {
dogmaphobic's avatar
dogmaphobic committed
122
        return totalTilesSizeStr();
123
    }
dogmaphobic's avatar
dogmaphobic committed
124 125
    if(_totalTileCount <= _savedTileCount) {
        return savedTileSizeStr();
dogmaphobic's avatar
dogmaphobic committed
126
    } else {
dogmaphobic's avatar
dogmaphobic committed
127
        return savedTileSizeStr() + " / " + totalTilesSizeStr();
dogmaphobic's avatar
dogmaphobic committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    }
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::createDownloadTask()
{
    if(!_downloading) {
        _errorCount   = 0;
        _downloading  = true;
        _noMoreTiles  = false;
        emit downloadingChanged();
        emit errorCountChanged();
    }
    QGCGetTileDownloadListTask* task = new QGCGetTileDownloadListTask(_id, TILE_BATCH_SIZE);
    connect(task, &QGCGetTileDownloadListTask::tileListFetched, this, &QGCCachedTileSet::_tileListFetched);
    if(_manager)
        connect(task, &QGCMapTask::error, _manager, &QGCMapEngineManager::taskError);
    getQGCMapEngine()->addTask(task);
dogmaphobic's avatar
dogmaphobic committed
147 148
    emit totalTileCountChanged();
    emit totalTilesSizeChanged();
dogmaphobic's avatar
dogmaphobic committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    _batchRequested = true;
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::resumeDownloadTask()
{
    //-- Reset and download error flag (for all tiles)
    QGCUpdateTileDownloadStateTask* task = new QGCUpdateTileDownloadStateTask(_id, QGCTile::StatePending, "*");
    getQGCMapEngine()->addTask(task);
    //-- Start download
    createDownloadTask();
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::cancelDownloadTask()
{
    if(_downloading) {
        _downloading = false;
        emit downloadingChanged();
    }
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::_tileListFetched(QList<QGCTile *> tiles)
{
    _batchRequested = false;
    //-- Done?
    if(tiles.size() < TILE_BATCH_SIZE) {
        _noMoreTiles = true;
    }
    if(!tiles.size()) {
dogmaphobic's avatar
dogmaphobic committed
183
        _doneWithDownload();
dogmaphobic's avatar
dogmaphobic committed
184 185 186 187 188 189 190 191 192 193 194 195
        return;
    }
    //-- If this is the first time, create Network Manager
    if (!_networkManager) {
        _networkManager = new QNetworkAccessManager(this);
    }
    //-- Add tiles to the list
    _tilesToDownload += tiles;
    //-- Kick downloads
    _prepareDownload();
}

dogmaphobic's avatar
dogmaphobic committed
196 197 198 199 200 201 202
//-----------------------------------------------------------------------------
void QGCCachedTileSet::_doneWithDownload()
{
    if(!_errorCount) {
        _totalTileCount = _savedTileCount;
        _totalTileSize  = _savedTileSize;
        //-- Too expensive to compute the real size now. Estimate it for the time being.
203 204 205 206 207 208 209 210 211
        quint32 avg;
        if(_savedTileSize != 0){
            avg = _savedTileSize / _savedTileCount;
        }
        else{
            qWarning() << "QGCMapEngineManager::_doneWithDownload _savedTileSize=0 !";
            avg = 0;
        }

dogmaphobic's avatar
dogmaphobic committed
212 213 214 215 216 217 218 219 220 221 222 223
        _uniqueTileSize = _uniqueTileCount * avg;
    }
    emit totalTileCountChanged();
    emit totalTilesSizeChanged();
    emit savedTileSizeChanged();
    emit savedTileCountChanged();
    emit uniqueTileSizeChanged();
    _downloading = false;
    emit downloadingChanged();
    emit completeChanged();
}

dogmaphobic's avatar
dogmaphobic committed
224 225 226 227 228 229
//-----------------------------------------------------------------------------
void QGCCachedTileSet::_prepareDownload()
{
    if(!_tilesToDownload.count()) {
        //-- Are we done?
        if(_noMoreTiles) {
dogmaphobic's avatar
dogmaphobic committed
230
            _doneWithDownload();
dogmaphobic's avatar
dogmaphobic committed
231 232 233 234 235 236 237 238 239 240 241 242 243
        } else {
            if(!_batchRequested)
                createDownloadTask();
        }
        return;
    }
    //-- Prepare queue (QNetworkAccessManager has a limit for concurrent downloads)
    for(int i = _replies.count(); i < QGCMapEngine::concurrentDownloads(_type); i++) {
        if(_tilesToDownload.count()) {
            QGCTile* tile = _tilesToDownload.first();
            _tilesToDownload.removeFirst();
            QNetworkRequest request = getQGCMapEngine()->urlFactory()->getTileURL(tile->type(), tile->x(), tile->y(), tile->z(), _networkManager);
            request.setAttribute(QNetworkRequest::User, tile->hash());
244 245 246 247 248 249
#if !defined(__mobile__)
            QNetworkProxy proxy = _networkManager->proxy();
            QNetworkProxy tProxy;
            tProxy.setType(QNetworkProxy::DefaultProxy);
            _networkManager->setProxy(tProxy);
#endif
dogmaphobic's avatar
dogmaphobic committed
250 251 252
            QNetworkReply* reply = _networkManager->get(request);
            reply->setParent(0);
            connect(reply, &QNetworkReply::finished, this, &QGCCachedTileSet::_networkReplyFinished);
253
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
dogmaphobic's avatar
dogmaphobic committed
254
            connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &QGCCachedTileSet::_networkReplyError);
255 256 257
#else
            connect(reply, &QNetworkReply::errorOccurred, this, &QGCCachedTileSet::_networkReplyError);
#endif
dogmaphobic's avatar
dogmaphobic committed
258
            _replies.insert(tile->hash(), reply);
259 260 261
#if !defined(__mobile__)
            _networkManager->setProxy(proxy);
#endif
262
            delete tile;
dogmaphobic's avatar
dogmaphobic committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
            //-- Refill queue if running low
            if(!_batchRequested && !_noMoreTiles && _tilesToDownload.count() < (QGCMapEngine::concurrentDownloads(_type) * 10)) {
                //-- Request new batch of tiles
                createDownloadTask();
            }
        }
    }
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::_networkReplyFinished()
{
    //-- Figure out which reply this is
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender());
    if(!reply) {
        qWarning() << "QGCMapEngineManager::networkReplyFinished() NULL Reply";
        return;
    }
282 283 284 285 286 287 288 289 290 291 292
    if (reply->error() == QNetworkReply::NoError) {
        //-- Get tile hash
        const QString hash = reply->request().attribute(QNetworkRequest::User).toString();
        if(!hash.isEmpty()) {
            if(_replies.contains(hash)) {
                _replies.remove(hash);
            } else {
                qWarning() << "QGCMapEngineManager::networkReplyFinished() Reply not in list: " << hash;
            }
            qCDebug(QGCCachedTileSetLog) << "Tile fetched" << hash;
            QByteArray image = reply->readAll();
293
            QString type = getQGCMapEngine()->hashToType(hash);
294
            if (type == "Airmap Elevation" ) {
295
                image = TerrainTile::serialize(image);
dogmaphobic's avatar
dogmaphobic committed
296
            }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
            QString format = getQGCMapEngine()->urlFactory()->getImageFormat(type, image);
            if(!format.isEmpty()) {
                //-- Cache tile
                getQGCMapEngine()->cacheTile(type, hash, image, format, _id);
                QGCUpdateTileDownloadStateTask* task = new QGCUpdateTileDownloadStateTask(_id, QGCTile::StateComplete, hash);
                getQGCMapEngine()->addTask(task);
                //-- Updated cached (downloaded) data
                _savedTileSize += image.size();
                _savedTileCount++;
                emit savedTileSizeChanged();
                emit savedTileCountChanged();
                //-- Update estimate
                if(_savedTileCount % 10 == 0) {
                    quint32 avg = _savedTileSize / _savedTileCount;
                    _totalTileSize  = avg * _totalTileCount;
                    _uniqueTileSize = avg * _uniqueTileCount;
                    emit totalTilesSizeChanged();
                    emit uniqueTileSizeChanged();
                }
            }
            //-- Setup a new download
            _prepareDownload();
        } else {
            qWarning() << "QGCMapEngineManager::networkReplyFinished() Empty Hash";
dogmaphobic's avatar
dogmaphobic committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334
        }
    }
    reply->deleteLater();
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::_networkReplyError(QNetworkReply::NetworkError error)
{
    //-- Figure out which reply this is
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender());
    if (!reply) {
        return;
    }
335
    //-- Update error count
dogmaphobic's avatar
dogmaphobic committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    _errorCount++;
    emit errorCountChanged();
    //-- Get tile hash
    QString hash = reply->request().attribute(QNetworkRequest::User).toString();
    qCDebug(QGCCachedTileSetLog) << "Error fetching tile" << reply->errorString();
    if(!hash.isEmpty()) {
        if(_replies.contains(hash)) {
            _replies.remove(hash);
        } else {
            qWarning() << "QGCMapEngineManager::networkReplyError() Reply not in list: " << hash;
        }
        if (error != QNetworkReply::OperationCanceledError) {
            qWarning() << "QGCMapEngineManager::networkReplyError() Error:" << reply->errorString();
        }
        QGCUpdateTileDownloadStateTask* task = new QGCUpdateTileDownloadStateTask(_id, QGCTile::StateError, hash);
        getQGCMapEngine()->addTask(task);
    } else {
        qWarning() << "QGCMapEngineManager::networkReplyError() Empty Hash";
    }
    //-- Setup a new download
    _prepareDownload();
    reply->deleteLater();
}

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::setManager(QGCMapEngineManager* mgr)
{
    _manager = mgr;
}
366 367 368 369 370 371 372 373 374 375 376

//-----------------------------------------------------------------------------
void
QGCCachedTileSet::setSelected(bool sel)
{
    _selected = sel;
    emit selectedChanged();
    if(_manager) {
        emit _manager->selectedCountChanged();
    }
}