QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgstilecache.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgstilecache.h
3  --------------------------------------
4  Date : September 2016
5  Copyright : (C) 2016 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgstilecache.h"
17 
19 #include "qgsapplication.h"
20 #include <QAbstractNetworkCache>
21 #include <QImage>
22 #include <QUrl>
23 
24 QCache<QUrl, QImage> QgsTileCache::sTileCache( 256 );
25 QMutex QgsTileCache::sTileCacheMutex;
26 
27 
28 void QgsTileCache::insertTile( const QUrl &url, const QImage &image )
29 {
30  QMutexLocker locker( &sTileCacheMutex );
31  sTileCache.insert( url, new QImage( image ) );
32 }
33 
34 bool QgsTileCache::tile( const QUrl &url, QImage &image )
35 {
36  QMutexLocker locker( &sTileCacheMutex );
37  bool success = false;
38  if ( QImage *i = sTileCache.object( url ) )
39  {
40  image = *i;
41  success = true;
42  }
43  else if ( QgsNetworkAccessManager::instance()->cache()->metaData( url ).isValid() )
44  {
45  if ( QIODevice *data = QgsNetworkAccessManager::instance()->cache()->data( url ) )
46  {
47  QByteArray imageData = data->readAll();
48  delete data;
49 
50  image = QImage::fromData( imageData );
51 
52  // cache it as well (mutex is already locked)
53  // Check for null because it could be a redirect (see: https://github.com/qgis/QGIS/issues/24336 )
54  if ( ! image.isNull( ) )
55  {
56  sTileCache.insert( url, new QImage( image ) );
57  success = true;
58  }
59  }
60  }
61  return success;
62 }
63 
65 {
66  QMutexLocker locker( &sTileCacheMutex );
67  return sTileCache.totalCost();
68 }
69 
71 {
72  QMutexLocker locker( &sTileCacheMutex );
73  return sTileCache.maxCost();
74 }
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
static bool tile(const QUrl &url, QImage &image)
Try to access a tile and load it into "image" argument.
static int totalCost()
how many tiles are stored in the in-memory cache
static void insertTile(const QUrl &url, const QImage &image)
Add a tile image with given URL to the cache.
static int maxCost()
how many tiles can be stored in the in-memory cache