QGCMapEngine.cpp 13.1 KB
Newer Older
1 2
/****************************************************************************
 *
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
 *
15
 *   @author Gus Grubba <gus@auterion.com>
dogmaphobic's avatar
dogmaphobic committed
16 17
 *
 */
18 19 20
#include "QGCApplication.h"
#include "AppSettings.h"
#include "SettingsManager.h"
dogmaphobic's avatar
dogmaphobic committed
21 22 23 24 25

#include <math.h>
#include <QSettings>
#include <QStandardPaths>
#include <QDir>
Gus Grubba's avatar
Gus Grubba committed
26
#include <stdio.h>
dogmaphobic's avatar
dogmaphobic committed
27 28 29 30 31 32 33 34 35 36 37

#include "QGCMapEngine.h"
#include "QGCMapTileSet.h"

Q_DECLARE_METATYPE(QGCMapTask::TaskType)
Q_DECLARE_METATYPE(QGCTile)
Q_DECLARE_METATYPE(QList<QGCTile*>)

static const char* kDbFileName = "qgcMapCache.db";
static QLocale kLocale;

dogmaphobic's avatar
dogmaphobic committed
38
#define CACHE_PATH_VERSION  "300"
39

dogmaphobic's avatar
dogmaphobic committed
40 41
struct stQGeoTileCacheQGCMapTypes {
    const char* name;
42
    QString type;
dogmaphobic's avatar
dogmaphobic committed
43 44 45 46 47 48 49
};

static const char* kMaxDiskCacheKey = "MaxDiskCache";
static const char* kMaxMemCacheKey  = "MaxMemoryCache";

//-----------------------------------------------------------------------------
// Singleton
50
static QGCMapEngine* kMapEngine = nullptr;
dogmaphobic's avatar
dogmaphobic committed
51 52 53 54 55 56 57 58 59 60 61 62
QGCMapEngine*
getQGCMapEngine()
{
    if(!kMapEngine)
        kMapEngine = new QGCMapEngine();
    return kMapEngine;
}

//-----------------------------------------------------------------------------
void
destroyMapEngine()
{
63 64
    delete kMapEngine;
    kMapEngine = nullptr;
dogmaphobic's avatar
dogmaphobic committed
65 66 67 68
}

//-----------------------------------------------------------------------------
QGCMapEngine::QGCMapEngine()
69
    : _urlFactory(new UrlFactory())
dogmaphobic's avatar
dogmaphobic committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#ifdef WE_ARE_KOSHER
    //-- TODO: Get proper version
    #if defined Q_OS_MAC
        , _userAgent("QGroundControl (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/2.9.0")
    #elif defined Q_OS_WIN32
        , _userAgent("QGroundControl (Windows; Windows NT 6.0) (KHTML, like Gecko) Version/2.9.0")
    #else
        , _userAgent("QGroundControl (X11; Ubuntu; Linux x86_64) (KHTML, like Gecko) Version/2.9.0")
    #endif
#else
    #if defined Q_OS_MAC
        , _userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0")
    #elif defined Q_OS_WIN32
        , _userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0")
    #else
        , _userAgent("Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0")
    #endif
#endif
    , _maxDiskCache(0)
    , _maxMemCache(0)
    , _prunning(false)
dogmaphobic's avatar
dogmaphobic committed
91
    , _cacheWasReset(false)
92
    , _isInternetActive(false)
dogmaphobic's avatar
dogmaphobic committed
93 94 95 96
{
    qRegisterMetaType<QGCMapTask::TaskType>();
    qRegisterMetaType<QGCTile>();
    qRegisterMetaType<QList<QGCTile*>>();
97 98
    connect(&_worker, &QGCCacheWorker::updateTotals,   this, &QGCMapEngine::_updateTotals);
    connect(&_worker, &QGCCacheWorker::internetStatus, this, &QGCMapEngine::_internetStatus);
dogmaphobic's avatar
dogmaphobic committed
99 100 101 102 103 104 105
}

//-----------------------------------------------------------------------------
QGCMapEngine::~QGCMapEngine()
{
    _worker.quit();
    _worker.wait();
106 107
    delete _urlFactory;
    _urlFactory = nullptr;
dogmaphobic's avatar
dogmaphobic committed
108 109
}

dogmaphobic's avatar
dogmaphobic committed
110 111 112 113 114 115 116 117 118 119 120
//-----------------------------------------------------------------------------
void
QGCMapEngine::_checkWipeDirectory(const QString& dirPath)
{
    QDir dir(dirPath);
    if (dir.exists(dirPath)) {
        _cacheWasReset = true;
        _wipeDirectory(dirPath);
    }
}

dogmaphobic's avatar
dogmaphobic committed
121 122
//-----------------------------------------------------------------------------
void
dogmaphobic's avatar
dogmaphobic committed
123
QGCMapEngine::_wipeOldCaches()
dogmaphobic's avatar
dogmaphobic committed
124
{
dogmaphobic's avatar
dogmaphobic committed
125 126 127 128
    QString oldCacheDir;
#ifdef __mobile__
    oldCacheDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)      + QLatin1String("/QGCMapCache55");
#else
129
    oldCacheDir = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/QGCMapCache55");
dogmaphobic's avatar
dogmaphobic committed
130
#endif
dogmaphobic's avatar
dogmaphobic committed
131
    _checkWipeDirectory(oldCacheDir);
dogmaphobic's avatar
dogmaphobic committed
132
#ifdef __mobile__
dogmaphobic's avatar
dogmaphobic committed
133
    oldCacheDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)      + QLatin1String("/QGCMapCache100");
dogmaphobic's avatar
dogmaphobic committed
134
#else
135
    oldCacheDir = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/QGCMapCache100");
136
#endif
dogmaphobic's avatar
dogmaphobic committed
137
    _checkWipeDirectory(oldCacheDir);
dogmaphobic's avatar
dogmaphobic committed
138 139 140 141 142 143 144 145
}

//-----------------------------------------------------------------------------
void
QGCMapEngine::init()
{
    //-- Delete old style caches (if present)
    _wipeOldCaches();
146 147 148 149
    //-- Figure out cache path
#ifdef __mobile__
    QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)      + QLatin1String("/QGCMapCache" CACHE_PATH_VERSION);
#else
150
    QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/QGCMapCache" CACHE_PATH_VERSION);
dogmaphobic's avatar
dogmaphobic committed
151 152 153
#endif
    if(!QDir::root().mkpath(cacheDir)) {
        qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
154
        cacheDir = QDir::homePath() + QStringLiteral("/.qgcmapscache/");
dogmaphobic's avatar
dogmaphobic committed
155 156 157 158 159 160 161 162 163
        if(!QDir::root().mkpath(cacheDir)) {
            qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
            cacheDir.clear();
        }
    }
    _cachePath = cacheDir;
    if(!_cachePath.isEmpty()) {
        _cacheFile = kDbFileName;
        _worker.setDatabaseFile(_cachePath + "/" + _cacheFile);
164
        qDebug() << "Map Cache in:" << _cachePath << "/" << _cacheFile;
dogmaphobic's avatar
dogmaphobic committed
165 166 167 168 169 170 171
    } else {
        qCritical() << "Could not find suitable map cache directory.";
    }
    QGCMapTask* task = new QGCMapTask(QGCMapTask::taskInit);
    _worker.enqueueTask(task);
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
//-----------------------------------------------------------------------------
bool
QGCMapEngine::_wipeDirectory(const QString& dirPath)
{
    bool result = true;
    QDir dir(dirPath);
    if (dir.exists(dirPath)) {
        Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
            if (info.isDir()) {
                result = _wipeDirectory(info.absoluteFilePath());
            } else {
                result = QFile::remove(info.absoluteFilePath());
            }
            if (!result) {
                return result;
            }
        }
        result = dir.rmdir(dirPath);
    }
    return result;
}

dogmaphobic's avatar
dogmaphobic committed
194 195 196 197 198 199 200 201 202
//-----------------------------------------------------------------------------
void
QGCMapEngine::addTask(QGCMapTask* task)
{
    _worker.enqueueTask(task);
}

//-----------------------------------------------------------------------------
void
203
QGCMapEngine::cacheTile(QString type, int x, int y, int z, const QByteArray& image, const QString &format, qulonglong set)
dogmaphobic's avatar
dogmaphobic committed
204 205 206 207 208 209 210
{
    QString hash = getTileHash(type, x, y, z);
    cacheTile(type, hash, image, format, set);
}

//-----------------------------------------------------------------------------
void
211
QGCMapEngine::cacheTile(QString type, const QString& hash, const QByteArray& image, const QString& format, qulonglong set)
dogmaphobic's avatar
dogmaphobic committed
212
{
213 214 215 216 217 218
    AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings();
    //-- If we are allowed to persist data, save tile to cache
    if(!appSettings->disableAllPersistence()->rawValue().toBool()) {
        QGCSaveTileTask* task = new QGCSaveTileTask(new QGCCacheTile(hash, image, format, type, set));
        _worker.enqueueTask(task);
    }
dogmaphobic's avatar
dogmaphobic committed
219 220 221 222
}

//-----------------------------------------------------------------------------
QString
223
QGCMapEngine::getTileHash(QString type, int x, int y, int z)
dogmaphobic's avatar
dogmaphobic committed
224
{
225
    return QString::asprintf("%010d%08d%08d%03d", getQGCMapEngine()->urlFactory()->getIdFromType(type), x, y, z);
dogmaphobic's avatar
dogmaphobic committed
226 227 228
}

//-----------------------------------------------------------------------------
229
QString
dogmaphobic's avatar
dogmaphobic committed
230 231
QGCMapEngine::hashToType(const QString& hash)
{
232 233
    QString type = hash.mid(0,10);
    return urlFactory()->getTypeFromId(type.toInt());
dogmaphobic's avatar
dogmaphobic committed
234 235 236
}

//-----------------------------------------------------------------------------
237 238
	QGCFetchTileTask*
QGCMapEngine::createFetchTileTask(QString type, int x, int y, int z)
dogmaphobic's avatar
dogmaphobic committed
239
{
240 241 242
	QString hash = getTileHash(type, x, y, z);
	QGCFetchTileTask* task = new QGCFetchTileTask(hash);
	return task;
dogmaphobic's avatar
dogmaphobic committed
243 244
}

245
//-----------------------------------------------------------------------------
246 247
	QGCTileSet
QGCMapEngine::getTileCount(int zoom, double topleftLon, double topleftLat, double bottomRightLon, double bottomRightLat, QString mapType)
248
{
249 250
	if(zoom <  1) zoom = 1;
	if(zoom > MAX_MAP_ZOOM) zoom = MAX_MAP_ZOOM;
251

252
    return getQGCMapEngine()->urlFactory()->getTileCount(zoom, topleftLon, topleftLat, bottomRightLon, bottomRightLat, mapType);
253 254
}

dogmaphobic's avatar
dogmaphobic committed
255 256 257 258 259

//-----------------------------------------------------------------------------
QStringList
QGCMapEngine::getMapNameList()
{
260
    return QStringList(getQGCMapEngine()->urlFactory()->getProviderTable().keys());
dogmaphobic's avatar
dogmaphobic committed
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
}

//-----------------------------------------------------------------------------
quint32
QGCMapEngine::getMaxDiskCache()
{
    if(!_maxDiskCache) {
        QSettings settings;
        _maxDiskCache = settings.value(kMaxDiskCacheKey, 1024).toUInt();
    }
    return _maxDiskCache;
}

//-----------------------------------------------------------------------------
void
QGCMapEngine::setMaxDiskCache(quint32 size)
{
    QSettings settings;
    settings.setValue(kMaxDiskCacheKey, size);
    _maxDiskCache = size;
}

//-----------------------------------------------------------------------------
quint32
QGCMapEngine::getMaxMemCache()
{
    if(!_maxMemCache) {
        QSettings settings;
#ifdef __mobile__
        _maxMemCache = settings.value(kMaxMemCacheKey, 16).toUInt();
#else
        _maxMemCache = settings.value(kMaxMemCacheKey, 128).toUInt();
#endif
    }
295 296 297
    //-- Size in MB
    if(_maxMemCache > 1024)
        _maxMemCache = 1024;
dogmaphobic's avatar
dogmaphobic committed
298 299 300 301 302 303 304
    return _maxMemCache;
}

//-----------------------------------------------------------------------------
void
QGCMapEngine::setMaxMemCache(quint32 size)
{
305 306 307
    //-- Size in MB
    if(size > 1024)
        size = 1024;
dogmaphobic's avatar
dogmaphobic committed
308 309 310 311 312 313 314 315 316 317 318 319
    QSettings settings;
    settings.setValue(kMaxMemCacheKey, size);
    _maxMemCache = size;
}

//-----------------------------------------------------------------------------
QString
QGCMapEngine::bigSizeToString(quint64 size)
{
    if(size < 1024)
        return kLocale.toString(size);
    else if(size < 1024 * 1024)
320
        return kLocale.toString(static_cast<double>(size) / 1024.0, 'f', 1) + "kB";
dogmaphobic's avatar
dogmaphobic committed
321
    else if(size < 1024 * 1024 * 1024)
322
        return kLocale.toString(static_cast<double>(size) / (1024.0 * 1024.0), 'f', 1) + "MB";
dogmaphobic's avatar
dogmaphobic committed
323
    else if(size < 1024.0 * 1024.0 * 1024.0 * 1024.0)
324
        return kLocale.toString(static_cast<double>(size) / (1024.0 * 1024.0 * 1024.0), 'f', 1) + "GB";
dogmaphobic's avatar
dogmaphobic committed
325
    else
326 327 328 329 330 331 332 333 334 335 336 337 338
        return kLocale.toString(static_cast<double>(size) / (1024.0 * 1024.0 * 1024.0 * 1024), 'f', 1) + "TB";
}

//-----------------------------------------------------------------------------
QString
QGCMapEngine::storageFreeSizeToString(quint64 size_MB)
{
    if(size_MB < 1024)
        return kLocale.toString(static_cast<double>(size_MB) , 'f', 0) + " MB";
    else if(size_MB < 1024.0 * 1024.0)
        return kLocale.toString(static_cast<double>(size_MB) / (1024.0), 'f', 2) + " GB";
    else
        return kLocale.toString(static_cast<double>(size_MB) / (1024.0 * 1024), 'f', 2) + " TB";
dogmaphobic's avatar
dogmaphobic committed
339 340 341 342
}

//-----------------------------------------------------------------------------
QString
dogmaphobic's avatar
dogmaphobic committed
343
QGCMapEngine::numberToString(quint64 number)
dogmaphobic's avatar
dogmaphobic committed
344 345 346 347 348 349 350 351 352
{
    return kLocale.toString(number);
}

//-----------------------------------------------------------------------------
void
QGCMapEngine::_updateTotals(quint32 totaltiles, quint64 totalsize, quint32 defaulttiles, quint64 defaultsize)
{
    emit updateTotals(totaltiles, totalsize, defaulttiles, defaultsize);
353
    quint64 maxSize = static_cast<quint64>(getMaxDiskCache()) * 1024L * 1024L;
dogmaphobic's avatar
dogmaphobic committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    if(!_prunning && defaultsize > maxSize) {
        //-- Prune Disk Cache
        _prunning = true;
        QGCPruneCacheTask* task = new QGCPruneCacheTask(defaultsize - maxSize);
        connect(task, &QGCPruneCacheTask::pruned, this, &QGCMapEngine::_pruned);
        getQGCMapEngine()->addTask(task);
    }
}
//-----------------------------------------------------------------------------
void
QGCMapEngine::_pruned()
{
    _prunning = false;
}

//-----------------------------------------------------------------------------
int
371
QGCMapEngine::concurrentDownloads(QString type)
dogmaphobic's avatar
dogmaphobic committed
372
{
373 374 375 376 377
    Q_UNUSED(type);
    // TODO : We may want different values depending on
    // the provider here, let it like this as all provider are set to 12
    // at the moment
    return 12;
dogmaphobic's avatar
dogmaphobic committed
378 379 380 381 382 383 384 385 386 387
}

//-----------------------------------------------------------------------------
QGCCreateTileSetTask::~QGCCreateTileSetTask()
{
    //-- If not sent out, delete it
    if(!_saved && _tileSet)
        delete _tileSet;
}

388 389 390 391
//-----------------------------------------------------------------------------
void
QGCMapEngine::testInternet()
{
392 393 394 395
    if(qgcApp()->toolbox()->settingsManager()->appSettings()->checkInternet()->rawValue().toBool())
        getQGCMapEngine()->addTask(new QGCTestInternetTask());
    else
        _internetStatus(true);
396 397 398 399 400 401
}

//-----------------------------------------------------------------------------
void
QGCMapEngine::_internetStatus(bool active)
{
402 403 404 405
    if(_isInternetActive != active) {
        _isInternetActive = active;
        emit internetUpdated();
    }
406 407
}

dogmaphobic's avatar
dogmaphobic committed
408
// Resolution math: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale