QGIS API Documentation  3.10.0-A Coruña (6c816b4204)
qgsabstractcontentcache.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgsabstractcontentcache.h
3  ---------------
4  begin : December 2018
5  copyright : (C) 2018 by Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 #ifndef QGSABSTRACTCONTENTCACHE_H
19 #define QGSABSTRACTCONTENTCACHE_H
20 
21 #include "qgis_core.h"
22 #include "qgis_sip.h"
23 #include "qgslogger.h"
24 #include "qgsmessagelog.h"
25 #include "qgsapplication.h"
27 
28 #include <QObject>
29 #include <QMutex>
30 #include <QCache>
31 #include <QSet>
32 #include <QDateTime>
33 #include <QList>
35 #include <QNetworkReply>
36 
48 {
49  public:
50 
54  QgsAbstractContentCacheEntry( const QString &path ) ;
55 
56  virtual ~QgsAbstractContentCacheEntry() = default;
57 
61  QgsAbstractContentCacheEntry &operator=( const QgsAbstractContentCacheEntry &rh ) = delete;
62 
66  QString path;
67 
69  QDateTime fileModified;
70 
73 
75  int mFileModifiedCheckTimeout = 30000;
76 
81  QgsAbstractContentCacheEntry *nextEntry = nullptr;
82 
87  QgsAbstractContentCacheEntry *previousEntry = nullptr;
88 
89  bool operator==( const QgsAbstractContentCacheEntry &other ) const
90  {
91  return other.path == path;
92  }
93 
97  virtual int dataSize() const = 0;
98 
102  virtual void dump() const = 0;
103 
104  protected:
105 
111  virtual bool isEqual( const QgsAbstractContentCacheEntry *other ) const = 0;
112 
113  private:
114 #ifdef SIP_RUN
116 #endif
117 
118 };
119 
130 class CORE_EXPORT QgsAbstractContentCacheBase: public QObject
131 {
132  Q_OBJECT
133 
134  public:
135 
139  QgsAbstractContentCacheBase( QObject *parent );
140 
141  signals:
142 
146  void remoteContentFetched( const QString &url );
147 
148  protected:
149 
154  virtual bool checkReply( QNetworkReply *reply, const QString &path ) const
155  {
156  Q_UNUSED( reply )
157  Q_UNUSED( path )
158  return true;
159  }
160 
161  protected slots:
162 
169  virtual void onRemoteContentFetched( const QString &url, bool success );
170 
171 };
172 
173 #ifndef SIP_RUN
174 
188 template<class T>
190 {
191 
192  public:
193 
205  QgsAbstractContentCache( QObject *parent SIP_TRANSFERTHIS = nullptr,
206  const QString &typeString = QString(),
207  long maxCacheSize = 20000000,
208  int fileModifiedCheckTimeout = 30000 )
209  : QgsAbstractContentCacheBase( parent )
210  , mMutex( QMutex::Recursive )
211  , mMaxCacheSize( maxCacheSize )
212  , mFileModifiedCheckTimeout( fileModifiedCheckTimeout )
213  , mTypeString( typeString.isEmpty() ? QObject::tr( "Content" ) : typeString )
214  {
215  }
216 
218  {
219  qDeleteAll( mEntryLookup );
220  }
221 
222  protected:
223 
228  {
229  //only one entry in cache
230  if ( mLeastRecentEntry == mMostRecentEntry )
231  {
232  return;
233  }
234  T *entry = mLeastRecentEntry;
235  while ( entry && ( mTotalSize > mMaxCacheSize ) )
236  {
237  T *bkEntry = entry;
238  entry = static_cast< T * >( entry->nextEntry );
239 
240  takeEntryFromList( bkEntry );
241  mEntryLookup.remove( bkEntry->path, bkEntry );
242  mTotalSize -= bkEntry->dataSize();
243  delete bkEntry;
244  }
245  }
246 
260  QByteArray getContent( const QString &path, const QByteArray &missingContent, const QByteArray &fetchingContent, bool blocking = false ) const
261  {
262  // is it a path to local file?
263  QFile file( path );
264  if ( file.exists() )
265  {
266  if ( file.open( QIODevice::ReadOnly ) )
267  {
268  return file.readAll();
269  }
270  else
271  {
272  return missingContent;
273  }
274  }
275 
276  // maybe it's an embedded base64 string
277  if ( path.startsWith( QLatin1String( "base64:" ), Qt::CaseInsensitive ) )
278  {
279  QByteArray base64 = path.mid( 7 ).toLocal8Bit(); // strip 'base64:' prefix
280  return QByteArray::fromBase64( base64, QByteArray::OmitTrailingEquals );
281  }
282 
283  // maybe it's a url...
284  if ( !path.contains( QLatin1String( "://" ) ) ) // otherwise short, relative SVG paths might be considered URLs
285  {
286  return missingContent;
287  }
288 
289  QUrl url( path );
290  if ( !url.isValid() )
291  {
292  return missingContent;
293  }
294 
295  // check whether it's a url pointing to a local file
296  if ( url.scheme().compare( QLatin1String( "file" ), Qt::CaseInsensitive ) == 0 )
297  {
298  file.setFileName( url.toLocalFile() );
299  if ( file.exists() )
300  {
301  if ( file.open( QIODevice::ReadOnly ) )
302  {
303  return file.readAll();
304  }
305  }
306 
307  // not found...
308  return missingContent;
309  }
310 
311  QMutexLocker locker( &mMutex );
312 
313  // already a request in progress for this url
314  if ( mPendingRemoteUrls.contains( path ) )
315  {
316  // it's a non blocking request so return fetching content
317  if ( !blocking )
318  {
319  return fetchingContent;
320  }
321 
322  // it's a blocking request so try to find the task and wait for task finished
323  const auto constActiveTasks = QgsApplication::taskManager()->activeTasks();
324  for ( QgsTask *task : constActiveTasks )
325  {
326  // the network content fetcher task's description ends with the path
327  if ( !task->description().endsWith( path ) )
328  {
329  continue;
330  }
331 
332  // cast task to network content fetcher task
333  QgsNetworkContentFetcherTask *ncfTask = qobject_cast<QgsNetworkContentFetcherTask *>( task );
334  if ( ncfTask )
335  {
336  // wait for task finished
337  if ( waitForTaskFinished( ncfTask ) )
338  {
339  if ( mRemoteContentCache.contains( path ) )
340  {
341  // We got the file!
342  return *mRemoteContentCache[ path ];
343  }
344  }
345  }
346  // task found, no needs to continue
347  break;
348  }
349  // if no content returns the content is probably in remote content cache
350  // or a new task will be created
351  }
352 
353  if ( mRemoteContentCache.contains( path ) )
354  {
355  // already fetched this content - phew. Just return what we already got.
356  return *mRemoteContentCache[ path ];
357  }
358 
359  mPendingRemoteUrls.insert( path );
360  //fire up task to fetch content in background
361  QNetworkRequest request( url );
362  QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsAbstractContentCache<%1>" ).arg( mTypeString ) );
363  request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
364  request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );
365 
367  connect( task, &QgsNetworkContentFetcherTask::fetched, this, [this, task, path, missingContent]
368  {
369  QMutexLocker locker( &mMutex );
370 
371  QNetworkReply *reply = task->reply();
372  if ( !reply )
373  {
374  // canceled
375  QMetaObject::invokeMethod( const_cast< QgsAbstractContentCacheBase * >( qobject_cast< const QgsAbstractContentCacheBase * >( this ) ), "onRemoteContentFetched", Qt::QueuedConnection, Q_ARG( QString, path ), Q_ARG( bool, false ) );
376  return;
377  }
378 
379  if ( reply->error() != QNetworkReply::NoError )
380  {
381  QgsMessageLog::logMessage( tr( "%3 request failed [error: %1 - url: %2]" ).arg( reply->errorString(), path, mTypeString ), mTypeString );
382  return;
383  }
384 
385  bool ok = true;
386 
387  QVariant status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
388  if ( !status.isNull() && status.toInt() >= 400 )
389  {
390  QVariant phrase = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute );
391  QgsMessageLog::logMessage( tr( "%4 request error [status: %1 - reason phrase: %2] for %3" ).arg( status.toInt() ).arg( phrase.toString(), path, mTypeString ), mTypeString );
392  mRemoteContentCache.insert( path, new QByteArray( missingContent ) );
393  ok = false;
394  }
395 
396  if ( !checkReply( reply, path ) )
397  {
398  mRemoteContentCache.insert( path, new QByteArray( missingContent ) );
399  ok = false;
400  }
401 
402  if ( ok )
403  {
404  // read the content data
405  mRemoteContentCache.insert( path, new QByteArray( reply->readAll() ) );
406  }
407  QMetaObject::invokeMethod( const_cast< QgsAbstractContentCacheBase * >( qobject_cast< const QgsAbstractContentCacheBase * >( this ) ), "onRemoteContentFetched", Qt::QueuedConnection, Q_ARG( QString, path ), Q_ARG( bool, true ) );
408  } );
409 
411 
412  // if blocking, wait for finished
413  if ( blocking )
414  {
415  if ( waitForTaskFinished( task ) )
416  {
417  if ( mRemoteContentCache.contains( path ) )
418  {
419  // We got the file!
420  return *mRemoteContentCache[ path ];
421  }
422  }
423  }
424  return fetchingContent;
425  }
426 
427  void onRemoteContentFetched( const QString &url, bool success ) override
428  {
429  QMutexLocker locker( &mMutex );
430  mPendingRemoteUrls.remove( url );
431 
432  T *nextEntry = mLeastRecentEntry;
433  while ( T *entry = nextEntry )
434  {
435  nextEntry = static_cast< T * >( entry->nextEntry );
436  if ( entry->path == url )
437  {
438  takeEntryFromList( entry );
439  mEntryLookup.remove( entry->path, entry );
440  mTotalSize -= entry->dataSize();
441  delete entry;
442  }
443  }
444 
445  if ( success )
446  emit remoteContentFetched( url );
447  }
448 
460  {
461  // First step, waiting for task running
462  if ( task->status() != QgsTask::Running )
463  {
464  QEventLoop loop;
465  connect( task, &QgsNetworkContentFetcherTask::begun, &loop, &QEventLoop::quit );
466  if ( task->status() != QgsTask::Running )
467  loop.exec();
468  }
469 
470  // Second step, wait 5 seconds for task finished
471  if ( task->waitForFinished( 5000 ) )
472  {
473  // The wait did not time out
474  // Third step, check status as complete
475  if ( task->status() == QgsTask::Complete )
476  {
477  // Fourth step, force the signal fetched to be sure reply has been checked
478  task->fetched();
479  return true;
480  }
481  }
482  return false;
483  }
484 
494  T *findExistingEntry( T *entryTemplate )
495  {
496  //search entries in mEntryLookup
497  const QString path = entryTemplate->path;
498  T *currentEntry = nullptr;
499  const QList<T *> entries = mEntryLookup.values( path );
500  QDateTime modified;
501  for ( T *cacheEntry : entries )
502  {
503  if ( cacheEntry->isEqual( entryTemplate ) )
504  {
505  if ( mFileModifiedCheckTimeout <= 0 || cacheEntry->fileModifiedLastCheckTimer.hasExpired( mFileModifiedCheckTimeout ) )
506  {
507  if ( !modified.isValid() )
508  modified = QFileInfo( path ).lastModified();
509 
510  if ( cacheEntry->fileModified != modified )
511  continue;
512  else
513  cacheEntry->fileModifiedLastCheckTimer.restart();
514  }
515  currentEntry = cacheEntry;
516  break;
517  }
518  }
519 
520  //if not found: insert entryTemplate as a new entry
521  if ( !currentEntry )
522  {
523  currentEntry = insertCacheEntry( entryTemplate );
524  }
525  else
526  {
527  delete entryTemplate;
528  entryTemplate = nullptr;
529  takeEntryFromList( currentEntry );
530  if ( !mMostRecentEntry ) //list is empty
531  {
532  mMostRecentEntry = currentEntry;
533  mLeastRecentEntry = currentEntry;
534  }
535  else
536  {
537  mMostRecentEntry->nextEntry = currentEntry;
538  currentEntry->previousEntry = mMostRecentEntry;
539  currentEntry->nextEntry = nullptr;
540  mMostRecentEntry = currentEntry;
541  }
542  }
543 
544  //debugging
545  //printEntryList();
546 
547  return currentEntry;
548  }
549 
550  mutable QMutex mMutex;
552  long mTotalSize = 0;
553 
555  long mMaxCacheSize = 20000000;
556 
557  private:
558 
564  T *insertCacheEntry( T *entry )
565  {
566  entry->mFileModifiedCheckTimeout = mFileModifiedCheckTimeout;
567 
568  if ( !entry->path.startsWith( QStringLiteral( "base64:" ) ) )
569  {
570  entry->fileModified = QFileInfo( entry->path ).lastModified();
571  entry->fileModifiedLastCheckTimer.start();
572  }
573 
574  mEntryLookup.insert( entry->path, entry );
575 
576  //insert to most recent place in entry list
577  if ( !mMostRecentEntry ) //inserting first entry
578  {
579  mLeastRecentEntry = entry;
580  mMostRecentEntry = entry;
581  entry->previousEntry = nullptr;
582  entry->nextEntry = nullptr;
583  }
584  else
585  {
586  entry->previousEntry = mMostRecentEntry;
587  entry->nextEntry = nullptr;
588  mMostRecentEntry->nextEntry = entry;
589  mMostRecentEntry = entry;
590  }
591 
592  trimToMaximumSize();
593  return entry;
594  }
595 
596 
600  void takeEntryFromList( T *entry )
601  {
602  if ( !entry )
603  {
604  return;
605  }
606 
607  if ( entry->previousEntry )
608  {
609  entry->previousEntry->nextEntry = entry->nextEntry;
610  }
611  else
612  {
613  mLeastRecentEntry = static_cast< T * >( entry->nextEntry );
614  }
615  if ( entry->nextEntry )
616  {
617  entry->nextEntry->previousEntry = entry->previousEntry;
618  }
619  else
620  {
621  mMostRecentEntry = static_cast< T * >( entry->previousEntry );
622  }
623  }
624 
628  void printEntryList()
629  {
630  QgsDebugMsg( QStringLiteral( "****************cache entry list*************************" ) );
631  QgsDebugMsg( "Cache size: " + QString::number( mTotalSize ) );
632  T *entry = mLeastRecentEntry;
633  while ( entry )
634  {
635  QgsDebugMsg( QStringLiteral( "***Entry:" ) );
636  entry->dump();
637  entry = entry->nextEntry;
638  }
639  }
640 
642  QMultiHash< QString, T * > mEntryLookup;
643 
645  int mFileModifiedCheckTimeout = 30000;
646 
647  //The content cache keeps the entries on a double connected list, moving the current entry to the front.
648  //That way, removing entries for more space can start with the least used objects.
649  T *mLeastRecentEntry = nullptr;
650  T *mMostRecentEntry = nullptr;
651 
652  mutable QCache< QString, QByteArray > mRemoteContentCache;
653  mutable QSet< QString > mPendingRemoteUrls;
654 
655  QString mTypeString;
656 
657  friend class TestQgsSvgCache;
658  friend class TestQgsImageCache;
659 };
660 
661 #endif
662 
663 #endif // QGSABSTRACTCONTENTCACHE_H
QByteArray getContent(const QString &path, const QByteArray &missingContent, const QByteArray &fetchingContent, bool blocking=false) const
Gets the file content corresponding to the given path.
#define QgsSetRequestInitiatorClass(request, _class)
Abstract base class for file content caches, such as SVG or raster image caches.
#define SIP_TRANSFERTHIS
Definition: qgis_sip.h:53
bool waitForTaskFinished(QgsNetworkContentFetcherTask *task) const
Blocks the current thread until the task finishes or an arbitrary setting maximum wait to 5 seconds...
void fetched()
Emitted when the network content has been fetched, regardless of whether the fetch was successful or ...
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QgsAbstractContentCache(QObject *parent=nullptr, const QString &typeString=QString(), long maxCacheSize=20000000, int fileModifiedCheckTimeout=30000)
Constructor for QgsAbstractContentCache, with the specified parent object.
Base class for entries in a QgsAbstractContentCache.
bool waitForFinished(int timeout=30000)
Blocks the current thread until the task finishes or a maximum of timeout milliseconds.
void begun()
Will be emitted by task to indicate its commencement.
void remoteContentFetched(const QString &url)
Emitted when the cache has finished retrieving content from a remote url.
QNetworkReply * reply()
Returns the network reply.
Handles HTTP network content fetching in a background task.
static QgsTaskManager * taskManager()
Returns the application&#39;s task manager, used for managing application wide background task handling...
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
Abstract base class for long running background tasks.
Task successfully completed.
void onRemoteContentFetched(const QString &url, bool success) override
Triggered after remote content (i.e.
QList< QgsTask *> activeTasks() const
Returns a list of the active (queued or running) tasks.
Task is currently running.
T * findExistingEntry(T *entryTemplate)
Returns the existing entry from the cache which matches entryTemplate (deleting entryTemplate when do...
QDateTime fileModified
Timestamp when file was last modified.
TaskStatus status() const
Returns the current task status.
A QObject derived base class for QgsAbstractContentCache.
virtual bool checkReply(QNetworkReply *reply, const QString &path) const
Runs additional checks on a network reply to ensure that the reply content is consistent with that re...
QElapsedTimer fileModifiedLastCheckTimer
Time since last check of file modified date.
bool operator==(const QgsAbstractContentCacheEntry &other) const
void trimToMaximumSize()
Removes the least used cache entries until the maximum cache size is under the predefined size limit...
QString path
Represents the absolute path to a file, a remote URL, or a base64 encoded string. ...