QGCTileCacheWorker.cpp 48.8 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 Cache Worker Thread
 *
Gus Grubba's avatar
Gus Grubba committed
15
 *   @author Gus Grubba <gus@auterion.com>
dogmaphobic's avatar
dogmaphobic committed
16 17 18
 *
 */

dogmaphobic's avatar
dogmaphobic committed
19 20 21
#include "QGCMapEngine.h"
#include "QGCMapTileSet.h"

dogmaphobic's avatar
dogmaphobic committed
22 23 24 25 26 27 28
#include <QVariant>
#include <QtSql/QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QDateTime>
#include <QApplication>
#include <QFile>
29
#include <QSettings>
dogmaphobic's avatar
dogmaphobic committed
30 31 32

#include "time.h"

33 34 35
static const char*      kDefaultSet     = "Default Tile Set";
static const QString    kSession        = QStringLiteral("QGeoTileWorkerSession");
static const QString    kExportSession  = QStringLiteral("QGeoTileExportSession");
dogmaphobic's avatar
dogmaphobic committed
36 37 38 39 40 41 42 43 44 45

QGC_LOGGING_CATEGORY(QGCTileCacheLog, "QGCTileCacheLog")

//-- Update intervals

#define LONG_TIMEOUT        5
#define SHORT_TIMEOUT       2

//-----------------------------------------------------------------------------
QGCCacheWorker::QGCCacheWorker()
46
    : _db(nullptr)
dogmaphobic's avatar
dogmaphobic committed
47 48 49 50 51 52 53 54 55
    , _valid(false)
    , _failed(false)
    , _defaultSet(UINT64_MAX)
    , _totalSize(0)
    , _totalCount(0)
    , _defaultSize(0)
    , _defaultCount(0)
    , _lastUpdate(0)
    , _updateTimeout(SHORT_TIMEOUT)
56
    , _hostLookupID(0)
dogmaphobic's avatar
dogmaphobic committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
{
}

//-----------------------------------------------------------------------------
QGCCacheWorker::~QGCCacheWorker()
{
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::setDatabaseFile(const QString& path)
{
    _databasePath = path;
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::quit()
{
76 77 78
    if(_hostLookupID) {
        QHostInfo::abortHostLookup(_hostLookupID);
    }
dogmaphobic's avatar
dogmaphobic committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    _mutex.lock();
    while(_taskQueue.count()) {
        QGCMapTask* task = _taskQueue.dequeue();
        delete task;
    }
    _mutex.unlock();
    if(this->isRunning()) {
        _waitc.wakeAll();
    }
}

//-----------------------------------------------------------------------------
bool
QGCCacheWorker::enqueueTask(QGCMapTask* task)
{
    //-- If not initialized, the only allowed task is Init
    if(!_valid && task->type() != QGCMapTask::taskInit) {
        task->setError("Database Not Initialized");
        task->deleteLater();
        return false;
    }
100 101 102 103 104 105 106
    _mutex.lock();
    _taskQueue.enqueue(task);
    _mutex.unlock();
    if(this->isRunning()) {
        _waitc.wakeAll();
    } else {
        this->start(QThread::HighPriority);
dogmaphobic's avatar
dogmaphobic committed
107
    }
108
    return true;
dogmaphobic's avatar
dogmaphobic committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::run()
{
    if(!_valid && !_failed) {
        _init();
    }
    if(_valid) {
        _db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", kSession));
        _db->setDatabaseName(_databasePath);
        _db->setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
        _valid = _db->open();
    }
124
    _deleteBingNoTileTiles();
dogmaphobic's avatar
dogmaphobic committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    while(true) {
        QGCMapTask* task;
        if(_taskQueue.count()) {
            _mutex.lock();
            task = _taskQueue.dequeue();
            _mutex.unlock();
            switch(task->type()) {
                case QGCMapTask::taskInit:
                    break;
                case QGCMapTask::taskCacheTile:
                    _saveTile(task);
                    break;
                case QGCMapTask::taskFetchTile:
                    _getTile(task);
                    break;
                case QGCMapTask::taskFetchTileSets:
                    _getTileSets(task);
                    break;
                case QGCMapTask::taskCreateTileSet:
                    _createTileSet(task);
                    break;
                case QGCMapTask::taskGetTileDownloadList:
                    _getTileDownloadList(task);
                    break;
                case QGCMapTask::taskUpdateTileDownloadState:
                    _updateTileDownloadState(task);
                    break;
                case QGCMapTask::taskDeleteTileSet:
                    _deleteTileSet(task);
                    break;
Gus Grubba's avatar
Gus Grubba committed
155 156 157
                case QGCMapTask::taskRenameTileSet:
                    _renameTileSet(task);
                    break;
dogmaphobic's avatar
dogmaphobic committed
158 159 160 161 162 163
                case QGCMapTask::taskPruneCache:
                    _pruneCache(task);
                    break;
                case QGCMapTask::taskReset:
                    _resetCacheDatabase(task);
                    break;
164 165 166
                case QGCMapTask::taskExport:
                    _exportSets(task);
                    break;
Gus Grubba's avatar
Gus Grubba committed
167 168 169
                case QGCMapTask::taskImport:
                    _importSets(task);
                    break;
170 171 172
                case QGCMapTask::taskTestInternet:
                    _testInternet();
                    break;
dogmaphobic's avatar
dogmaphobic committed
173 174 175
            }
            task->deleteLater();
            //-- Check for update timeout
176
            size_t count = static_cast<size_t>(_taskQueue.count());
dogmaphobic's avatar
dogmaphobic committed
177 178 179 180 181
            if(count > 100) {
                _updateTimeout = LONG_TIMEOUT;
            } else if(count < 25) {
                _updateTimeout = SHORT_TIMEOUT;
            }
182
            if(!count || (time(nullptr) - _lastUpdate > _updateTimeout)) {
dogmaphobic's avatar
dogmaphobic committed
183 184 185
                if(_valid) {
                    _updateTotals();
                }
dogmaphobic's avatar
dogmaphobic committed
186 187 188 189
            }
        } else {
            //-- Wait a bit before shutting things down
            _waitmutex.lock();
190
            unsigned long timeout = 5000;
191 192 193 194 195
            _waitc.wait(&_waitmutex, timeout);
            _waitmutex.unlock();
            _mutex.lock();
            //-- If nothing to do, close db and leave thread
            if(!_taskQueue.count()) {
dogmaphobic's avatar
dogmaphobic committed
196
                _mutex.unlock();
197
                break;
dogmaphobic's avatar
dogmaphobic committed
198
            }
199
            _mutex.unlock();
dogmaphobic's avatar
dogmaphobic committed
200 201 202 203
        }
    }
    if(_db) {
        delete _db;
204
        _db = nullptr;
dogmaphobic's avatar
dogmaphobic committed
205 206 207
        QSqlDatabase::removeDatabase(kSession);
    }
}
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_deleteBingNoTileTiles()
{
    QSettings settings;
    static const char* alreadyDoneKey = "_deleteBingNoTileTilesDone";

    if (settings.value(alreadyDoneKey, false).toBool()) {
        return;
    }
    settings.setValue(alreadyDoneKey, true);

    // Previously we would store these empty tile graphics in the cache. This prevented the ability to zoom beyong the level
    // of available tiles. So we need to remove only of these still hanging around to make higher zoom levels work.
    QFile file(":/res/BingNoTileBytes.dat");
    file.open(QFile::ReadOnly);
    QByteArray noTileBytes = file.readAll();
    file.close();

    QSqlQuery query(*_db);
    QString s;
    //-- Select tiles in default set only, sorted by oldest.
    s = QString("SELECT tileID, tile, hash FROM Tiles WHERE LENGTH(tile) = %1").arg(noTileBytes.count());
    QList<quint64> idsToDelete;
    if (query.exec(s)) {
        while(query.next()) {
            if (query.value(1).toByteArray() == noTileBytes) {
                idsToDelete.append(query.value(0).toULongLong());
                qCDebug(QGCTileCacheLog) << "_deleteBingNoTileTiles HASH:" << query.value(2).toString();
            }
        }
        for (const quint64 tileId: idsToDelete) {
            s = QString("DELETE FROM Tiles WHERE tileID = %1").arg(tileId);
            if (!query.exec(s)) {
                qCWarning(QGCTileCacheLog) << "Delete failed";
            }
        }
    } else {
        qCWarning(QGCTileCacheLog) << "_deleteBingNoTileTiles query failed";
    }
}

dogmaphobic's avatar
dogmaphobic committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
//-----------------------------------------------------------------------------
bool
QGCCacheWorker::_findTileSetID(const QString name, quint64& setID)
{
    QSqlQuery query(*_db);
    QString s = QString("SELECT setID FROM TileSets WHERE name = \"%1\"").arg(name);
    if(query.exec(s)) {
        if(query.next()) {
            setID = query.value(0).toULongLong();
            return true;
        }
    }
    return false;
}

//-----------------------------------------------------------------------------
quint64
QGCCacheWorker::_getDefaultTileSet()
{
    if(_defaultSet != UINT64_MAX)
        return _defaultSet;
    QSqlQuery query(*_db);
    QString s = QString("SELECT setID FROM TileSets WHERE defaultSet = 1");
    if(query.exec(s)) {
        if(query.next()) {
            _defaultSet = query.value(0).toULongLong();
            return _defaultSet;
        }
    }
    return 1L;
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_saveTile(QGCMapTask *mtask)
{
    if(_valid) {
        QGCSaveTileTask* task = static_cast<QGCSaveTileTask*>(mtask);
        QSqlQuery query(*_db);
        query.prepare("INSERT INTO Tiles(hash, format, tile, size, type, date) VALUES(?, ?, ?, ?, ?, ?)");
        query.addBindValue(task->tile()->hash());
        query.addBindValue(task->tile()->format());
        query.addBindValue(task->tile()->img());
        query.addBindValue(task->tile()->img().size());
        query.addBindValue(task->tile()->type());
        query.addBindValue(QDateTime::currentDateTime().toTime_t());
        if(query.exec()) {
            quint64 tileID = query.lastInsertId().toULongLong();
            quint64 setID = task->tile()->set() == UINT64_MAX ? _getDefaultTileSet() : task->tile()->set();
            QString s = QString("INSERT INTO SetTiles(tileID, setID) VALUES(%1, %2)").arg(tileID).arg(setID);
            query.prepare(s);
            if(!query.exec()) {
                qWarning() << "Map Cache SQL error (add tile into SetTiles):" << query.lastError().text();
            }
            qCDebug(QGCTileCacheLog) << "_saveTile() HASH:" << task->tile()->hash();
        } else {
            //-- Tile was already there.
            //   QtLocation some times requests the same tile twice in a row. The first is saved, the second is already there.
        }
    } else {
        qWarning() << "Map Cache SQL error (saveTile() open db):" << _db->lastError();
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_getTile(QGCMapTask* mtask)
{
319
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
320 321 322 323 324 325 326 327 328 329
        return;
    }
    bool found = false;
    QGCFetchTileTask* task = static_cast<QGCFetchTileTask*>(mtask);
    QSqlQuery query(*_db);
    QString s = QString("SELECT tile, format, type FROM Tiles WHERE hash = \"%1\"").arg(task->hash());
    if(query.exec(s)) {
        if(query.next()) {
            QByteArray ar   = query.value(0).toByteArray();
            QString format  = query.value(1).toString();
330
            QString type = getQGCMapEngine()->urlFactory()->getTypeFromId(query.value(2).toInt());
dogmaphobic's avatar
dogmaphobic committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
            qCDebug(QGCTileCacheLog) << "_getTile() (Found in DB) HASH:" << task->hash();
            QGCCacheTile* tile = new QGCCacheTile(task->hash(), ar, format, type);
            task->setTileFetched(tile);
            found = true;
        }
    }
    if(!found) {
        qCDebug(QGCTileCacheLog) << "_getTile() (NOT in DB) HASH:" << task->hash();
        task->setError("Tile not in cache database");
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_getTileSets(QGCMapTask* mtask)
{
347
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
348 349 350 351 352
        return;
    }
    QGCFetchTileSetTask* task = static_cast<QGCFetchTileSetTask*>(mtask);
    QSqlQuery query(*_db);
    QString s = QString("SELECT * FROM TileSets ORDER BY defaultSet DESC, name ASC");
dogmaphobic's avatar
dogmaphobic committed
353
    qCDebug(QGCTileCacheLog) << "_getTileSets(): " << s;
dogmaphobic's avatar
dogmaphobic committed
354 355 356
    if(query.exec(s)) {
        while(query.next()) {
            QString name = query.value("name").toString();
dogmaphobic's avatar
dogmaphobic committed
357
            QGCCachedTileSet* set = new QGCCachedTileSet(name);
dogmaphobic's avatar
dogmaphobic committed
358 359 360 361 362 363 364 365
            set->setId(query.value("setID").toULongLong());
            set->setMapTypeStr(query.value("typeStr").toString());
            set->setTopleftLat(query.value("topleftLat").toDouble());
            set->setTopleftLon(query.value("topleftLon").toDouble());
            set->setBottomRightLat(query.value("bottomRightLat").toDouble());
            set->setBottomRightLon(query.value("bottomRightLon").toDouble());
            set->setMinZoom(query.value("minZoom").toInt());
            set->setMaxZoom(query.value("maxZoom").toInt());
366
            set->setType(getQGCMapEngine()->urlFactory()->getTypeFromId(query.value("type").toInt()));
dogmaphobic's avatar
dogmaphobic committed
367
            set->setTotalTileCount(query.value("numTiles").toUInt());
dogmaphobic's avatar
dogmaphobic committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            set->setDefaultSet(query.value("defaultSet").toInt() != 0);
            set->setCreationDate(QDateTime::fromTime_t(query.value("date").toUInt()));
            _updateSetTotals(set);
            //-- Object created here must be moved to app thread to be used there
            set->moveToThread(QApplication::instance()->thread());
            task->tileSetFetched(set);
        }
    } else {
        task->setError("No tile set in database");
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_updateSetTotals(QGCCachedTileSet* set)
{
    if(set->defaultSet()) {
385
        _updateTotals();
dogmaphobic's avatar
dogmaphobic committed
386 387 388 389
        set->setSavedTileCount(_totalCount);
        set->setSavedTileSize(_totalSize);
        set->setTotalTileCount(_defaultCount);
        set->setTotalTileSize(_defaultSize);
dogmaphobic's avatar
dogmaphobic committed
390 391 392 393
        return;
    }
    QSqlQuery subquery(*_db);
    QString sq = QString("SELECT COUNT(size), SUM(size) FROM Tiles A INNER JOIN SetTiles B on A.tileID = B.tileID WHERE B.setID = %1").arg(set->id());
dogmaphobic's avatar
dogmaphobic committed
394
    qCDebug(QGCTileCacheLog) << "_updateSetTotals(): " << sq;
dogmaphobic's avatar
dogmaphobic committed
395 396
    if(subquery.exec(sq)) {
        if(subquery.next()) {
dogmaphobic's avatar
dogmaphobic committed
397 398 399 400
            set->setSavedTileCount(subquery.value(0).toUInt());
            set->setSavedTileSize(subquery.value(1).toULongLong());
            qCDebug(QGCTileCacheLog) << "Set" << set->id() << "Totals:" << set->savedTileCount() << " " << set->savedTileSize() << "Expected: " << set->totalTileCount() << " " << set->totalTilesSize();
            //-- Update (estimated) size
401
            quint64 avg = getQGCMapEngine()->urlFactory()->averageSizeForType(set->type());
dogmaphobic's avatar
dogmaphobic committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            if(set->totalTileCount() <= set->savedTileCount()) {
                //-- We're done so the saved size is the total size
                set->setTotalTileSize(set->savedTileSize());
            } else {
                //-- Otherwise we need to estimate it.
                if(set->savedTileCount() > 10 && set->savedTileSize()) {
                    avg = set->savedTileSize() / set->savedTileCount();
                }
                set->setTotalTileSize(avg * set->totalTileCount());
            }
            //-- Now figure out the count for tiles unique to this set
            quint32 ucount = 0;
            quint64 usize  = 0;
            sq = QString("SELECT COUNT(size), SUM(size) FROM Tiles WHERE tileID IN (SELECT A.tileID FROM SetTiles A join SetTiles B on A.tileID = B.tileID WHERE B.setID = %1 GROUP by A.tileID HAVING COUNT(A.tileID) = 1)").arg(set->id());
            if(subquery.exec(sq)) {
                if(subquery.next()) {
                    //-- This is only accurate when all tiles are downloaded
                    ucount = subquery.value(0).toUInt();
                    usize  = subquery.value(1).toULongLong();
                }
            }
            //-- If we haven't downloaded it all, estimate size of unique tiles
            quint32 expectedUcount = set->totalTileCount() - set->savedTileCount();
            if(!ucount) {
                usize = expectedUcount * avg;
            } else {
                expectedUcount = ucount;
dogmaphobic's avatar
dogmaphobic committed
429
            }
dogmaphobic's avatar
dogmaphobic committed
430 431
            set->setUniqueTileCount(expectedUcount);
            set->setUniqueTileSize(usize);
dogmaphobic's avatar
dogmaphobic committed
432 433 434 435 436 437 438 439 440 441 442
        }
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_updateTotals()
{
    QSqlQuery query(*_db);
    QString s;
    s = QString("SELECT COUNT(size), SUM(size) FROM Tiles");
dogmaphobic's avatar
dogmaphobic committed
443
    qCDebug(QGCTileCacheLog) << "_updateTotals(): " << s;
dogmaphobic's avatar
dogmaphobic committed
444 445 446 447 448 449
    if(query.exec(s)) {
        if(query.next()) {
            _totalCount = query.value(0).toUInt();
            _totalSize  = query.value(1).toULongLong();
        }
    }
dogmaphobic's avatar
dogmaphobic committed
450 451
    s = QString("SELECT COUNT(size), SUM(size) FROM Tiles WHERE tileID IN (SELECT A.tileID FROM SetTiles A join SetTiles B on A.tileID = B.tileID WHERE B.setID = %1 GROUP by A.tileID HAVING COUNT(A.tileID) = 1)").arg(_getDefaultTileSet());
    qCDebug(QGCTileCacheLog) << "_updateTotals(): " << s;
dogmaphobic's avatar
dogmaphobic committed
452 453 454 455 456 457 458
    if(query.exec(s)) {
        if(query.next()) {
            _defaultCount = query.value(0).toUInt();
            _defaultSize  = query.value(1).toULongLong();
        }
    }
    emit updateTotals(_totalCount, _totalSize, _defaultCount, _defaultSize);
459
    _lastUpdate = time(nullptr);
dogmaphobic's avatar
dogmaphobic committed
460 461 462
}

//-----------------------------------------------------------------------------
dogmaphobic's avatar
dogmaphobic committed
463
quint64 QGCCacheWorker::_findTile(const QString hash)
dogmaphobic's avatar
dogmaphobic committed
464
{
dogmaphobic's avatar
dogmaphobic committed
465
    quint64 tileID = 0;
dogmaphobic's avatar
dogmaphobic committed
466
    QSqlQuery query(*_db);
dogmaphobic's avatar
dogmaphobic committed
467
    QString s = QString("SELECT tileID FROM Tiles WHERE hash = \"%1\"").arg(hash);
dogmaphobic's avatar
dogmaphobic committed
468 469
    if(query.exec(s)) {
        if(query.next()) {
dogmaphobic's avatar
dogmaphobic committed
470
            tileID = query.value(0).toULongLong();
dogmaphobic's avatar
dogmaphobic committed
471 472
        }
    }
dogmaphobic's avatar
dogmaphobic committed
473
    return tileID;
dogmaphobic's avatar
dogmaphobic committed
474 475 476 477 478 479 480 481 482 483 484 485
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_createTileSet(QGCMapTask *mtask)
{
    if(_valid) {
        //-- Create Tile Set
        quint32 actual_count = 0;
        QGCCreateTileSetTask* task = static_cast<QGCCreateTileSetTask*>(mtask);
        QSqlQuery query(*_db);
        query.prepare("INSERT INTO TileSets("
dogmaphobic's avatar
dogmaphobic committed
486 487
            "name, typeStr, topleftLat, topleftLon, bottomRightLat, bottomRightLon, minZoom, maxZoom, type, numTiles, date"
            ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
dogmaphobic's avatar
dogmaphobic committed
488 489 490 491 492 493 494 495
        query.addBindValue(task->tileSet()->name());
        query.addBindValue(task->tileSet()->mapTypeStr());
        query.addBindValue(task->tileSet()->topleftLat());
        query.addBindValue(task->tileSet()->topleftLon());
        query.addBindValue(task->tileSet()->bottomRightLat());
        query.addBindValue(task->tileSet()->bottomRightLon());
        query.addBindValue(task->tileSet()->minZoom());
        query.addBindValue(task->tileSet()->maxZoom());
Pierre TILAK's avatar
Pierre TILAK committed
496
        query.addBindValue(getQGCMapEngine()->urlFactory()->getIdFromType(task->tileSet()->type()));
dogmaphobic's avatar
dogmaphobic committed
497
        query.addBindValue(task->tileSet()->totalTileCount());
dogmaphobic's avatar
dogmaphobic committed
498 499 500 501
        query.addBindValue(QDateTime::currentDateTime().toTime_t());
        if(!query.exec()) {
            qWarning() << "Map Cache SQL error (add tileSet into TileSets):" << query.lastError().text();
        } else {
dogmaphobic's avatar
dogmaphobic committed
502
            //-- Get just created (auto-incremented) setID
dogmaphobic's avatar
dogmaphobic committed
503 504 505
            quint64 setID = query.lastInsertId().toULongLong();
            task->tileSet()->setId(setID);
            //-- Prepare Download List
dogmaphobic's avatar
dogmaphobic committed
506
            quint64 tileCount = 0;
Gus Grubba's avatar
Gus Grubba committed
507
            _db->transaction();
dogmaphobic's avatar
dogmaphobic committed
508 509 510 511
            for(int z = task->tileSet()->minZoom(); z <= task->tileSet()->maxZoom(); z++) {
                QGCTileSet set = QGCMapEngine::getTileCount(z,
                    task->tileSet()->topleftLon(), task->tileSet()->topleftLat(),
                    task->tileSet()->bottomRightLon(), task->tileSet()->bottomRightLat(), task->tileSet()->type());
dogmaphobic's avatar
dogmaphobic committed
512
                tileCount += set.tileCount;
513
                QString type = task->tileSet()->type();
dogmaphobic's avatar
dogmaphobic committed
514 515 516 517
                for(int x = set.tileX0; x <= set.tileX1; x++) {
                    for(int y = set.tileY0; y <= set.tileY1; y++) {
                        //-- See if tile is already downloaded
                        QString hash = QGCMapEngine::getTileHash(type, x, y, z);
dogmaphobic's avatar
dogmaphobic committed
518 519
                        quint64 tileID = _findTile(hash);
                        if(!tileID) {
dogmaphobic's avatar
dogmaphobic committed
520 521 522 523
                            //-- Set to download
                            query.prepare("INSERT OR IGNORE INTO TilesDownload(setID, hash, type, x, y, z, state) VALUES(?, ?, ?, ?, ? ,? ,?)");
                            query.addBindValue(setID);
                            query.addBindValue(hash);
Pierre TILAK's avatar
Pierre TILAK committed
524
                            query.addBindValue(getQGCMapEngine()->urlFactory()->getIdFromType(type));
dogmaphobic's avatar
dogmaphobic committed
525 526 527 528 529 530 531 532 533 534
                            query.addBindValue(x);
                            query.addBindValue(y);
                            query.addBindValue(z);
                            query.addBindValue(0);
                            if(!query.exec()) {
                                qWarning() << "Map Cache SQL error (add tile into TilesDownload):" << query.lastError().text();
                                mtask->setError("Error creating tile set download list");
                                return;
                            } else
                                actual_count++;
dogmaphobic's avatar
dogmaphobic committed
535 536 537 538 539 540 541 542
                        } else {
                            //-- Tile already in the database. No need to dowload.
                            QString s = QString("INSERT OR IGNORE INTO SetTiles(tileID, setID) VALUES(%1, %2)").arg(tileID).arg(setID);
                            query.prepare(s);
                            if(!query.exec()) {
                                qWarning() << "Map Cache SQL error (add tile into SetTiles):" << query.lastError().text();
                            }
                            qCDebug(QGCTileCacheLog) << "_createTileSet() Already Cached HASH:" << hash;
dogmaphobic's avatar
dogmaphobic committed
543 544 545 546
                        }
                    }
                }
            }
Gus Grubba's avatar
Gus Grubba committed
547
            _db->commit();
dogmaphobic's avatar
dogmaphobic committed
548 549 550 551 552 553 554 555 556 557 558 559 560
            //-- Done
            _updateSetTotals(task->tileSet());
            task->setTileSetSaved();
            return;
        }
    }
    mtask->setError("Error saving tile set");
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_getTileDownloadList(QGCMapTask* mtask)
{
561
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
562 563 564 565 566 567 568 569 570 571
        return;
    }
    QList<QGCTile*> tiles;
    QGCGetTileDownloadListTask* task = static_cast<QGCGetTileDownloadListTask*>(mtask);
    QSqlQuery query(*_db);
    QString s = QString("SELECT hash, type, x, y, z FROM TilesDownload WHERE setID = %1 AND state = 0 LIMIT %2").arg(task->setID()).arg(task->count());
    if(query.exec(s)) {
        while(query.next()) {
            QGCTile* tile = new QGCTile;
            tile->setHash(query.value("hash").toString());
572
            tile->setType(getQGCMapEngine()->urlFactory()->getTypeFromId(query.value("type").toInt()));
dogmaphobic's avatar
dogmaphobic committed
573 574 575 576 577 578
            tile->setX(query.value("x").toInt());
            tile->setY(query.value("y").toInt());
            tile->setZ(query.value("z").toInt());
            tiles.append(tile);
        }
        for(int i = 0; i < tiles.size(); i++) {
579
            s = QString("UPDATE TilesDownload SET state = %1 WHERE setID = %2 and hash = \"%3\"").arg(static_cast<int>(QGCTile::StateDownloading)).arg(task->setID()).arg(tiles[i]->hash());
dogmaphobic's avatar
dogmaphobic committed
580 581 582 583 584 585 586 587 588 589 590 591
            if(!query.exec(s)) {
                qWarning() << "Map Cache SQL error (set TilesDownload state):" << query.lastError().text();
            }
        }
    }
    task->setTileListFetched(tiles);
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_updateTileDownloadState(QGCMapTask* mtask)
{
592
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
593 594 595 596 597 598 599 600 601
        return;
    }
    QGCUpdateTileDownloadStateTask* task = static_cast<QGCUpdateTileDownloadStateTask*>(mtask);
    QSqlQuery query(*_db);
    QString s;
    if(task->state() == QGCTile::StateComplete) {
        s = QString("DELETE FROM TilesDownload WHERE setID = %1 AND hash = \"%2\"").arg(task->setID()).arg(task->hash());
    } else {
        if(task->hash() == "*") {
602
            s = QString("UPDATE TilesDownload SET state = %1 WHERE setID = %2").arg(static_cast<int>(task->state())).arg(task->setID());
dogmaphobic's avatar
dogmaphobic committed
603
        } else {
604
            s = QString("UPDATE TilesDownload SET state = %1 WHERE setID = %2 AND hash = \"%3\"").arg(static_cast<int>(task->state())).arg(task->setID()).arg(task->hash());
dogmaphobic's avatar
dogmaphobic committed
605 606 607 608 609 610 611 612 613 614 615
        }
    }
    if(!query.exec(s)) {
        qWarning() << "QGCCacheWorker::_updateTileDownloadState() Error:" << query.lastError().text();
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_pruneCache(QGCMapTask* mtask)
{
616
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
617 618 619 620 621
        return;
    }
    QGCPruneCacheTask* task = static_cast<QGCPruneCacheTask*>(mtask);
    QSqlQuery query(*_db);
    QString s;
dogmaphobic's avatar
dogmaphobic committed
622 623
    //-- Select tiles in default set only, sorted by oldest.
    s = QString("SELECT tileID, size, hash FROM Tiles WHERE tileID IN (SELECT A.tileID FROM SetTiles A join SetTiles B on A.tileID = B.tileID WHERE B.setID = %1 GROUP by A.tileID HAVING COUNT(A.tileID) = 1) ORDER BY DATE ASC LIMIT 128").arg(_getDefaultTileSet());
dogmaphobic's avatar
dogmaphobic committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    qint64 amount = (qint64)task->amount();
    QList<quint64> tlist;
    if(query.exec(s)) {
        while(query.next() && amount >= 0) {
            tlist << query.value(0).toULongLong();
            amount -= query.value(1).toULongLong();
            qCDebug(QGCTileCacheLog) << "_pruneCache() HASH:" << query.value(2).toString();
        }
        while(tlist.count()) {
            s = QString("DELETE FROM Tiles WHERE tileID = %1").arg(tlist[0]);
            tlist.removeFirst();
            if(!query.exec(s))
                break;
        }
        task->setPruned();
    }
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_deleteTileSet(QGCMapTask* mtask)
{
646
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
647 648 649
        return;
    }
    QGCDeleteTileSetTask* task = static_cast<QGCDeleteTileSetTask*>(mtask);
650 651 652 653 654 655 656 657
    _deleteTileSet(task->setID());
    task->setTileSetDeleted();
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_deleteTileSet(qulonglong id)
{
dogmaphobic's avatar
dogmaphobic committed
658 659
    QSqlQuery query(*_db);
    QString s;
dogmaphobic's avatar
dogmaphobic committed
660
    //-- Only delete tiles unique to this set
661
    s = QString("DELETE FROM Tiles WHERE tileID IN (SELECT A.tileID FROM SetTiles A JOIN SetTiles B ON A.tileID = B.tileID WHERE B.setID = %1 GROUP BY A.tileID HAVING COUNT(A.tileID) = 1)").arg(id);
dogmaphobic's avatar
dogmaphobic committed
662
    query.exec(s);
663
    s = QString("DELETE FROM TilesDownload WHERE setID = %1").arg(id);
dogmaphobic's avatar
dogmaphobic committed
664
    query.exec(s);
665
    s = QString("DELETE FROM TileSets WHERE setID = %1").arg(id);
dogmaphobic's avatar
dogmaphobic committed
666
    query.exec(s);
667
    s = QString("DELETE FROM SetTiles WHERE setID = %1").arg(id);
dogmaphobic's avatar
dogmaphobic committed
668 669 670
    query.exec(s);
    _updateTotals();
}
671

dogmaphobic's avatar
dogmaphobic committed
672
//-----------------------------------------------------------------------------
Gus Grubba's avatar
Gus Grubba committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
void
QGCCacheWorker::_renameTileSet(QGCMapTask* mtask)
{
    if(!_testTask(mtask)) {
        return;
    }
    QGCRenameTileSetTask* task = static_cast<QGCRenameTileSetTask*>(mtask);
    QSqlQuery query(*_db);
    QString s;
    s = QString("UPDATE TileSets SET name = \"%1\" WHERE setID = %2").arg(task->newName()).arg(task->setID());
    if(!query.exec(s)) {
        task->setError("Error renaming tile set");
    }
}

//-----------------------------------------------------------------------------
dogmaphobic's avatar
dogmaphobic committed
689 690 691
void
QGCCacheWorker::_resetCacheDatabase(QGCMapTask* mtask)
{
692
    if(!_testTask(mtask)) {
dogmaphobic's avatar
dogmaphobic committed
693 694 695 696 697 698 699 700 701 702 703 704 705
        return;
    }
    QGCResetTask* task = static_cast<QGCResetTask*>(mtask);
    QSqlQuery query(*_db);
    QString s;
    s = QString("DROP TABLE Tiles");
    query.exec(s);
    s = QString("DROP TABLE TileSets");
    query.exec(s);
    s = QString("DROP TABLE SetTiles");
    query.exec(s);
    s = QString("DROP TABLE TilesDownload");
    query.exec(s);
706
    _valid = _createDB(_db);
dogmaphobic's avatar
dogmaphobic committed
707 708 709
    task->setResetCompleted();
}

Gus Grubba's avatar
Gus Grubba committed
710 711 712 713 714 715 716 717
//-----------------------------------------------------------------------------
void
QGCCacheWorker::_importSets(QGCMapTask* mtask)
{
    if(!_testTask(mtask)) {
        return;
    }
    QGCImportTileTask* task = static_cast<QGCImportTileTask*>(mtask);
Gus Grubba's avatar
Gus Grubba committed
718 719 720 721 722
    //-- If replacing, simply copy over it
    if(task->replace()) {
        //-- Close and delete old database
        if(_db) {
            delete _db;
723
            _db = nullptr;
Gus Grubba's avatar
Gus Grubba committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
            QSqlDatabase::removeDatabase(kSession);
        }
        QFile file(_databasePath);
        file.remove();
        //-- Copy given database
        QFile::copy(task->path(), _databasePath);
        task->setProgress(25);
        _init();
        if(_valid) {
            task->setProgress(50);
            _db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", kSession));
            _db->setDatabaseName(_databasePath);
            _db->setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
            _valid = _db->open();
        }
        task->setProgress(100);
    } else {
        //-- Open imported set
        QSqlDatabase* dbImport = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", kExportSession));
        dbImport->setDatabaseName(task->path());
        dbImport->setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
        if (dbImport->open()) {
            QSqlQuery query(*dbImport);
            //-- Prepare progress report
            quint64 tileCount = 0;
            quint64 currentCount = 0;
750
            int lastProgress = -1;
Gus Grubba's avatar
Gus Grubba committed
751 752 753 754
            QString s;
            s = QString("SELECT COUNT(tileID) FROM Tiles");
            if(query.exec(s)) {
                if(query.next()) {
755
                    //-- Total number of tiles in imported database
Gus Grubba's avatar
Gus Grubba committed
756 757 758
                    tileCount  = query.value(0).toULongLong();
                }
            }
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
            if(tileCount) {
                //-- Iterate Tile Sets
                s = QString("SELECT * FROM TileSets ORDER BY defaultSet DESC, name ASC");
                if(query.exec(s)) {
                    while(query.next()) {
                        QString name            = query.value("name").toString();
                        quint64 setID           = query.value("setID").toULongLong();
                        QString mapType         = query.value("typeStr").toString();
                        double  topleftLat      = query.value("topleftLat").toDouble();
                        double  topleftLon      = query.value("topleftLon").toDouble();
                        double  bottomRightLat  = query.value("bottomRightLat").toDouble();
                        double  bottomRightLon  = query.value("bottomRightLon").toDouble();
                        int     minZoom         = query.value("minZoom").toInt();
                        int     maxZoom         = query.value("maxZoom").toInt();
                        int     type            = query.value("type").toInt();
                        quint32 numTiles        = query.value("numTiles").toUInt();
                        int     defaultSet      = query.value("defaultSet").toInt();
                        quint64 insertSetID     = _getDefaultTileSet();
                        //-- If not default set, create new one
                        if(!defaultSet) {
                            //-- Check if we have this tile set already
                            if(_findTileSetID(name, insertSetID)) {
                                int testCount = 0;
                                //-- Set with this name already exists. Make name unique.
                                while (true) {
784
                                    auto testName = QString::asprintf("%s %02d", name.toLatin1().data(), ++testCount);
785 786 787 788
                                    if(!_findTileSetID(testName, insertSetID) || testCount > 99) {
                                        name = testName;
                                        break;
                                    }
Gus Grubba's avatar
Gus Grubba committed
789 790
                                }
                            }
791 792 793 794 795 796 797 798 799 800 801 802 803
                            //-- Create new set
                            QSqlQuery cQuery(*_db);
                            cQuery.prepare("INSERT INTO TileSets("
                                "name, typeStr, topleftLat, topleftLon, bottomRightLat, bottomRightLon, minZoom, maxZoom, type, numTiles, defaultSet, date"
                                ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                            cQuery.addBindValue(name);
                            cQuery.addBindValue(mapType);
                            cQuery.addBindValue(topleftLat);
                            cQuery.addBindValue(topleftLon);
                            cQuery.addBindValue(bottomRightLat);
                            cQuery.addBindValue(bottomRightLon);
                            cQuery.addBindValue(minZoom);
                            cQuery.addBindValue(maxZoom);
Gus Grubba's avatar
Gus Grubba committed
804
                            cQuery.addBindValue(type);
805 806
                            cQuery.addBindValue(numTiles);
                            cQuery.addBindValue(defaultSet);
Gus Grubba's avatar
Gus Grubba committed
807
                            cQuery.addBindValue(QDateTime::currentDateTime().toTime_t());
808 809 810 811 812 813
                            if(!cQuery.exec()) {
                                task->setError("Error adding imported tile set to database");
                                break;
                            } else {
                                //-- Get just created (auto-incremented) setID
                                insertSetID = cQuery.lastInsertId().toULongLong();
Gus Grubba's avatar
Gus Grubba committed
814 815
                            }
                        }
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
                        //-- Find set tiles
                        QSqlQuery cQuery(*_db);
                        QSqlQuery subQuery(*dbImport);
                        QString sb = QString("SELECT * FROM Tiles WHERE tileID IN (SELECT A.tileID FROM SetTiles A JOIN SetTiles B ON A.tileID = B.tileID WHERE B.setID = %1 GROUP BY A.tileID HAVING COUNT(A.tileID) = 1)").arg(setID);
                        if(subQuery.exec(sb)) {
                            quint64 tilesFound = 0;
                            quint64 tilesSaved = 0;
                            _db->transaction();
                            while(subQuery.next()) {
                                tilesFound++;
                                QString hash    = subQuery.value("hash").toString();
                                QString format  = subQuery.value("format").toString();
                                QByteArray img  = subQuery.value("tile").toByteArray();
                                int type        = subQuery.value("type").toInt();
                                //-- Save tile
                                cQuery.prepare("INSERT INTO Tiles(hash, format, tile, size, type, date) VALUES(?, ?, ?, ?, ?, ?)");
                                cQuery.addBindValue(hash);
                                cQuery.addBindValue(format);
                                cQuery.addBindValue(img);
                                cQuery.addBindValue(img.size());
                                cQuery.addBindValue(type);
                                cQuery.addBindValue(QDateTime::currentDateTime().toTime_t());
                                if(cQuery.exec()) {
                                    tilesSaved++;
                                    quint64 importTileID = cQuery.lastInsertId().toULongLong();
                                    QString s = QString("INSERT INTO SetTiles(tileID, setID) VALUES(%1, %2)").arg(importTileID).arg(insertSetID);
                                    cQuery.prepare(s);
                                    cQuery.exec();
                                    currentCount++;
                                    if(tileCount) {
                                        int progress = (int)((double)currentCount / (double)tileCount * 100.0);
                                        //-- Avoid calling this if (int) progress hasn't changed.
                                        if(lastProgress != progress) {
                                            lastProgress = progress;
                                            task->setProgress(progress);
                                        }
                                    }
                                }
                            }
                            _db->commit();
                            if(tilesSaved) {
                                //-- Update tile count (if any added)
                                s = QString("SELECT COUNT(size) FROM Tiles A INNER JOIN SetTiles B on A.tileID = B.tileID WHERE B.setID = %1").arg(insertSetID);
                                if(cQuery.exec(s)) {
                                    if(cQuery.next()) {
                                        quint64 count  = cQuery.value(0).toULongLong();
                                        s = QString("UPDATE TileSets SET numTiles = %1 WHERE setID = %2").arg(count).arg(insertSetID);
                                        cQuery.exec(s);
                                    }
                                }
                            }
                            qint64 uniqueTiles = tilesFound - tilesSaved;
                            if((quint64)uniqueTiles < tileCount) {
                                tileCount -= uniqueTiles;
                            } else {
                                tileCount = 0;
                            }
                            //-- If there was nothing new in this set, remove it.
                            if(!tilesSaved && !defaultSet) {
                                qCDebug(QGCTileCacheLog) << "No unique tiles in" << name << "Removing it.";
                                _deleteTileSet(insertSetID);
Gus Grubba's avatar
Gus Grubba committed
877 878 879
                            }
                        }
                    }
880 881
                } else {
                    task->setError("No tile set in database");
Gus Grubba's avatar
Gus Grubba committed
882 883 884 885
                }
            }
            delete dbImport;
            QSqlDatabase::removeDatabase(kExportSession);
886 887 888
            if(!tileCount) {
                task->setError("No unique tiles in imported database");
            }
Gus Grubba's avatar
Gus Grubba committed
889 890 891 892
        } else {
            task->setError("Error opening import database");
        }
    }
Gus Grubba's avatar
Gus Grubba committed
893 894 895
    task->setImportCompleted();
}

896 897 898 899 900 901 902 903
//-----------------------------------------------------------------------------
void
QGCCacheWorker::_exportSets(QGCMapTask* mtask)
{
    if(!_testTask(mtask)) {
        return;
    }
    QGCExportTileTask* task = static_cast<QGCExportTileTask*>(mtask);
Gus Grubba's avatar
Gus Grubba committed
904 905 906
    //-- Delete target if it exists
    QFile file(task->path());
    file.remove();
907 908 909 910 911 912
    //-- Create exported database
    QSqlDatabase *dbExport = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", kExportSession));
    dbExport->setDatabaseName(task->path());
    dbExport->setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
    if (dbExport->open()) {
        if(_createDB(dbExport, false)) {
Gus Grubba's avatar
Gus Grubba committed
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
            //-- Prepare progress report
            quint64 tileCount = 0;
            quint64 currentCount = 0;
            for(int i = 0; i < task->sets().count(); i++) {
                QGCCachedTileSet* set = task->sets()[i];
                //-- Default set has no unique tiles
                if(set->defaultSet()) {
                    tileCount += set->totalTileCount();
                } else {
                    tileCount += set->uniqueTileCount();
                }
            }
            if(!tileCount) {
                tileCount = 1;
            }
928 929 930 931 932 933
            //-- Iterate sets to save
            for(int i = 0; i < task->sets().count(); i++) {
                QGCCachedTileSet* set = task->sets()[i];
                //-- Create Tile Exported Set
                QSqlQuery exportQuery(*dbExport);
                exportQuery.prepare("INSERT INTO TileSets("
Gus Grubba's avatar
Gus Grubba committed
934 935 936
                    "name, typeStr, topleftLat, topleftLon, bottomRightLat, bottomRightLon, minZoom, maxZoom, type, numTiles, defaultSet, date"
                    ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                exportQuery.addBindValue(set->name());
937 938 939 940 941 942 943
                exportQuery.addBindValue(set->mapTypeStr());
                exportQuery.addBindValue(set->topleftLat());
                exportQuery.addBindValue(set->topleftLon());
                exportQuery.addBindValue(set->bottomRightLat());
                exportQuery.addBindValue(set->bottomRightLon());
                exportQuery.addBindValue(set->minZoom());
                exportQuery.addBindValue(set->maxZoom());
Pierre TILAK's avatar
Pierre TILAK committed
944
                exportQuery.addBindValue(getQGCMapEngine()->urlFactory()->getIdFromType(set->type()));
945
                exportQuery.addBindValue(set->totalTileCount());
Gus Grubba's avatar
Gus Grubba committed
946
                exportQuery.addBindValue(set->defaultSet());
947 948 949 950 951 952 953 954 955 956 957
                exportQuery.addBindValue(QDateTime::currentDateTime().toTime_t());
                if(!exportQuery.exec()) {
                    task->setError("Error adding tile set to exported database");
                    break;
                } else {
                    //-- Get just created (auto-incremented) setID
                    quint64 exportSetID = exportQuery.lastInsertId().toULongLong();
                    //-- Find set tiles
                    QString s = QString("SELECT * FROM SetTiles WHERE setID = %1").arg(set->id());
                    QSqlQuery query(*_db);
                    if(query.exec(s)) {
Gus Grubba's avatar
Gus Grubba committed
958
                        dbExport->transaction();
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
                        while(query.next()) {
                            quint64 tileID = query.value("tileID").toULongLong();
                            //-- Get tile
                            QString s = QString("SELECT * FROM Tiles WHERE tileID = \"%1\"").arg(tileID);
                            QSqlQuery subQuery(*_db);
                            if(subQuery.exec(s)) {
                                if(subQuery.next()) {
                                    QString hash    = subQuery.value("hash").toString();
                                    QString format  = subQuery.value("format").toString();
                                    QByteArray img  = subQuery.value("tile").toByteArray();
                                    int type        = subQuery.value("type").toInt();
                                    //-- Save tile
                                    exportQuery.prepare("INSERT INTO Tiles(hash, format, tile, size, type, date) VALUES(?, ?, ?, ?, ?, ?)");
                                    exportQuery.addBindValue(hash);
                                    exportQuery.addBindValue(format);
                                    exportQuery.addBindValue(img);
                                    exportQuery.addBindValue(img.size());
                                    exportQuery.addBindValue(type);
                                    exportQuery.addBindValue(QDateTime::currentDateTime().toTime_t());
                                    if(exportQuery.exec()) {
                                        quint64 exportTileID = exportQuery.lastInsertId().toULongLong();
                                        QString s = QString("INSERT INTO SetTiles(tileID, setID) VALUES(%1, %2)").arg(exportTileID).arg(exportSetID);
                                        exportQuery.prepare(s);
                                        exportQuery.exec();
Gus Grubba's avatar
Gus Grubba committed
983 984
                                        currentCount++;
                                        task->setProgress((int)((double)currentCount / (double)tileCount * 100.0));
985 986 987 988 989
                                    }
                                }
                            }
                        }
                    }
Gus Grubba's avatar
Gus Grubba committed
990
                    dbExport->commit();
991 992 993 994 995 996 997 998 999 1000
                }
            }
        } else {
            task->setError("Error creating export database");
        }
    } else {
        qCritical() << "Map Cache SQL error (create export database):" << dbExport->lastError();
        task->setError("Error opening export database");
    }
    delete dbExport;
Gus Grubba's avatar
Gus Grubba committed
1001
    QSqlDatabase::removeDatabase(kExportSession);
Gus Grubba's avatar
Gus Grubba committed
1002
    task->setExportCompleted();
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
}

//-----------------------------------------------------------------------------
bool QGCCacheWorker::_testTask(QGCMapTask* mtask)
{
    if(!_valid) {
        mtask->setError("No Cache Database");
        return false;
    }
    return true;
}

dogmaphobic's avatar
dogmaphobic committed
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
//-----------------------------------------------------------------------------
bool
QGCCacheWorker::_init()
{
    _failed = false;
    if(!_databasePath.isEmpty()) {
        qCDebug(QGCTileCacheLog) << "Mapping cache directory:" << _databasePath;
        //-- Initialize Database
        _db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", kSession));
        _db->setDatabaseName(_databasePath);
        _db->setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
        if (_db->open()) {
1027 1028 1029 1030
            _valid = _createDB(_db);
            if(!_valid) {
                _failed = true;
            }
dogmaphobic's avatar
dogmaphobic committed
1031 1032 1033 1034 1035
        } else {
            qCritical() << "Map Cache SQL error (init() open db):" << _db->lastError();
            _failed = true;
        }
        delete _db;
1036
        _db = nullptr;
dogmaphobic's avatar
dogmaphobic committed
1037 1038 1039 1040 1041
        QSqlDatabase::removeDatabase(kSession);
    } else {
        qCritical() << "Could not find suitable cache directory.";
        _failed = true;
    }
1042
    _testInternet();
dogmaphobic's avatar
dogmaphobic committed
1043 1044 1045 1046
    return _failed;
}

//-----------------------------------------------------------------------------
1047 1048
bool
QGCCacheWorker::_createDB(QSqlDatabase* db, bool createDefault)
dogmaphobic's avatar
dogmaphobic committed
1049
{
1050 1051
    bool res = false;
    QSqlQuery query(*db);
dogmaphobic's avatar
dogmaphobic committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    if(!query.exec(
        "CREATE TABLE IF NOT EXISTS Tiles ("
        "tileID INTEGER PRIMARY KEY NOT NULL, "
        "hash TEXT NOT NULL UNIQUE, "
        "format TEXT NOT NULL, "
        "tile BLOB NULL, "
        "size INTEGER, "
        "type INTEGER, "
        "date INTEGER DEFAULT 0)"))
    {
        qWarning() << "Map Cache SQL error (create Tiles db):" << query.lastError().text();
    } else {
        if(!query.exec(
            "CREATE TABLE IF NOT EXISTS TileSets ("
            "setID INTEGER PRIMARY KEY NOT NULL, "
            "name TEXT NOT NULL UNIQUE, "
            "typeStr TEXT, "
            "topleftLat REAL DEFAULT 0.0, "
            "topleftLon REAL DEFAULT 0.0, "
            "bottomRightLat REAL DEFAULT 0.0, "
            "bottomRightLon REAL DEFAULT 0.0, "
            "minZoom INTEGER DEFAULT 3, "
            "maxZoom INTEGER DEFAULT 3, "
            "type INTEGER DEFAULT -1, "
            "numTiles INTEGER DEFAULT 0, "
            "defaultSet INTEGER DEFAULT 0, "
            "date INTEGER DEFAULT 0)"))
        {
            qWarning() << "Map Cache SQL error (create TileSets db):" << query.lastError().text();
        } else {
            if(!query.exec(
                "CREATE TABLE IF NOT EXISTS SetTiles ("
                "setID INTEGER, "
                "tileID INTEGER)"))
            {
                qWarning() << "Map Cache SQL error (create SetTiles db):" << query.lastError().text();
            } else {
                if(!query.exec(
                    "CREATE TABLE IF NOT EXISTS TilesDownload ("
                    "setID INTEGER, "
                    "hash TEXT NOT NULL UNIQUE, "
                    "type INTEGER, "
                    "x INTEGER, "
                    "y INTEGER, "
                    "z INTEGER, "
                    "state INTEGER DEFAULT 0)"))
                {
                    qWarning() << "Map Cache SQL error (create TilesDownload db):" << query.lastError().text();
                } else {
                    //-- Database it ready for use
1102
                    res = true;
dogmaphobic's avatar
dogmaphobic committed
1103 1104 1105 1106 1107
                }
            }
        }
    }
    //-- Create default tile set
1108
    if(res && createDefault) {
dogmaphobic's avatar
dogmaphobic committed
1109 1110 1111
        QString s = QString("SELECT name FROM TileSets WHERE name = \"%1\"").arg(kDefaultSet);
        if(query.exec(s)) {
            if(!query.next()) {
dogmaphobic's avatar
dogmaphobic committed
1112
                query.prepare("INSERT INTO TileSets(name, defaultSet, date) VALUES(?, ?, ?)");
dogmaphobic's avatar
dogmaphobic committed
1113 1114 1115 1116
                query.addBindValue(kDefaultSet);
                query.addBindValue(1);
                query.addBindValue(QDateTime::currentDateTime().toTime_t());
                if(!query.exec()) {
1117 1118
                    qWarning() << "Map Cache SQL error (Creating default tile set):" << db->lastError();
                    res = false;
dogmaphobic's avatar
dogmaphobic committed
1119 1120 1121
                }
            }
        } else {
1122
            qWarning() << "Map Cache SQL error (Looking for default tile set):" << db->lastError();
dogmaphobic's avatar
dogmaphobic committed
1123 1124
        }
    }
1125
    if(!res) {
dogmaphobic's avatar
dogmaphobic committed
1126 1127 1128
        QFile file(_databasePath);
        file.remove();
    }
1129
    return res;
dogmaphobic's avatar
dogmaphobic committed
1130
}
1131 1132 1133 1134 1135

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_testInternet()
{
Gus Grubba's avatar
Gus Grubba committed
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    /*
        To test if you have Internet connection, the code tests a connection to
        8.8.8.8:53 (google DNS). It appears that some routers are now blocking TCP
        connections to port 53. So instead, we use a TCP connection to "github.com"
        (80). On exit, if the look up for “github.com” is under way, a call to abort
        the lookup is made. This abort call on Android has no effect, and the code
        blocks for a full minute. So to work around the issue, we continue a direct
        TCP connection to 8.8.8.8:53 on Android and do the lookup/connect on the
        other platforms.
    */
#if defined(__android__)
    QTcpSocket socket;
    socket.connectToHost("8.8.8.8", 53);
    if (socket.waitForConnected(2000)) {
        qCDebug(QGCTileCacheLog) << "Yes Internet Access";
        emit internetStatus(true);
        return;
    }
    qWarning() << "No Internet Access";
    emit internetStatus(false);
#else
1157 1158 1159
    if(!_hostLookupID) {
        _hostLookupID = QHostInfo::lookupHost("www.github.com", this, SLOT(_lookupReady(QHostInfo)));
    }
Gus Grubba's avatar
Gus Grubba committed
1160
#endif
1161 1162 1163 1164 1165 1166
}

//-----------------------------------------------------------------------------
void
QGCCacheWorker::_lookupReady(QHostInfo info)
{
Gus Grubba's avatar
Gus Grubba committed
1167 1168 1169
#if defined(__android__)
    Q_UNUSED(info);
#else
1170 1171 1172
    _hostLookupID = 0;
    if(info.error() == QHostInfo::NoError && info.addresses().size()) {
        QTcpSocket socket;
1173 1174 1175
        QNetworkProxy tempProxy;
        tempProxy.setType(QNetworkProxy::DefaultProxy);
        socket.setProxy(tempProxy);
1176 1177 1178 1179 1180 1181
        socket.connectToHost(info.addresses().first(), 80);
        if (socket.waitForConnected(2000)) {
            qCDebug(QGCTileCacheLog) << "Yes Internet Access";
            emit internetStatus(true);
            return;
        }
1182
    }
1183
    qDebug() << "No Internet Access";
1184
    emit internetStatus(false);
Gus Grubba's avatar
Gus Grubba committed
1185
#endif
1186
}