18 #include <QDirIterator>
20 using namespace Marble;
24 return cacheDirectory +
"/cache_index.idx";
28 : m_CacheDirectory( cacheDirectory ),
29 m_CacheLimit( 300 * 1024 * 1024 ),
30 m_CurrentCacheSize( 0 )
32 Q_ASSERT( !m_CacheDirectory.isEmpty() &&
"Passed empty cache directory!" );
36 if ( file.exists() ) {
37 if ( file.open( QIODevice::ReadOnly ) ) {
38 QDataStream s( &file );
42 s >> m_CurrentCacheSize;
46 qWarning(
"Unable to open cache directory %s", qPrintable( m_CacheDirectory ) );
55 if ( file.open( QIODevice::WriteOnly ) ) {
56 QDataStream s( &file );
60 s << m_CurrentCacheSize;
74 QDirIterator it( m_CacheDirectory );
77 while ( it.hasNext() ) {
83 QFile::remove( it.fileName() );
90 m_CurrentCacheSize = 0;
95 return m_Entries.contains( key );
101 if ( !m_Entries.contains( key ) )
105 QFile file( keyToFileName( key ) );
106 if ( file.open( QIODevice::ReadOnly ) ) {
107 data = file.readAll();
109 m_Entries[ key ].first = QDateTime::currentDateTime();
119 QFile file( keyToFileName( key ) );
120 if ( !file.open( QIODevice::WriteOnly ) )
124 if ( m_Entries.contains( key ) )
125 m_CurrentCacheSize -= m_Entries.value( key ).second;
131 m_Entries.insert( key, QPair<QDateTime, quint64>(QDateTime::currentDateTime(), data.length()) );
134 m_CurrentCacheSize += data.length();
144 if ( !m_Entries.contains( key ) )
149 if ( !QFile::remove( keyToFileName( key ) ) )
153 m_CurrentCacheSize -= m_Entries.value( key ).second;
156 m_Entries.remove( key );
166 QString DiscCache::keyToFileName(
const QString &key )
168 QString fileName( key );
169 fileName.replace(
'/',
'_' );
171 return m_CacheDirectory +
'/' + fileName;
174 void DiscCache::cleanup()
177 quint64 fivePercent = quint64( m_CacheLimit * 0.05 );
179 while ( m_CurrentCacheSize > (m_CacheLimit - fivePercent) ) {
180 QDateTime oldestDate( QDateTime::currentDateTime() );
183 QMapIterator<QString, QPair<QDateTime, quint64> > it( m_Entries );
184 while ( it.hasNext() ) {
187 if ( it.value().first < oldestDate ) {
188 oldestDate = it.value().first;
189 oldestKey = it.key();
193 if ( !oldestKey.isEmpty() ) {
quint64 cacheLimit() const
DiscCache(const QString &cacheDirectory)
void remove(const QString &key)
static QString indexFileName(const QString &cacheDirectory)
void setCacheLimit(quint64 n)
bool find(const QString &key, QByteArray &data)
bool exists(const QString &key) const
bool insert(const QString &key, const QByteArray &data)