diff --git a/akonadi/collectioncombobox.cpp b/akonadi/collectioncombobox.cpp index 2761cfaf2..3061c9522 100644 --- a/akonadi/collectioncombobox.cpp +++ b/akonadi/collectioncombobox.cpp @@ -1,163 +1,163 @@ /* This file is part of Akonadi Contact. Copyright (c) 2007-2009 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectioncombobox.h" #include "asyncselectionhandler_p.h" #include #include #include #include #include #include #include "kdescendantsproxymodel_p.h" #include using namespace Akonadi; class CollectionComboBox::Private { public: Private( QAbstractItemModel *customModel, CollectionComboBox *parent ) : mParent( parent ), mMonitor( 0 ), mModel( 0 ) { QAbstractItemModel *baseModel; if ( customModel ) { baseModel = customModel; } else { mMonitor = new Akonadi::ChangeRecorder( mParent ); mMonitor->fetchCollection( true ); mMonitor->setCollectionMonitored( Akonadi::Collection::root() ); - mModel = new EntityTreeModel( Session::defaultSession(), mMonitor, mParent ); + mModel = new EntityTreeModel( mMonitor, mParent ); mModel->setItemPopulationStrategy( EntityTreeModel::NoItemPopulation ); KDescendantsProxyModel *proxyModel = new KDescendantsProxyModel( parent ); proxyModel->setDisplayAncestorData( true ); proxyModel->setSourceModel( mModel ); baseModel = proxyModel; } mMimeTypeFilterModel = new CollectionFilterProxyModel( parent ); mMimeTypeFilterModel->setSourceModel( baseModel ); mRightsFilterModel = new EntityRightsFilterModel( parent ); mRightsFilterModel->setSourceModel( mMimeTypeFilterModel ); mParent->setModel( mRightsFilterModel ); mSelectionHandler = new AsyncSelectionHandler( mRightsFilterModel, mParent ); mParent->connect( mSelectionHandler, SIGNAL( collectionAvailable( const QModelIndex& ) ), mParent, SLOT( activated( const QModelIndex& ) ) ); mParent->connect( mParent, SIGNAL( activated( int ) ), mParent, SLOT( activated( int ) ) ); } ~Private() { } void activated( int index ); void activated( const QModelIndex& index ); CollectionComboBox *mParent; ChangeRecorder *mMonitor; EntityTreeModel *mModel; CollectionFilterProxyModel *mMimeTypeFilterModel; EntityRightsFilterModel *mRightsFilterModel; AsyncSelectionHandler *mSelectionHandler; }; void CollectionComboBox::Private::activated( int index ) { const QModelIndex modelIndex = mParent->model()->index( index, 0 ); if ( modelIndex.isValid() ) emit mParent->currentChanged( modelIndex.data( EntityTreeModel::CollectionRole).value() ); } void CollectionComboBox::Private::activated( const QModelIndex &index ) { mParent->setCurrentIndex( index.row() ); } CollectionComboBox::CollectionComboBox( QWidget *parent ) : KComboBox( parent ), d( new Private( 0, this ) ) { } CollectionComboBox::CollectionComboBox( QAbstractItemModel *model, QWidget *parent ) : KComboBox( parent ), d( new Private( model, this ) ) { } CollectionComboBox::~CollectionComboBox() { delete d; } void CollectionComboBox::setMimeTypeFilter( const QStringList &contentMimeTypes ) { d->mMimeTypeFilterModel->clearFilters(); d->mMimeTypeFilterModel->addMimeTypeFilters( contentMimeTypes ); if ( d->mMonitor ) foreach ( const QString &mimeType, contentMimeTypes ) d->mMonitor->setMimeTypeMonitored( mimeType, true ); } QStringList CollectionComboBox::mimeTypeFilter() const { return d->mMimeTypeFilterModel->mimeTypeFilters(); } void CollectionComboBox::setAccessRightsFilter( Collection::Rights rights ) { d->mRightsFilterModel->setAccessRights( rights ); } Collection::Rights CollectionComboBox::accessRightsFilter() const { return d->mRightsFilterModel->accessRights(); } void CollectionComboBox::setDefaultCollection( const Collection &collection ) { d->mSelectionHandler->waitForCollection( collection ); } Akonadi::Collection CollectionComboBox::currentCollection() const { const QModelIndex modelIndex = model()->index( currentIndex(), 0 ); if ( modelIndex.isValid() ) return modelIndex.data( Akonadi::EntityTreeModel::CollectionRole ).value(); else return Akonadi::Collection(); } #include "collectioncombobox.moc" diff --git a/akonadi/collectiondialog.cpp b/akonadi/collectiondialog.cpp index 797e68434..5ecccde9b 100644 --- a/akonadi/collectiondialog.cpp +++ b/akonadi/collectiondialog.cpp @@ -1,209 +1,209 @@ /* Copyright 2008 Ingo Klöcker This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectiondialog.h" #include "asyncselectionhandler_p.h" #include #include #include #include #include #include #include #include #include #include using namespace Akonadi; class CollectionDialog::Private { public: Private( QAbstractItemModel *customModel, CollectionDialog *parent ) : mParent( parent ), mMonitor( 0 ), mModel( 0 ) { // setup GUI QWidget *widget = mParent->mainWidget(); QVBoxLayout *layout = new QVBoxLayout( widget ); mTextLabel = new QLabel; layout->addWidget( mTextLabel ); mTextLabel->hide(); mView = new EntityTreeView; mView->header()->hide(); layout->addWidget( mView ); mParent->enableButton( KDialog::Ok, false ); // setup models QAbstractItemModel *baseModel; if ( customModel ) { baseModel = customModel; } else { mMonitor = new Akonadi::ChangeRecorder( mParent ); mMonitor->fetchCollection( true ); mMonitor->setCollectionMonitored( Akonadi::Collection::root() ); - mModel = new EntityTreeModel( Session::defaultSession(), mMonitor, mParent ); + mModel = new EntityTreeModel( mMonitor, mParent ); mModel->setItemPopulationStrategy( EntityTreeModel::NoItemPopulation ); baseModel = mModel; } mMimeTypeFilterModel = new CollectionFilterProxyModel( mParent ); mMimeTypeFilterModel->setSourceModel( baseModel ); mRightsFilterModel = new EntityRightsFilterModel( mParent ); mRightsFilterModel->setSourceModel( mMimeTypeFilterModel ); mSelectionHandler = new AsyncSelectionHandler( mRightsFilterModel, mParent ); mParent->connect( mSelectionHandler, SIGNAL( collectionAvailable( const QModelIndex& ) ), mParent, SLOT( slotCollectionAvailable( const QModelIndex& ) ) ); mView->setModel( mRightsFilterModel ); mParent->connect( mView->selectionModel(), SIGNAL( selectionChanged( QItemSelection, QItemSelection ) ), mParent, SLOT( slotSelectionChanged() ) ); } ~Private() { } void slotCollectionAvailable( const QModelIndex &index ) { mView->expandAll(); mView->setCurrentIndex( index ); } CollectionDialog *mParent; ChangeRecorder *mMonitor; EntityTreeModel *mModel; CollectionFilterProxyModel *mMimeTypeFilterModel; EntityRightsFilterModel *mRightsFilterModel; EntityTreeView *mView; AsyncSelectionHandler *mSelectionHandler; QLabel *mTextLabel; void slotSelectionChanged(); }; void CollectionDialog::Private::slotSelectionChanged() { mParent->enableButton( KDialog::Ok, mView->selectionModel()->selectedIndexes().count() > 0 ); } CollectionDialog::CollectionDialog( QWidget *parent ) : KDialog( parent ), d( new Private( 0, this ) ) { } CollectionDialog::CollectionDialog( QAbstractItemModel *model, QWidget *parent ) : KDialog( parent ), d( new Private( model, this ) ) { } CollectionDialog::~CollectionDialog() { delete d; } Akonadi::Collection CollectionDialog::selectedCollection() const { if ( selectionMode() == QAbstractItemView::SingleSelection ) { const QModelIndex index = d->mView->currentIndex(); if ( index.isValid() ) return index.model()->data( index, EntityTreeModel::CollectionRole ).value(); } return Collection(); } Akonadi::Collection::List CollectionDialog::selectedCollections() const { Collection::List collections; const QItemSelectionModel *selectionModel = d->mView->selectionModel(); const QModelIndexList selectedIndexes = selectionModel->selectedIndexes(); foreach ( const QModelIndex &index, selectedIndexes ) { if ( index.isValid() ) { const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value(); if ( collection.isValid() ) collections.append( collection ); } } return collections; } void CollectionDialog::setMimeTypeFilter( const QStringList &mimeTypes ) { d->mMimeTypeFilterModel->clearFilters(); d->mMimeTypeFilterModel->addMimeTypeFilters( mimeTypes ); if ( d->mMonitor ) foreach( const QString &mimetype, mimeTypes ) d->mMonitor->setMimeTypeMonitored( mimetype ); } QStringList CollectionDialog::mimeTypeFilter() const { return d->mMimeTypeFilterModel->mimeTypeFilters(); } void CollectionDialog::setAccessRightsFilter( Collection::Rights rights ) { d->mRightsFilterModel->setAccessRights( rights ); } Collection::Rights CollectionDialog::accessRightsFilter() const { return d->mRightsFilterModel->accessRights(); } void CollectionDialog::setDescription( const QString &text ) { d->mTextLabel->setText( text ); d->mTextLabel->show(); } void CollectionDialog::setDefaultCollection( const Collection &collection ) { d->mSelectionHandler->waitForCollection( collection ); } void CollectionDialog::setSelectionMode( QAbstractItemView::SelectionMode mode ) { d->mView->setSelectionMode( mode ); } QAbstractItemView::SelectionMode CollectionDialog::selectionMode() const { return d->mView->selectionMode(); } #include "collectiondialog.moc" diff --git a/akonadi/contact/contactcompletionmodel.cpp b/akonadi/contact/contactcompletionmodel.cpp index 79a3a0403..dc9e34898 100644 --- a/akonadi/contact/contactcompletionmodel.cpp +++ b/akonadi/contact/contactcompletionmodel.cpp @@ -1,135 +1,135 @@ /* This file is part of Akonadi Contact. Copyright (c) 2009 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "contactcompletionmodel_p.h" #include "../kdescendantsproxymodel_p.h" #include #include #include #include #include using namespace Akonadi; QAbstractItemModel* ContactCompletionModel::mSelf = 0; QAbstractItemModel* ContactCompletionModel::self() { if ( mSelf ) return mSelf; ChangeRecorder *monitor = new ChangeRecorder; monitor->fetchCollection( true ); monitor->itemFetchScope().fetchFullPayload(); monitor->setCollectionMonitored( Akonadi::Collection::root() ); monitor->setMimeTypeMonitored( KABC::Addressee::mimeType() ); - ContactCompletionModel *model = new ContactCompletionModel( Session::defaultSession(), monitor ); + ContactCompletionModel *model = new ContactCompletionModel( monitor ); KDescendantsProxyModel *descModel = new KDescendantsProxyModel( model ); descModel->setSourceModel( model ); EntityMimeTypeFilterModel *filter = new Akonadi::EntityMimeTypeFilterModel( model ); filter->setSourceModel( descModel ); filter->addMimeTypeExclusionFilter( Akonadi::Collection::mimeType() ); filter->setHeaderGroup( Akonadi::EntityTreeModel::ItemListHeaders ); mSelf = filter; return mSelf; } -ContactCompletionModel::ContactCompletionModel( Session *session, ChangeRecorder *monitor, QObject *parent ) - : EntityTreeModel( session, monitor, parent ) +ContactCompletionModel::ContactCompletionModel( ChangeRecorder *monitor, QObject *parent ) + : EntityTreeModel( monitor, parent ) { } ContactCompletionModel::~ContactCompletionModel() { } QVariant ContactCompletionModel::entityData( const Item &item, int column, int role ) const { if ( !item.hasPayload() ) { // Pass modeltest if ( role == Qt::DisplayRole ) return item.remoteId(); return QVariant(); } if ( role == Qt::DisplayRole || role == Qt::EditRole ) { const KABC::Addressee contact = item.payload(); switch ( column ) { case NameColumn: if ( !contact.formattedName().isEmpty() ) return contact.formattedName(); else return contact.assembledName(); break; case NameAndEmailColumn: { QString name = QString::fromLatin1( "%1 %2" ).arg( contact.givenName() ) .arg( contact.familyName() ).simplified(); if ( name.isEmpty() ) name = contact.organization().simplified(); if ( name.isEmpty() ) return QString(); const QString email = contact.preferredEmail().simplified(); if ( email.isEmpty() ) return QString(); return QString::fromLatin1( "%1 <%2>" ).arg( name ).arg( email ); } break; case EmailColumn: return contact.preferredEmail(); break; } } return EntityTreeModel::entityData( item, column, role ); } QVariant ContactCompletionModel::entityData( const Collection &collection, int column, int role ) const { return EntityTreeModel::entityData( collection, column, role ); } int ContactCompletionModel::columnCount( const QModelIndex &parent ) const { if ( !parent.isValid() ) return 3; else return 0; } int ContactCompletionModel::entityColumnCount( HeaderGroup ) const { return 3; } #include "contactcompletionmodel_p.moc" diff --git a/akonadi/contact/contactcompletionmodel_p.h b/akonadi/contact/contactcompletionmodel_p.h index 8f89cd55b..54f496fe3 100644 --- a/akonadi/contact/contactcompletionmodel_p.h +++ b/akonadi/contact/contactcompletionmodel_p.h @@ -1,57 +1,57 @@ /* This file is part of Akonadi Contact. Copyright (c) 2009 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_CONTACTCOMPLETIONMODEL_P_H #define AKONADI_CONTACTCOMPLETIONMODEL_P_H #include namespace Akonadi { class ContactCompletionModel : public EntityTreeModel { Q_OBJECT public: enum Columns { NameColumn, ///< The name of the contact. NameAndEmailColumn, ///< The name and the email of the contact. EmailColumn ///< The preferred email of the contact. }; - ContactCompletionModel( Session *session, ChangeRecorder *monitor, QObject *parent = 0 ); + ContactCompletionModel( ChangeRecorder *monitor, QObject *parent = 0 ); virtual ~ContactCompletionModel(); virtual QVariant entityData( const Item &item, int column, int role = Qt::DisplayRole ) const; virtual QVariant entityData( const Collection &collection, int column, int role = Qt::DisplayRole ) const; virtual int columnCount( const QModelIndex &parent ) const; virtual int entityColumnCount( HeaderGroup ) const; static QAbstractItemModel* self(); private: static QAbstractItemModel* mSelf; }; } #endif diff --git a/akonadi/entitycache.cpp b/akonadi/entitycache.cpp index 892e325ac..a980fbc58 100644 --- a/akonadi/entitycache.cpp +++ b/akonadi/entitycache.cpp @@ -1,28 +1,33 @@ /* Copyright (c) 2009 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "entitycache_p.h" using namespace Akonadi; -EntityCacheBase::EntityCacheBase( QObject *parent ) : QObject( parent ) +EntityCacheBase::EntityCacheBase( Session *_session ) : QObject( _session ), session(_session) { } +void EntityCacheBase::setSession( Session *_session ) +{ + session = _session; +} + #include "entitycache_p.moc" diff --git a/akonadi/entitycache_p.h b/akonadi/entitycache_p.h index 723b9e244..6e5cb80c5 100644 --- a/akonadi/entitycache_p.h +++ b/akonadi/entitycache_p.h @@ -1,237 +1,243 @@ /* Copyright (c) 2009 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_ENTITYCACHE_P_H #define AKONADI_ENTITYCACHE_P_H #include #include #include #include #include #include +#include #include #include #include #include class KJob; namespace Akonadi { /** @internal QObject part of EntityCache. */ class EntityCacheBase : public QObject { Q_OBJECT public: - explicit EntityCacheBase (QObject * parent = 0); + explicit EntityCacheBase ( Session * parent = 0 ); + + void setSession(Session *session); + + protected: + Session *session; signals: void dataAvailable(); private slots: virtual void fetchResult( KJob* job ) = 0; }; template struct EntityCacheNode { EntityCacheNode() : pending( false ), invalid( false ) {} EntityCacheNode( typename T::Id id ) : entity( T( id ) ), pending( true ), invalid( false ) {} T entity; bool pending; bool invalid; }; /** * @internal * A in-memory FIFO cache for a small amount of Entity objects. */ template class EntityCache : public EntityCacheBase { public: - explicit EntityCache( int maxCapacity, QObject *parent = 0 ) : - EntityCacheBase( parent ), + explicit EntityCache( int maxCapacity, Session *session = 0 ) : + EntityCacheBase( session ), mCapacity( maxCapacity ) {} ~EntityCache() { qDeleteAll( mCache ); } /** Object is available in the cache and can be retrieved. */ bool isCached( typename T::Id id ) const { EntityCacheNode* node = cacheNodeForId( id ); return node && !node->pending; } /** Object has been requested but is not yet loaded into the cache or is already available. */ bool isRequested( typename T::Id id ) const { return cacheNodeForId( id ); } /** Returns the cached object if available, an empty instance otherwise. */ T retrieve( typename T::Id id ) const { EntityCacheNode* node = cacheNodeForId( id ); if ( node && !node->pending && !node->invalid ) return node->entity; return T(); } /** Marks the cache entry as invalid, use in case the object has been deleted on the server. */ void invalidate( typename T::Id id ) { EntityCacheNode* node = cacheNodeForId( id ); if ( node ) node->invalid = true; } /** Triggers a re-fetching of a cache entry, use if it has changed on the server. */ void update( typename T::Id id, const FetchScope &scope ) { EntityCacheNode* node = cacheNodeForId( id ); if ( node ) { mCache.removeAll( node ); if ( node->pending ) request( id, scope ); delete node; } } /** Requests the object to be cached if it is not yet in the cache. @returns @c true if it was in the cache already. */ bool ensureCached( typename T::Id id, const FetchScope &scope ) { EntityCacheNode* node = cacheNodeForId( id ); if ( !node ) { request( id, scope ); return false; } return !node->pending; } /** Asks the cache to retrieve @p id. @p request is used as a token to indicate which request has been finished in the dataAvailable() signal. */ void request( typename T::Id id, const FetchScope &scope ) { Q_ASSERT( !isRequested( id ) ); shrinkCache(); EntityCacheNode *node = new EntityCacheNode( id ); FetchJob* job = createFetchJob( id ); job->setFetchScope( scope ); job->setProperty( "EntityCacheNode", QVariant::fromValue( id ) ); connect( job, SIGNAL(result(KJob*)), SLOT(fetchResult(KJob*)) ); mCache.enqueue( node ); } private: EntityCacheNode* cacheNodeForId( typename T::Id id ) const { for ( typename QQueue*>::const_iterator it = mCache.constBegin(), endIt = mCache.constEnd(); it != endIt; ++it ) { if ( (*it)->entity.id() == id ) return *it; } return 0; } void fetchResult( KJob* job ) { if ( job->error() ) { kWarning() << "Fetch failed:" << job->errorString(); return; } typename T::Id id = job->property( "EntityCacheNode" ).template value(); EntityCacheNode *node = cacheNodeForId( id ); if ( !node ) return; // got replaced in the meantime node->pending = false; extractResult( node, job ); // make sure we find this node again if something went wrong here, // most likely the object got deleted from the server in the meantime if ( node->entity.id() != id ) { node->entity.setId( id ); node->invalid = true; } emit dataAvailable(); } void extractResult( EntityCacheNode* node, KJob* job ) const; inline FetchJob* createFetchJob( typename T::Id id ) { - return new FetchJob( T( id ), this ); + return new FetchJob( T( id ), session ); } /** Tries to reduce the cache size until at least one more object fits in. */ void shrinkCache() { while ( mCache.size() >= mCapacity && !mCache.first()->pending ) delete mCache.dequeue(); } private: QQueue*> mCache; int mCapacity; }; template<> inline void EntityCache::extractResult( EntityCacheNode* node, KJob *job ) const { CollectionFetchJob* fetch = qobject_cast( job ); Q_ASSERT( fetch ); if ( fetch->collections().isEmpty() ) node->entity = Collection(); else node->entity = fetch->collections().first(); } template<> inline void EntityCache::extractResult( EntityCacheNode* node, KJob *job ) const { ItemFetchJob* fetch = qobject_cast( job ); Q_ASSERT( fetch ); if ( fetch->items().isEmpty() ) node->entity = Item(); else node->entity = fetch->items().first(); } template<> inline CollectionFetchJob* EntityCache::createFetchJob( Collection::Id id ) { - return new CollectionFetchJob( Collection( id ), CollectionFetchJob::Base, this ); + return new CollectionFetchJob( Collection( id ), CollectionFetchJob::Base, session ); } typedef EntityCache CollectionCache; typedef EntityCache ItemCache; } #endif diff --git a/akonadi/entitytreemodel.cpp b/akonadi/entitytreemodel.cpp index 5bd24de2c..865778223 100644 --- a/akonadi/entitytreemodel.cpp +++ b/akonadi/entitytreemodel.cpp @@ -1,1050 +1,1048 @@ /* Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "entitytreemodel.h" #include "entitytreemodel_p.h" #include "monitor_p.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "collectionfetchscope.h" #include "collectionutils_p.h" #include "kdebug.h" #include "pastehelper_p.h" // TODO: // * Implement ordering support. Q_DECLARE_METATYPE( QSet ) using namespace Akonadi; -EntityTreeModel::EntityTreeModel( Session *session, - ChangeRecorder *monitor, +EntityTreeModel::EntityTreeModel( ChangeRecorder *monitor, QObject *parent ) : QAbstractItemModel( parent ), d_ptr( new EntityTreeModelPrivate( this ) ) { Q_D( EntityTreeModel ); - d->init( monitor, session ); + d->init( monitor ); } -EntityTreeModel::EntityTreeModel( Session *session, - ChangeRecorder *monitor, +EntityTreeModel::EntityTreeModel( ChangeRecorder *monitor, EntityTreeModelPrivate *d, QObject *parent ) : QAbstractItemModel( parent ), d_ptr( d ) { - d->init(monitor, session); + d->init(monitor ); } EntityTreeModel::~EntityTreeModel() { Q_D( EntityTreeModel ); foreach( const QList &list, d->m_childEntities ) { qDeleteAll( list ); } delete d_ptr; } bool EntityTreeModel::systemEntitiesShown() const { Q_D( const EntityTreeModel ); return d->m_showSystemEntities; } void EntityTreeModel::setShowSystemEntities( bool show ) { Q_D( EntityTreeModel ); d->m_showSystemEntities = show; } void EntityTreeModel::clearAndReset() { Q_D( EntityTreeModel ); d->beginResetModel(); d->endResetModel(); } int EntityTreeModel::columnCount( const QModelIndex & parent ) const { // TODO: Statistics? if ( parent.isValid() && parent.column() != 0 ) return 0; return qMax( entityColumnCount( CollectionTreeHeaders ), entityColumnCount( ItemListHeaders ) ); } QVariant EntityTreeModel::entityData( const Item &item, int column, int role ) const { if ( column == 0 ) { switch ( role ) { case Qt::DisplayRole: case Qt::EditRole: if ( item.hasAttribute() && !item.attribute()->displayName().isEmpty() ) { return item.attribute()->displayName(); } else { return item.remoteId(); } break; case Qt::DecorationRole: if ( item.hasAttribute() && !item.attribute()->iconName().isEmpty() ) return item.attribute()->icon(); break; default: break; } } return QVariant(); } QVariant EntityTreeModel::entityData( const Collection &collection, int column, int role ) const { Q_D( const EntityTreeModel ); if ( column > 0 ) return QString(); if ( collection == Collection::root() ) { // Only display the root collection. It may not be edited. if ( role == Qt::DisplayRole ) return d->m_rootCollectionDisplayName; if ( role == Qt::EditRole ) return QVariant(); } switch ( role ) { case Qt::DisplayRole: case Qt::EditRole: if ( column == 0 ) { if ( collection.hasAttribute() && !collection.attribute()->displayName().isEmpty() ) { return collection.attribute()->displayName(); } return collection.name(); } break; case Qt::DecorationRole: if ( collection.hasAttribute() && !collection.attribute()->iconName().isEmpty() ) { return collection.attribute()->icon(); } return KIcon( CollectionUtils::defaultIconName( collection ) ); default: break; } return QVariant(); } QVariant EntityTreeModel::data( const QModelIndex & index, int role ) const { Q_D( const EntityTreeModel ); if ( role == SessionRole ) return QVariant::fromValue( qobject_cast( d->m_session ) ); // Ugly, but at least the API is clean. const HeaderGroup headerGroup = static_cast( ( role / static_cast( TerminalUserRole ) ) ); role %= TerminalUserRole; if ( !index.isValid() ) { if ( ColumnCountRole != role ) return QVariant(); return entityColumnCount( headerGroup ); } if ( ColumnCountRole == role ) return entityColumnCount( headerGroup ); const Node *node = reinterpret_cast( index.internalPointer() ); if ( ParentCollectionRole == role ) { const Collection parentCollection = d->m_collections.value( node->parent ); Q_ASSERT( parentCollection.isValid() ); return QVariant::fromValue( parentCollection ); } if ( Node::Collection == node->type ) { const Collection collection = d->m_collections.value( node->id ); if ( !collection.isValid() ) return QVariant(); switch ( role ) { case MimeTypeRole: return collection.mimeType(); break; case RemoteIdRole: return collection.remoteId(); break; case CollectionIdRole: return collection.id(); break; case ItemIdRole: // QVariant().toInt() is 0, not -1, so we have to handle the ItemIdRole // and CollectionIdRole (below) specially return -1; break; case CollectionRole: return QVariant::fromValue( collection ); break; case EntityUrlRole: return collection.url().url(); break; case Qt::BackgroundRole: { if ( collection.hasAttribute() ) { EntityDisplayAttribute *eda = collection.attribute(); QColor color = eda->backgroundColor(); if ( color.isValid() ) return color; } // fall through. } default: return entityData( collection, index.column(), role ); break; } } else if ( Node::Item == node->type ) { const Item item = d->m_items.value( node->id ); if ( !item.isValid() ) return QVariant(); switch ( role ) { case MimeTypeRole: return item.mimeType(); break; case RemoteIdRole: return item.remoteId(); break; case ItemRole: return QVariant::fromValue( item ); break; case ItemIdRole: return item.id(); break; case CollectionIdRole: return -1; break; case LoadedPartsRole: return QVariant::fromValue( item.loadedPayloadParts() ); break; case AvailablePartsRole: return QVariant::fromValue( item.availablePayloadParts() ); break; case EntityUrlRole: return item.url( Akonadi::Item::UrlWithMimeType ).url(); break; case Qt::BackgroundRole: { if ( item.hasAttribute() ) { EntityDisplayAttribute *eda = item.attribute(); QColor color = eda->backgroundColor(); if ( color.isValid() ) return color; } // fall through. } default: return entityData( item, index.column(), role ); break; } } return QVariant(); } Qt::ItemFlags EntityTreeModel::flags( const QModelIndex & index ) const { Q_D( const EntityTreeModel ); // Pass modeltest. // http://labs.trolltech.com/forums/topic/79 if ( !index.isValid() ) return 0; Qt::ItemFlags flags = QAbstractItemModel::flags( index ); const Node *node = reinterpret_cast( index.internalPointer() ); if ( Node::Collection == node->type ) { // cut out entities will be shown as inactive if ( d->m_pendingCutCollections.contains( node->id ) ) return Qt::ItemIsSelectable; const Collection collection = d->m_collections.value( node->id ); if ( collection.isValid() ) { if ( collection == Collection::root() ) { // Selectable and displayable only. return flags; } const int rights = collection.rights(); if ( rights & Collection::CanChangeCollection ) { if ( index.column() == 0 ) flags |= Qt::ItemIsEditable; // Changing the collection includes changing the metadata (child entityordering). // Need to allow this by drag and drop. flags |= Qt::ItemIsDropEnabled; } if ( rights & ( Collection::CanCreateCollection | Collection::CanCreateItem | Collection::CanLinkItem ) ) { // Can we drop new collections and items into this collection? flags |= Qt::ItemIsDropEnabled; } // dragging is always possible, even for read-only objects, but they can only be copied, not moved. flags |= Qt::ItemIsDragEnabled; } } else if ( Node::Item == node->type ) { if ( d->m_pendingCutItems.contains( node->id ) ) return Qt::ItemIsSelectable; // Rights come from the parent collection. Collection parentCollection; if ( !index.parent().isValid() ) { parentCollection = d->m_rootCollection; } else { const Node *parentNode = reinterpret_cast( index.parent().internalPointer() ); parentCollection = d->m_collections.value( parentNode->id ); } if ( parentCollection.isValid() ) { const int rights = parentCollection.rights(); // Can't drop onto items. if ( rights & Collection::CanChangeItem && index.column() == 0 ) { flags = flags | Qt::ItemIsEditable; } // dragging is always possible, even for read-only objects, but they can only be copied, not moved. flags |= Qt::ItemIsDragEnabled; } } return flags; } Qt::DropActions EntityTreeModel::supportedDropActions() const { return (Qt::CopyAction | Qt::MoveAction | Qt::LinkAction); } QStringList EntityTreeModel::mimeTypes() const { // TODO: Should this return the mimetypes that the items provide? Allow dragging a contact from here for example. return QStringList() << QLatin1String( "text/uri-list" ); } bool EntityTreeModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent ) { Q_UNUSED( row ); Q_UNUSED( column ); Q_D( EntityTreeModel ); // Can't drop onto Collection::root. if ( !parent.isValid() ) return false; // TODO Use action and collection rights and return false if necessary // if row and column are -1, then the drop was on parent directly. // data should then be appended on the end of the items of the collections as appropriate. // That will mean begin insert rows etc. // Otherwise it was a sibling of the row^th item of parent. // Needs to be handled when ordering is accounted for. // Handle dropping between items as well as on items. // if ( row != -1 && column != -1 ) // { // } if ( action == Qt::IgnoreAction ) return true; // Shouldn't do this. Need to be able to drop vcards for example. // if ( !data->hasFormat( "text/uri-list" ) ) // return false; Node *node = reinterpret_cast( parent.internalId() ); Q_ASSERT( node ); if ( Node::Item == node->type ) { if ( !parent.parent().isValid() ) { // The drop is somehow on an item with no parent (shouldn't happen) // The drop should be considered handled anyway. kWarning() << "Dropped onto item with no parent collection"; return true; } // A drop onto an item should be considered as a drop onto its parent collection node = reinterpret_cast( parent.parent().internalId() ); } if ( Node::Collection == node->type ) { const Collection destCollection = d->m_collections.value( node->id ); // Applications can't create new collections in root. Only resources can. if ( destCollection == Collection::root() ) // Accept the event so that it doesn't propagate. return true; if ( data->hasFormat( QLatin1String( "text/uri-list" ) ) ) { MimeTypeChecker mimeChecker; mimeChecker.setWantedMimeTypes( destCollection.contentMimeTypes() ); const KUrl::List urls = KUrl::List::fromMimeData( data ); foreach ( const KUrl &url, urls ) { const Collection collection = d->m_collections.value( Collection::fromUrl( url ).id() ); if ( collection.isValid() ) { if ( collection.parentCollection().id() == destCollection.id() ) { kDebug() << "Error: source and destination of move are the same."; return false; } if ( !mimeChecker.isWantedCollection( collection ) ) { kDebug() << "unwanted collection" << mimeChecker.wantedMimeTypes() << collection.contentMimeTypes(); return false; } } else { const Item item = d->m_items.value( Item::fromUrl( url ).id() ); if ( item.isValid() ) { if ( item.parentCollection().id() == destCollection.id() ) { kDebug() << "Error: source and destination of move are the same."; return false; } if ( !mimeChecker.isWantedItem( item ) ) { kDebug() << "unwanted item" << mimeChecker.wantedMimeTypes() << item.mimeType(); return false; } } } } KJob *job = PasteHelper::pasteUriList( data, destCollection, action, d->m_session ); if ( !job ) return false; connect( job, SIGNAL( result( KJob* ) ), SLOT( pasteJobDone( KJob* ) ) ); // Accpet the event so that it doesn't propagate. return true; } else { // not a set of uris. Maybe vcards etc. Check if the parent supports them, and maybe do // fromMimeData for them. Hmm, put it in the same transaction with the above? // TODO: This should be handled first, not last. } } return false; } QModelIndex EntityTreeModel::index( int row, int column, const QModelIndex & parent ) const { Q_D( const EntityTreeModel ); if ( parent.column() > 0 ) return QModelIndex(); //TODO: don't use column count here? Use some d-> func. if ( column >= columnCount() || column < 0 ) return QModelIndex(); QList childEntities; const Node *parentNode = reinterpret_cast( parent.internalPointer() ); if ( !parentNode || !parent.isValid() ) { if ( d->m_showRootCollection ) childEntities << d->m_childEntities.value( -1 ); else childEntities = d->m_childEntities.value( d->m_rootCollection.id() ); } else { if ( parentNode->id >= 0 ) childEntities = d->m_childEntities.value( parentNode->id ); } const int size = childEntities.size(); if ( row < 0 || row >= size ) return QModelIndex(); Node *node = childEntities.at( row ); return createIndex( row, column, reinterpret_cast( node ) ); } QModelIndex EntityTreeModel::parent( const QModelIndex & index ) const { Q_D( const EntityTreeModel ); if ( !index.isValid() ) return QModelIndex(); const Node *node = reinterpret_cast( index.internalPointer() ); if ( !node ) return QModelIndex(); const Collection collection = d->m_collections.value( node->parent ); if ( !collection.isValid() ) return QModelIndex(); if ( collection.id() == d->m_rootCollection.id() ) { if ( !d->m_showRootCollection ) return QModelIndex(); else return createIndex( 0, 0, reinterpret_cast( d->m_rootNode ) ); } const int row = d->indexOf( d->m_childEntities.value( collection.parentCollection().id() ), collection.id() ); Q_ASSERT( row >= 0 ); Node *parentNode = d->m_childEntities.value( collection.parentCollection().id() ).at( row ); return createIndex( row, 0, reinterpret_cast( parentNode ) ); } int EntityTreeModel::rowCount( const QModelIndex & parent ) const { Q_D( const EntityTreeModel ); const Node *node = reinterpret_cast( parent.internalPointer() ); qint64 id; if ( !parent.isValid() ) { // If we're showing the root collection then it will be the only child of the root. if ( d->m_showRootCollection ) return d->m_childEntities.value( -1 ).size(); id = d->m_rootCollection.id(); } else { if ( !node ) return 0; if ( Node::Item == node->type ) return 0; id = node->id; } if ( parent.column() <= 0 ) return d->m_childEntities.value( id ).size(); return 0; } int EntityTreeModel::entityColumnCount( HeaderGroup headerGroup ) const { // Not needed in this model. Q_UNUSED( headerGroup ); return 1; } QVariant EntityTreeModel::entityHeaderData( int section, Qt::Orientation orientation, int role, HeaderGroup headerGroup ) const { Q_D( const EntityTreeModel ); // Not needed in this model. Q_UNUSED( headerGroup ); if ( section == 0 && orientation == Qt::Horizontal && role == Qt::DisplayRole ) { if ( d->m_rootCollection == Collection::root() ) return i18nc( "@title:column Name of a thing", "Name" ); return d->m_rootCollection.name(); } return QAbstractItemModel::headerData( section, orientation, role ); } QVariant EntityTreeModel::headerData( int section, Qt::Orientation orientation, int role ) const { const HeaderGroup headerGroup = static_cast( (role / static_cast( TerminalUserRole ) ) ); role %= TerminalUserRole; return entityHeaderData( section, orientation, role, headerGroup ); } QMimeData *EntityTreeModel::mimeData( const QModelIndexList &indexes ) const { Q_D( const EntityTreeModel ); QMimeData *data = new QMimeData(); KUrl::List urls; foreach( const QModelIndex &index, indexes ) { if ( index.column() != 0 ) continue; if ( !index.isValid() ) continue; const Node *node = reinterpret_cast( index.internalPointer() ); if ( Node::Collection == node->type ) urls << d->m_collections.value( node->id ).url(); else if ( Node::Item == node->type ) urls << d->m_items.value( node->id ).url( Item::UrlWithMimeType ); else // if that happens something went horrible wrong Q_ASSERT( false ); } urls.populateMimeData( data ); return data; } // Always return false for actions which take place asyncronously, eg via a Job. bool EntityTreeModel::setData( const QModelIndex &index, const QVariant &value, int role ) { Q_D( EntityTreeModel ); const Node *node = reinterpret_cast( index.internalPointer() ); if ( role == PendingCutRole ) { if ( index.isValid() && value.toBool() ) { if ( Node::Collection == node->type ) d->m_pendingCutCollections.append( node->id ); if ( Node::Item == node->type ) d->m_pendingCutItems.append( node->id ); } else { d->m_pendingCutCollections.clear(); d->m_pendingCutItems.clear(); } return true; } if ( index.isValid() && node->type == Node::Collection && (role == CollectionRefRole || role == CollectionDerefRole) ) { const Collection collection = index.data( CollectionRole ).value(); Q_ASSERT( collection.isValid() ); if ( role == CollectionDerefRole ) d->deref( collection.id() ); else if ( role == CollectionRefRole ) d->ref( collection.id() ); } if ( index.column() == 0 && ( role & ( Qt::EditRole | ItemRole | CollectionRole ) ) ) { if ( Node::Collection == node->type ) { Collection collection = d->m_collections.value( node->id ); if ( !collection.isValid() || !value.isValid() ) return false; if ( Qt::EditRole == role ) { collection.setName( value.toString() ); if ( collection.hasAttribute() ) { EntityDisplayAttribute *displayAttribute = collection.attribute(); displayAttribute->setDisplayName( value.toString() ); } } if ( Qt::BackgroundRole == role ) { QColor color = value.value(); if ( color.isValid() ) return false; EntityDisplayAttribute *eda = collection.attribute( Entity::AddIfMissing ); eda->setBackgroundColor( color ); } if ( CollectionRole == role ) collection = value.value(); CollectionModifyJob *job = new CollectionModifyJob( collection, d->m_session ); connect( job, SIGNAL( result( KJob* ) ), SLOT( updateJobDone( KJob* ) ) ); return false; } else if ( Node::Item == node->type ) { Item item = d->m_items.value( node->id ); if ( !item.isValid() || !value.isValid() ) return false; if ( Qt::EditRole == role ) { if ( item.hasAttribute() ) { EntityDisplayAttribute *displayAttribute = item.attribute( Entity::AddIfMissing ); displayAttribute->setDisplayName( value.toString() ); } } if ( Qt::BackgroundRole == role ) { QColor color = value.value(); if ( !color.isValid() ) return false; EntityDisplayAttribute *eda = item.attribute( Entity::AddIfMissing ); eda->setBackgroundColor( color ); } if ( ItemRole == role ) { item = value.value(); Q_ASSERT( item.id() == node->id ); } ItemModifyJob *itemModifyJob = new ItemModifyJob( item, d->m_session ); connect( itemModifyJob, SIGNAL( result( KJob* ) ), SLOT( updateJobDone( KJob* ) ) ); return false; } } return QAbstractItemModel::setData( index, value, role ); } bool EntityTreeModel::canFetchMore( const QModelIndex & parent ) const { Q_D( const EntityTreeModel ); const Item item = parent.data( ItemRole ).value(); if ( item.isValid() ) { // items can't have more rows. // TODO: Should I use this for fetching more of an item, ie more payload parts? return false; } else { // but collections can... const Collection::Id colId = parent.data( CollectionIdRole ).toULongLong(); // But the root collection can't... if ( Collection::root().id() == colId ) return false; foreach ( Node *node, d->m_childEntities.value( colId ) ) { if ( Node::Item == node->type ) { // Only try to fetch more from a collection if we don't already have items in it. // Otherwise we'd spend all the time listing items in collections. // This means that collections which don't contain items get a lot of item fetch jobs started on them. // Will fix that later. return false; } } return true; } // TODO: It might be possible to get akonadi to tell us if a collection is empty // or not and use that information instead of assuming all collections are not empty. // Using Collection statistics? } void EntityTreeModel::fetchMore( const QModelIndex & parent ) { Q_D( EntityTreeModel ); if ( !canFetchMore( parent ) ) return; if ( d->m_itemPopulation == ImmediatePopulation ) // Nothing to do. The items are already in the model. return; else if ( d->m_itemPopulation == LazyPopulation ) { const Collection collection = parent.data( CollectionRole ).value(); if ( !collection.isValid() ) return; d->fetchItems( collection ); } } bool EntityTreeModel::hasChildren( const QModelIndex &parent ) const { Q_D( const EntityTreeModel ); // TODO: Empty collections right now will return true and get a little + to expand. // There is probably no way to tell if a collection // has child items in akonadi without first attempting an itemFetchJob... // Figure out a way to fix this. (Statistics) return ((rowCount( parent ) > 0) || (canFetchMore( parent ) && d->m_itemPopulation == LazyPopulation)); } bool EntityTreeModel::entityMatch( const Item &item, const QVariant &value, Qt::MatchFlags flags ) const { Q_UNUSED( item ); Q_UNUSED( value ); Q_UNUSED( flags ); return false; } bool EntityTreeModel::entityMatch( const Collection &collection, const QVariant &value, Qt::MatchFlags flags ) const { Q_UNUSED( collection ); Q_UNUSED( value ); Q_UNUSED( flags ); return false; } QModelIndexList EntityTreeModel::match( const QModelIndex& start, int role, const QVariant& value, int hits, Qt::MatchFlags flags ) const { Q_D( const EntityTreeModel ); if ( role == CollectionIdRole || role == CollectionRole ) { Collection::Id id; if ( role == CollectionRole ) { const Collection collection = value.value(); id = collection.id(); } id = value.toLongLong(); QModelIndexList list; const Collection collection = d->m_collections.value( id ); if ( !collection.isValid() ) return list; const QModelIndex collectionIndex = d->indexForCollection( collection ); Q_ASSERT( collectionIndex.isValid() ); list << collectionIndex; return list; } if ( role == ItemIdRole ) { Item::Id id; if ( role == CollectionRole ) { const Item item = value.value(); id = item.id(); } id = value.toLongLong(); QModelIndexList list; const Item item = d->m_items.value( id ); if ( !item.isValid() ) return list; return d->indexesForItem( item ); } if ( role == EntityUrlRole ) { const KUrl url( value.toString() ); const Item item = Item::fromUrl( url ); if ( item.isValid() ) return d->indexesForItem( d->m_items.value( item.id() ) ); const Collection collection = Collection::fromUrl( url ); QModelIndexList list; if ( collection.isValid() ) list << d->indexForCollection( collection ); return list; } if ( role != AmazingCompletionRole ) return QAbstractItemModel::match( start, role, value, hits, flags ); // Try to match names, and email addresses. QModelIndexList list; if ( role < 0 || !start.isValid() || !value.isValid() ) return list; const int column = 0; int row = start.row(); const QModelIndex parentIndex = start.parent(); const int parentRowCount = rowCount( parentIndex ); while ( row < parentRowCount && (hits == -1 || list.size() < hits) ) { const QModelIndex idx = index( row, column, parentIndex ); const Item item = idx.data( ItemRole ).value(); if ( !item.isValid() ) { const Collection collection = idx.data( CollectionRole ).value(); if ( !collection.isValid() ) continue; if ( entityMatch( collection, value, flags ) ) list << idx; } else { if ( entityMatch( item, value, flags ) ) list << idx; } ++row; } return list; } bool EntityTreeModel::insertRows( int, int, const QModelIndex& ) { return false; } bool EntityTreeModel::insertColumns( int, int, const QModelIndex& ) { return false; } bool EntityTreeModel::removeRows( int, int, const QModelIndex& ) { return false; } bool EntityTreeModel::removeColumns( int, int, const QModelIndex& ) { return false; } void EntityTreeModel::setItemPopulationStrategy( ItemPopulationStrategy strategy ) { Q_D( EntityTreeModel ); d->beginResetModel(); d->m_itemPopulation = strategy; if ( strategy == NoItemPopulation ) { disconnect( d->m_monitor, SIGNAL( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ), this, SLOT( monitoredItemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( itemChanged( const Akonadi::Item&, const QSet& ) ), this, SLOT( monitoredItemChanged( const Akonadi::Item&, const QSet& ) ) ); disconnect( d->m_monitor, SIGNAL( itemRemoved( const Akonadi::Item& ) ), this, SLOT( monitoredItemRemoved( const Akonadi::Item& ) ) ); disconnect( d->m_monitor, SIGNAL( itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ), this, SLOT( monitoredItemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( itemLinked( const Akonadi::Item&, const Akonadi::Collection& ) ), this, SLOT( monitoredItemLinked( const Akonadi::Item&, const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( itemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ) ), this, SLOT( monitoredItemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ) ) ); } d->m_monitor->d_ptr->useRefCounting = (strategy == LazyPopulation); d->endResetModel(); } EntityTreeModel::ItemPopulationStrategy EntityTreeModel::itemPopulationStrategy() const { Q_D( const EntityTreeModel ); return d->m_itemPopulation; } void EntityTreeModel::setIncludeRootCollection( bool include ) { Q_D( EntityTreeModel ); d->beginResetModel(); d->m_showRootCollection = include; d->endResetModel(); } bool EntityTreeModel::includeRootCollection() const { Q_D( const EntityTreeModel ); return d->m_showRootCollection; } void EntityTreeModel::setRootCollectionDisplayName( const QString &displayName ) { Q_D( EntityTreeModel ); d->m_rootCollectionDisplayName = displayName; // TODO: Emit datachanged if it is being shown. } QString EntityTreeModel::rootCollectionDisplayName() const { Q_D( const EntityTreeModel ); return d->m_rootCollectionDisplayName; } void EntityTreeModel::setCollectionFetchStrategy( CollectionFetchStrategy strategy ) { Q_D( EntityTreeModel ); d->beginResetModel(); d->m_collectionFetchStrategy = strategy; if ( strategy == FetchNoCollections ) { disconnect( d->m_monitor, SIGNAL( collectionChanged( const Akonadi::Collection& ) ), this, SLOT( monitoredCollectionChanged( const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( collectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ) ), this, SLOT( monitoredCollectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( collectionRemoved( const Akonadi::Collection& ) ), this, SLOT( monitoredCollectionRemoved( const Akonadi::Collection& ) ) ); disconnect( d->m_monitor, SIGNAL( collectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection& ) ), this, SLOT( monitoredCollectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); } d->endResetModel(); } EntityTreeModel::CollectionFetchStrategy EntityTreeModel::collectionFetchStrategy() const { Q_D( const EntityTreeModel ); return d->m_collectionFetchStrategy; } #include "entitytreemodel.moc" diff --git a/akonadi/entitytreemodel.h b/akonadi/entitytreemodel.h index 9a5f7ff78..5e2d0a078 100644 --- a/akonadi/entitytreemodel.h +++ b/akonadi/entitytreemodel.h @@ -1,567 +1,567 @@ /* Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_ENTITYTREEMODEL_H #define AKONADI_ENTITYTREEMODEL_H #include "akonadi_export.h" #include #include #include #include namespace Akonadi { class ChangeRecorder; class CollectionStatistics; class Item; class ItemFetchScope; class Monitor; class Session; class EntityTreeModelPrivate; /** * @short A model for collections and items together. * * Akonadi models and views provide a high level way to interact with the akonadi server. * Most applications will use these classes. * * Models provide an interface for viewing, deleting and moving Items and Collections. * Additionally, the models are updated automatically if another application changes the * data or inserts of deletes items etc. * * @note The EntityTreeModel should be used with the EntityTreeView or the EntityListView class * either directly or indirectly via proxy models. * *

Retrieving Collections and Items from the model

* * If you want to retrieve and Item or Collection from the model, and already have a valid * QModelIndex for the correct row, the Collection can be retrieved like this: * * @code * Collection col = index.data( EntityTreeModel::CollectionRole ).value(); * @endcode * * And similarly for Items. This works even if there is a proxy model between the calling code * and the EntityTreeModel. * * If you want to retrieve a Collection for a particular Collection::Id and you do not yet * have a valid QModelIndex, use match: * * @code * QModelIndexList list = model->match(QModelIndex(), CollectionIdRole, id); * if (list.isEmpty()) * return; // A Collection with that Id is not in the model. * Q_ASSERT( list.size() == 1 ); // Otherwise there must be only one instance of it. * Collection col = list.at( 0 ).data( EntityTreeModel::CollectionRole ).value(); * @endcode * * Not that a single Item may appear multiple times in a model, so the list size may not be 1 * if it is not empty in that case, so the Q_ASSERT should not be used. * @see virtual-collections * *

Using EntityTreeModel in your application

* * The responsibilities which fall to the application developer are * - Configuring the ChangeRecorder and EntityTreeModel * - Making use of this class via proxy models * - Subclassing for type specific display information * *

Creating and configuring the EntityTreeModel

* * This class is a wrapper around a Akonadi::ChangeRecorder object. The model represents a * part of the collection and item tree configured in the ChangeRecorder. The structure of the * model mirrors the structure of Collections and Items on the %Akonadi server. * * The following code creates a model which fetches items and collections relevant to * addressees (contacts), and automatically manages keeping the items up to date. * * @code * * ChangeRecorder *changeRecorder = new ChangeRecorder( this ); * changeRecorder->setCollectionMonitored( Collection::root() ); * changeRecorder->setMimeTypeMonitored( KABC::addresseeMimeType() ); * * EntityTreeModel *model = new EntityTreeModel( session, changeRecorder, this ); * * EntityTreeView *view = new EntityTreeView( this ); * view->setModel( model ); * * @endcode * * The EntityTreeModel will show items of a different type by changing the line * * @code * changeRecorder->setMimeTypeMonitored( KABC::addresseeMimeType() ); * @endcode * * to a different mimetype. KABC::addresseeMimeType() is an alias for "text/directory". If changed to KMime::Message::mimeType() * (an alias for "message/rfc822") the model would instead contain emails. The model can be configured to contain items of any mimetype * known to %Akonadi. * * @note The EntityTreeModel does some extra configuration on the Monitor, such as setting itemFetchScope() and collectionFetchScope() * to retrieve all ancestors. This is necessary for proper function of the model. * * @see Akonadi::ItemFetchScope::AncestorRetrieval. * * @see akonadi-mimetypes. * * The EntityTreeModel can be further configured for certain behaviours such as fetching of collections and items. * * The model can be configured to not fetch items into the model (ie, fetch collections only) by setting * * @code * entityTreeModel->setItemPopulationStrategy( EntityTreeModel::NoItemPopulation ); * @endcode * * The items may be fetched lazily, i.e. not inserted into the model until request by the user for performance reasons. * * The Collection tree is always built immediately if Collections are to be fetched. * * @code * entityTreeModel->setItemPopulationStrategy( EntityTreeModel::LazyPopulation ); * @endcode * * This will typically be used with a EntityMimeTypeFilterModel in a configuration such as KMail4.5 or AkonadiConsole. * * The CollectionFetchStrategy determines how the model will be populated with Collections. That is, if FetchNoCollections is set, * no collections beyond the root of the model will be fetched. This can be used in combination with setting a particular Collection to monitor. * * @code * // Get an collection id from a config file. * Collection::Id id; * monitor->setCollectionMonitored( Collection( id ) ); * // ... Other initialization code. * entityTree->setCollectionFetchStrategy( FetchNoCollections ); * @endcode * * This has the effect of creating a model of only a list of Items, and not collections. This is similar in behaviour and aims to the ItemModel. * By using FetchFirstLevelCollections instead, a mixed list of entities can be created. * * @note It is important that you set only one Collection to be monitored in the monitor object. This one collection will be the root of the tree. * If you need a model with a more complex structure, consider monitoring a common ancestor and using a SelectionProxyModel. * * @see lazy-model-population * * It is also possible to show the root Collection as part of the selectable model: * * @code * entityTree->setIncludeRootCollection(true); * @endcode * * * By default the displayed name of the root collection is '[*]', because it doesn't require i18n, and is generic. It can be changed too. * * @code * entityTree->setIncludeRootCollection(true); * entityTree->setRootCollectionDisplayName(i18nc("Name of top level for all addressbooks in the application", "[All AddressBooks]")) * @endcode * * This feature is used in KAddressBook. * *

Using EntityTreeModel with Proxy models

* * An Akonadi::SelectionProxyModel can be used to simplify managing selection in one view through multiple proxy models to a representation in another view. * The selectionModel of the initial view is used to create a proxied model which filters out anything not related to the current selection. * * @code * // ... create an EntityTreeModel * * collectionTree = new EntityMimeTypeFilterModel(this); * collectionTree->setSourceModel(entityTreeModel); * * // Include only collections in this proxy model. * collectionTree->addMimeTypeInclusionFilter( Collection::mimeType() ); * collectionTree->setHeaderGroup( EntityTreeModel::CollectionTreeHeaders ); * * treeview->setModel(collectionTree); * * // SelectionProxyModel can handle complex selections: * treeview->setSelectionMode( QAbstractItemView::ExtendedSelection ); * * SelectionProxyModel *selProxy = new SelectionProxyModel( treeview->selectionModel(), this ); * selProxy->setSourceModel( entityTreeModel ); * * itemList = new EntityMimeTypeFilterModel( this ); * itemList->setSourceModel( selProxy ); * * // Filter out collections. Show only items. * itemList->addMimeTypeExclusionFilter( Collection::mimeType() ); * itemList->setHeaderGroup( EntityTreeModel::ItemListHeaders ); * * EntityTreeView *itemView = new EntityTreeView( splitter ); * itemView->setModel( itemList ); * @endcode * * The SelectionProxyModel can handle complex selections. * * See the KSelectionProxyModel documentation for the valid configurations of a Akonadi::SelectionProxyModel. * * Obviously, the SelectionProxyModel may be used in a view, or further processed with other proxy models. Typically, the result * from this model will be further filtered to remove collections from the item list as in the above example. * * There are several advantages of using EntityTreeModel with the SelectionProxyModel, namely the items can be fetched and cached * instead of being fetched many times, and the chain of proxies from the core model to the view is automatically handled. There is * no need to manage all the mapToSource and mapFromSource calls manually. * * A KDescendantsProxyModel can be used to represent all descendants of a model as a flat list. * For example, to show all descendant items in a selected Collection in a list: * @code * collectionTree = new EntityMimeTypeFilterModel( this ); * collectionTree->setSourceModel( entityTreeModel ); * * // Include only collections in this proxy model. * collectionTree->addMimeTypeInclusionFilter( Collection::mimeType() ); * collectionTree->setHeaderGroup( EntityTreeModel::CollectionTreeHeaders ); * * treeview->setModel( collectionTree ); * * SelectionProxyModel *selProxy = new SelectionProxyModel( treeview->selectionModel(), this ); * selProxy->setSourceModel( entityTreeModel ); * * descendedList = new DescendantEntitiesProxyModel( this ); * descendedList->setSourceModel( selProxy ); * * itemList = new EntityMimeTypeFilterModel( this ); * itemList->setSourceModel( descendedList ); * * // Exclude collections from the list view. * itemList->addMimeTypeExclusionFilter( Collection::mimeType() ); * itemList->setHeaderGroup( EntityTreeModel::ItemListHeaders ); * * listView = new EntityTreeView( this ); * listView->setModel( itemList ); * @endcode * * * Note that it is important in this case to use the DescendantEntitesProxyModel before the EntityMimeTypeFilterModel. * Otherwise, by filtering out the collections first, you would also be filtering out their child items. * * This pattern is used in KAddressBook. * * It would not make sense to use a KDescendantsProxyModel with LazyPopulation. * *

Subclassing EntityTreeModel

* * Usually an application will create a subclass of an EntityTreeModel and use that in several views via proxy models. * * The subclassing is necessary in order for the data in the model to have type-specific representation in applications * * For example, the headerData for an EntityTreeModel will be different depending on whether it is in a view showing only Collections * in which case the header data should be "AddressBooks" for example, or only Items, in which case the headerData would be * for example "Family Name", "Given Name" and "Email addres" for contacts or "Subject", "Sender", "Date" in the case of emails. * * Additionally, the actual data shown in the rows of the model should be type specific. * * In summary, it must be possible to have different numbers of columns, different data in hte rows of those columns, and different * titles for each column depending on the contents of the view. * * The way this is accomplished is by using the EntityMimeTypeFilterModel for splitting the model into a "CollectionTree" and an "Item List" * as in the above example, and using a type-specific EntityTreeModel subclass to return the type-specific data, typically for only one type (for example, contacts or emails). * * The following protected virtual methods should be implemented in the subclass: * - int entityColumnCount( HeaderGroup headerGroup ) const; * -- Implement to return the number of columns for a HeaderGroup. If the HeaderGroup is CollectionTreeHeaders, return the number of columns to display for the * Collection tree, and if it is ItemListHeaders, return the number of columns to display for the item. In the case of addressee, this could be for example, * two (for given name and family name) or for emails it could be three (for subject, sender, date). This is a decision of the subclass implementor. * - QVariant entityHeaderData( int section, Qt::Orientation orientation, int role, HeaderGroup headerGroup ) const; * -- Implement to return the data for each section for a HeaderGroup. For example, if the header group is CollectionTreeHeaders in a contacts model, * the string "Address books" might be returned for column 0, whereas if the headerGroup is ItemListHeaders, the strings "Given Name", "Family Name", * "Email Address" might be returned for the columns 0, 1, and 2. * - QVariant entityData( const Collection &collection, int column, int role = Qt::DisplayRole ) const; * -- Implement to return data for a particular Collection. Typically this will be the name of the collection or the EntityDisplayAttribute. * - QVariant entityData( const Item &item, int column, int role = Qt::DisplayRole ) const; * -- Implement to return the data for a particular item and column. In the case of email for example, this would be the actual subject, sender and date of the email. * * @note The entityData methods are just for convenience. the QAbstractItemMOdel::data method can be overridden if required. * * The application writer must then properly configure proxy models for the views, so that the correct data is shown in the correct view. * That is the purpose of these lines in the above example * * @code * collectionTree->setHeaderGroup( EntityTreeModel::CollectionTreeHeaders ); * itemList->setHeaderGroup( EntityTreeModel::ItemListHeaders ); * @endcode * * @author Stephen Kelly * @since 4.4 */ class AKONADI_EXPORT EntityTreeModel : public QAbstractItemModel { Q_OBJECT public: /** * Describes the roles for items. Roles for collections are defined by the superclass. */ enum Roles { //sebsauer, 2009-05-07; to be able here to keep the akonadi_next EntityTreeModel compatible with //the akonadi_old ItemModel and CollectionModel, we need to use the same int-values for //ItemRole, ItemIdRole and MimeTypeRole like the Akonadi::ItemModel is using and the same //CollectionIdRole and CollectionRole like the Akonadi::CollectionModel is using. ItemIdRole = Qt::UserRole + 1, ///< The item id ItemRole = Qt::UserRole + 2, ///< The Item MimeTypeRole = Qt::UserRole + 3, ///< The mimetype of the entity CollectionIdRole = Qt::UserRole + 10, ///< The collection id. CollectionRole = Qt::UserRole + 11, ///< The collection. RemoteIdRole, ///< The remoteId of the entity CollectionChildOrderRole, ///< Ordered list of child items if available AmazingCompletionRole, ///< Role used to implement amazing completion ParentCollectionRole, ///< The parent collection of the entity ColumnCountRole, ///< @internal Used by proxies to determine the number of columns for a header group. LoadedPartsRole, ///< Parts available in the model for the item AvailablePartsRole, ///< Parts available in the Akonadi server for the item SessionRole, ///< @internal The Session used by this model CollectionRefRole, ///< @internal Used to increase the reference count on a Collection CollectionDerefRole, ///< @internal Used to decrease the reference count on a Collection PendingCutRole, ///< @internal Used to indicate items which are to be cut EntityUrlRole, ///< The akonadi:/ Url of the entity as a string. Item urls will contain the mimetype. UserRole = Qt::UserRole + 500, ///< First role for user extensions. TerminalUserRole = 2000, ///< Last role for user extensions. Don't use a role beyond this or headerData will break. EndRole = 65535 }; /** * Describes what header information the model shall return. */ enum HeaderGroup { EntityTreeHeaders, ///< Header information for a tree with collections and items CollectionTreeHeaders, ///< Header information for a collection-only tree ItemListHeaders, ///< Header information for a list of items UserHeaders = 10, ///< Last header information for submodel extensions EndHeaderGroup = 32 ///< Last headergroup role. Don't use a role beyond this or headerData will break. // Note that we're splitting up available roles for the header data hack and int(EndRole / TerminalUserRole) == 32 }; /** * Creates a new entity tree model. * * @param session The Session to use to communicate with Akonadi. * @param monitor The ChangeRecorder whose entities should be represented in the model. * @param parent The parent object. */ - EntityTreeModel( Session *session, ChangeRecorder *monitor, QObject *parent = 0 ); + explicit EntityTreeModel( ChangeRecorder *monitor, QObject *parent = 0 ); /** * Destroys the entity tree model. */ virtual ~EntityTreeModel(); /** * Describes how the model should populated its items. */ enum ItemPopulationStrategy { NoItemPopulation, ///< Do not include items in the model. ImmediatePopulation, ///< Retrieve items immediately when their parent is in the model. This is the default. LazyPopulation ///< Fetch items only when requested (using canFetchMore/fetchMore) }; /** Some Entities are hidden in the model, but exist for internal purposes, for example, custom object directories in groupware resources. They are hidden by default, but can be shown by setting @p show to true. Most applications will not need to use this feature. */ void setShowSystemEntities( bool show ); /** @returns True if internal system entities are shown, and false otherwise. */ bool systemEntitiesShown() const; /** * Sets the item population @p strategy of the model. */ void setItemPopulationStrategy( ItemPopulationStrategy strategy ); /** * Returns the item population strategy of the model. */ ItemPopulationStrategy itemPopulationStrategy() const; /** * Sets whether the root collection shall be provided by the model. * * @see setRootCollectionDisplayName() */ void setIncludeRootCollection( bool include ); /** * Returns whether the root collection is provided by the model. */ bool includeRootCollection() const; /** * Sets the display @p name of the root collection of the model. * The default display name is "[*]". * * @note The display name for the root collection is only used if * the root collection has been included with setIncludeRootCollection(). */ void setRootCollectionDisplayName( const QString &name ); /** * Returns the display name of the root collection. */ QString rootCollectionDisplayName() const; /** * Describes what collections shall be fetched by and represent in the model. */ enum CollectionFetchStrategy { FetchNoCollections, ///< Fetches nothing. This creates an empty model. FetchFirstLevelChildCollections, ///< Fetches first level collections in the root collection. FetchCollectionsRecursive ///< Fetches collections in the root collection recursively. This is the default. }; /** * Sets the collection fetch @p strategy of the model. */ void setCollectionFetchStrategy( CollectionFetchStrategy strategy ); /** * Returns the collection fetch strategy of the model. */ CollectionFetchStrategy collectionFetchStrategy() const; virtual int columnCount( const QModelIndex & parent = QModelIndex() ) const; virtual int rowCount( const QModelIndex & parent = QModelIndex() ) const; virtual QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const; virtual QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; virtual Qt::ItemFlags flags( const QModelIndex &index ) const; virtual QStringList mimeTypes() const; virtual Qt::DropActions supportedDropActions() const; virtual QMimeData *mimeData( const QModelIndexList &indexes ) const; virtual bool dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent ); virtual bool setData( const QModelIndex &index, const QVariant &value, int role = Qt::EditRole ); virtual QModelIndex index( int row, int column, const QModelIndex & parent = QModelIndex() ) const; virtual QModelIndex parent( const QModelIndex & index ) const; // TODO: Review the implementations of these. I think they could be better. virtual bool canFetchMore( const QModelIndex & parent ) const; virtual void fetchMore( const QModelIndex & parent ); virtual bool hasChildren( const QModelIndex &parent = QModelIndex() ) const; /** * Reimplemented to handle the AmazingCompletionRole. */ virtual QModelIndexList match( const QModelIndex& start, int role, const QVariant& value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap ) ) const; protected: /** * Clears and resets the model. Always call this instead of the reset method in the superclass. * Using the reset method will not reliably clear or refill the model. */ void clearAndReset(); /** * Provided for convenience of subclasses. */ virtual QVariant entityData( const Item &item, int column, int role = Qt::DisplayRole ) const; /** * Provided for convenience of subclasses. */ virtual QVariant entityData( const Collection &collection, int column, int role = Qt::DisplayRole ) const; /** * Reimplement this to provide different header data. This is needed when using one model * with multiple proxies and views, and each should show different header data. */ virtual QVariant entityHeaderData( int section, Qt::Orientation orientation, int role, HeaderGroup headerGroup ) const; virtual int entityColumnCount( HeaderGroup headerGroup ) const; /** * Reimplement this in a subclass to return true if @p item matches @p value with @p flags in the AmazingCompletionRole. */ virtual bool entityMatch( const Item &item, const QVariant &value, Qt::MatchFlags flags ) const; /** * Reimplement this in a subclass to return true if @p collection matches @p value with @p flags in the AmazingCompletionRole. */ virtual bool entityMatch( const Collection &collection, const QVariant &value, Qt::MatchFlags flags ) const; protected: //@cond PRIVATE Q_DECLARE_PRIVATE( EntityTreeModel ) EntityTreeModelPrivate * d_ptr; - EntityTreeModel( Session *session, ChangeRecorder *monitor, EntityTreeModelPrivate *d, QObject* parent = 0 ); + EntityTreeModel( ChangeRecorder *monitor, EntityTreeModelPrivate *d, QObject* parent = 0 ); //@endcond private: //@cond PRIVATE // Make these private, they shouldn't be called by applications virtual bool insertRows( int , int, const QModelIndex& = QModelIndex() ); virtual bool insertColumns( int, int, const QModelIndex& = QModelIndex() ); virtual bool removeColumns( int, int, const QModelIndex& = QModelIndex() ); virtual bool removeRows( int, int, const QModelIndex & = QModelIndex() ); Q_PRIVATE_SLOT( d_func(), void monitoredCollectionStatisticsChanged( Akonadi::Collection::Id, const Akonadi::CollectionStatistics& ) ) Q_PRIVATE_SLOT( d_func(), void rootCollectionFetched(Akonadi::Collection::List) ) Q_PRIVATE_SLOT( d_func(), void startFirstListJob() ) // Q_PRIVATE_SLOT( d_func(), void slotModelReset() ) // TODO: Can I merge these into one jobResult slot? Q_PRIVATE_SLOT( d_func(), void fetchJobDone( KJob *job ) ) Q_PRIVATE_SLOT( d_func(), void pasteJobDone( KJob *job ) ) Q_PRIVATE_SLOT( d_func(), void updateJobDone( KJob *job ) ) Q_PRIVATE_SLOT( d_func(), void itemsFetched( Akonadi::Item::List ) ) Q_PRIVATE_SLOT( d_func(), void collectionsFetched( Akonadi::Collection::List ) ) Q_PRIVATE_SLOT( d_func(), void topLevelCollectionsFetched( Akonadi::Collection::List ) ) Q_PRIVATE_SLOT( d_func(), void ancestorsFetched( Akonadi::Collection::List ) ) Q_PRIVATE_SLOT( d_func(), void monitoredMimeTypeChanged( const QString&, bool ) ) Q_PRIVATE_SLOT( d_func(), void monitoredCollectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredCollectionRemoved( const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredCollectionChanged( const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredCollectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection&) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemRemoved( const Akonadi::Item& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemChanged( const Akonadi::Item&, const QSet& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemLinked( const Akonadi::Item&, const Akonadi::Collection& ) ) Q_PRIVATE_SLOT( d_func(), void monitoredItemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ) ) //@endcond }; } // namespace #endif diff --git a/akonadi/entitytreemodel_p.cpp b/akonadi/entitytreemodel_p.cpp index c422cd259..699c940ca 100644 --- a/akonadi/entitytreemodel_p.cpp +++ b/akonadi/entitytreemodel_p.cpp @@ -1,1178 +1,1178 @@ /* Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "entitytreemodel_p.h" #include "entitytreemodel.h" #include "monitor_p.h" // For friend ref/deref #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Akonadi; EntityTreeModelPrivate::EntityTreeModelPrivate( EntityTreeModel *parent ) : q_ptr( parent ), m_collectionFetchStrategy( EntityTreeModel::FetchCollectionsRecursive ), m_itemPopulation( EntityTreeModel::ImmediatePopulation ), m_includeUnsubscribed( true ), m_includeStatistics( false ), m_showRootCollection( false ), m_showSystemEntities( false ) { } -void EntityTreeModelPrivate::init( ChangeRecorder *monitor, Session *session ) +void EntityTreeModelPrivate::init( ChangeRecorder *monitor ) { Q_Q( EntityTreeModel ); m_monitor = monitor; - m_session = session; + m_session = m_monitor->session(); m_monitor->setChangeRecordingEnabled( false ); m_includeStatistics = true; m_monitor->fetchCollectionStatistics( true ); m_monitor->collectionFetchScope().setAncestorRetrieval( Akonadi::CollectionFetchScope::All ); m_mimeChecker.setWantedMimeTypes( m_monitor->mimeTypesMonitored() ); q->connect( monitor, SIGNAL( mimeTypeMonitored( const QString&, bool ) ), SLOT( monitoredMimeTypeChanged( const QString&, bool ) ) ); // monitor collection changes q->connect( monitor, SIGNAL( collectionChanged( const Akonadi::Collection& ) ), SLOT( monitoredCollectionChanged( const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( collectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ) ), SLOT( monitoredCollectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( collectionRemoved( const Akonadi::Collection& ) ), SLOT( monitoredCollectionRemoved( const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( collectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection& ) ), SLOT( monitoredCollectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); if ( !monitor->itemFetchScope().isEmpty() ) { // Monitor item changes. q->connect( monitor, SIGNAL( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ), SLOT( monitoredItemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( itemChanged( const Akonadi::Item&, const QSet& ) ), SLOT( monitoredItemChanged( const Akonadi::Item&, const QSet& ) ) ); q->connect( monitor, SIGNAL( itemRemoved( const Akonadi::Item& ) ), SLOT( monitoredItemRemoved( const Akonadi::Item& ) ) ); q->connect( monitor, SIGNAL( itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ), SLOT( monitoredItemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( itemLinked( const Akonadi::Item&, const Akonadi::Collection& ) ), SLOT( monitoredItemLinked( const Akonadi::Item&, const Akonadi::Collection& ) ) ); q->connect( monitor, SIGNAL( itemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ) ), SLOT( monitoredItemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ) ) ); } q->connect( monitor, SIGNAL( collectionStatisticsChanged( Akonadi::Collection::Id, const Akonadi::CollectionStatistics& ) ), SLOT( monitoredCollectionStatisticsChanged( Akonadi::Collection::Id, const Akonadi::CollectionStatistics& ) ) ); QList list = monitor->collectionsMonitored(); if ( list.size() == 1 ) m_rootCollection = list.first(); else m_rootCollection = Collection::root(); m_rootCollectionDisplayName = QLatin1String( "[*]" ); fillModel(); } int EntityTreeModelPrivate::indexOf( const QList &nodes, Entity::Id id ) const { int i = 0; foreach ( const Node *node, nodes ) { if ( node->id == id ) return i; i++; } return -1; } ItemFetchJob* EntityTreeModelPrivate::getItemFetchJob( const Collection &parent, const ItemFetchScope &scope ) const { ItemFetchJob *itemJob = new Akonadi::ItemFetchJob( parent, m_session ); itemJob->setFetchScope( scope ); itemJob->fetchScope().setAncestorRetrieval( ItemFetchScope::All ); return itemJob; } ItemFetchJob* EntityTreeModelPrivate::getItemFetchJob( const Item &item, const ItemFetchScope &scope ) const { ItemFetchJob *itemJob = new Akonadi::ItemFetchJob( item, m_session ); itemJob->setFetchScope( scope ); return itemJob; } void EntityTreeModelPrivate::runItemFetchJob( ItemFetchJob *itemFetchJob, const Collection &parent ) const { Q_Q( const EntityTreeModel ); // TODO: This hack is probably not needed anymore. Remove it. // ### HACK: itemsReceivedFromJob needs to know which collection items were added to. // That is not provided by akonadi, so we attach it in a property. itemFetchJob->setProperty( ItemFetchCollectionId(), QVariant( parent.id() ) ); q->connect( itemFetchJob, SIGNAL( itemsReceived( const Akonadi::Item::List& ) ), q, SLOT( itemsFetched( const Akonadi::Item::List& ) ) ); q->connect( itemFetchJob, SIGNAL( result( KJob* ) ), q, SLOT( fetchJobDone( KJob* ) ) ); } void EntityTreeModelPrivate::fetchItems( const Collection &parent ) { // TODO: Use a more specific fetch scope to get only the envelope for mails etc. ItemFetchJob *itemJob = getItemFetchJob( parent, m_monitor->itemFetchScope() ); runItemFetchJob( itemJob, parent ); } void EntityTreeModelPrivate::fetchCollections( const Collection &collection, CollectionFetchJob::Type type ) { Q_Q( EntityTreeModel ); CollectionFetchJob *job = new CollectionFetchJob( collection, type, m_session ); job->fetchScope().setIncludeUnsubscribed( m_includeUnsubscribed ); job->fetchScope().setIncludeStatistics( m_includeStatistics ); job->fetchScope().setContentMimeTypes( m_monitor->mimeTypesMonitored() ); job->fetchScope().setAncestorRetrieval( Akonadi::CollectionFetchScope::All ); q->connect( job, SIGNAL( collectionsReceived( const Akonadi::Collection::List& ) ), q, SLOT( collectionsFetched( const Akonadi::Collection::List& ) ) ); q->connect( job, SIGNAL( result( KJob* ) ), q, SLOT( fetchJobDone( KJob* ) ) ); } bool EntityTreeModelPrivate::isHidden( const Entity &entity ) const { if ( m_showSystemEntities ) return false; if ( entity.id() == Collection::root().id() ) return false; if ( entity.hasAttribute() ) return true; const Collection parent = entity.parentCollection(); if ( parent.isValid() ) return isHidden( parent ); return false; } void EntityTreeModelPrivate::collectionsFetched( const Akonadi::Collection::List& collections ) { Q_Q( EntityTreeModel ); QListIterator it( collections ); QHash collectionsToInsert; QHash > subTreesToInsert; QHash parents; while ( it.hasNext() ) { const Collection collection = it.next(); if ( isHidden( collection ) ) continue; if ( m_collections.contains( collection.id() ) ) { // This is probably the result of a parent of a previous collection already being in the model. // Replace the dummy collection with the real one and move on. m_collections[ collection.id() ] = collection; const QModelIndex collectionIndex = indexForCollection( collection ); dataChanged( collectionIndex, collectionIndex ); continue; } Collection parent = collection; Collection tmp; while ( !m_collections.contains( parent.parentCollection().id() ) ) { if ( !subTreesToInsert[ parent.parentCollection().id() ].contains( parent.parentCollection().id() ) ) { subTreesToInsert[ parent.parentCollection().id() ].append( parent.parentCollection().id() ); collectionsToInsert.insert( parent.parentCollection().id(), parent.parentCollection() ); } foreach( Collection::Id collectionId, subTreesToInsert.take( parent.id() ) ) { if ( !subTreesToInsert[ parent.parentCollection().id() ].contains( collectionId ) ) subTreesToInsert[ parent.parentCollection().id() ].append( collectionId ); } tmp = parent.parentCollection(); parent = tmp; } if ( !subTreesToInsert[ parent.id() ].contains( collection.id() ) ) subTreesToInsert[ parent.id() ].append( collection.id() ); collectionsToInsert.insert( collection.id(), collection ); if ( !parents.contains( parent.id() ) ) parents.insert( parent.id(), parent.parentCollection() ); } const int row = 0; QHashIterator > collectionIt( subTreesToInsert ); while ( collectionIt.hasNext() ) { collectionIt.next(); const Collection::Id topCollectionId = collectionIt.key(); Q_ASSERT( !m_collections.contains( topCollectionId ) ); Q_ASSERT( parents.contains( topCollectionId ) ); const QModelIndex parentIndex = indexForCollection( parents.value( topCollectionId ) ); q->beginInsertRows( parentIndex, row, row ); Q_ASSERT( !collectionIt.value().isEmpty() ); Q_ASSERT( m_collections.contains( parents.value( topCollectionId ).id() ) ); foreach( Collection::Id collectionId, collectionIt.value() ) { const Collection collection = collectionsToInsert.take( collectionId ); Q_ASSERT( collection.isValid() ); m_collections.insert( collectionId, collection ); Node *node = new Node; node->id = collectionId; node->parent = collection.parentCollection().id(); node->type = Node::Collection; m_childEntities[ collection.parentCollection().id() ].prepend( node ); } q->endInsertRows(); if ( m_itemPopulation == EntityTreeModel::ImmediatePopulation ) foreach( const Collection::Id &collectionId, collectionIt.value() ) fetchItems( m_collections.value( collectionId ) ); } } void EntityTreeModelPrivate::itemsFetched( const Akonadi::Item::List& items ) { Q_Q( EntityTreeModel ); QObject *job = q->sender(); Q_ASSERT( job ); const Collection::Id collectionId = job->property( ItemFetchCollectionId() ).value(); Item::List itemsToInsert; Item::List itemsToUpdate; const Collection collection = m_collections.value( collectionId ); Q_ASSERT( collection.isValid() ); const QList collectionEntities = m_childEntities.value( collectionId ); foreach ( const Item &item, items ) { if ( isHidden( item ) ) continue; if ( indexOf( collectionEntities, item.id() ) != -1 ) { itemsToUpdate << item; } else { if ( m_mimeChecker.wantedMimeTypes().isEmpty() || m_mimeChecker.isWantedItem( item ) ) { itemsToInsert << item; } } } if ( itemsToInsert.size() > 0 ) { const int startRow = m_childEntities.value( collectionId ).size(); Q_ASSERT( m_collections.contains( collectionId ) ); const QModelIndex parentIndex = indexForCollection( m_collections.value( collectionId ) ); q->beginInsertRows( parentIndex, startRow, startRow + items.size() - 1 ); foreach ( const Item &item, items ) { const Item::Id itemId = item.id(); m_items.insert( itemId, item ); Node *node = new Node; node->id = itemId; node->parent = collectionId; node->type = Node::Item; m_childEntities[ collectionId ].append( node ); } q->endInsertRows(); } if ( itemsToUpdate.size() > 0 ) { foreach ( const Item &item, itemsToUpdate ) { m_items[ item.id() ].apply( item ); foreach ( const QModelIndex &index, indexesForItem( item ) ) { dataChanged( index, index ); } } } } void EntityTreeModelPrivate::monitoredMimeTypeChanged( const QString & mimeType, bool monitored ) { if ( monitored ) m_mimeChecker.addWantedMimeType( mimeType ); else m_mimeChecker.removeWantedMimeType( mimeType ); } void EntityTreeModelPrivate::retrieveAncestors( const Akonadi::Collection& collection ) { Q_Q( EntityTreeModel ); Collection parentCollection = collection.parentCollection(); Q_ASSERT( parentCollection != Collection::root() ); Collection temp; Collection::List ancestors; while ( !m_collections.contains( parentCollection.id() ) ) { // Put a temporary node in the tree later. ancestors.prepend( parentCollection ); // Fetch the real ancestor CollectionFetchJob *job = new CollectionFetchJob( parentCollection, CollectionFetchJob::Base, m_session ); job->fetchScope().setIncludeUnsubscribed( m_includeUnsubscribed ); job->fetchScope().setIncludeStatistics( m_includeStatistics ); q->connect( job, SIGNAL( collectionsReceived( const Akonadi::Collection::List& ) ), q, SLOT( ancestorsFetched( const Akonadi::Collection::List& ) ) ); q->connect( job, SIGNAL( result( KJob* ) ), q, SLOT( fetchJobDone( KJob* ) ) ); temp = parentCollection.parentCollection(); parentCollection = temp; } const QModelIndex parent = indexForCollection( parentCollection ); // Still prepending all collections for now. int row = 0; // Although we insert several Collections here, we only need to notify though the model // about the top-level one. The rest will be found auotmatically by the view. q->beginInsertRows( parent, row, row ); Collection::List::const_iterator it; const Collection::List::const_iterator begin = ancestors.constBegin(); const Collection::List::const_iterator end = ancestors.constEnd(); for ( it = begin; it != end; ++it ) { const Collection collection = *it; m_collections.insert( collection.id(), collection ); Node *node = new Node; node->id = collection.id(); node->parent = collection.parentCollection().id(); node->type = Node::Collection; m_childEntities[ node->parent ].prepend( node ); } q->endInsertRows(); } void EntityTreeModelPrivate::ancestorsFetched( const Akonadi::Collection::List& collectionList ) { Q_ASSERT( collectionList.size() == 1 ); const Collection collection = collectionList.at( 0 ); m_collections[ collection.id() ] = collection; const QModelIndex index = indexForCollection( collection ); Q_ASSERT( index.isValid() ); dataChanged( index, index ); } void EntityTreeModelPrivate::insertCollection( const Akonadi::Collection& collection, const Akonadi::Collection& parent ) { Q_ASSERT( collection.isValid() ); Q_ASSERT( parent.isValid() ); Q_Q( EntityTreeModel ); // TODO: Use order attribute of parent if available // Otherwise prepend collections and append items. Currently this prepends all collections. // Or I can prepend and append for single signals, then 'change' the parent. // QList childCols = m_childEntities.value( parent.id() ); // int row = childCols.size(); // int numChildCols = childCollections.value( parent.id() ).size(); const int row = 0; const QModelIndex parentIndex = indexForCollection( parent ); q->beginInsertRows( parentIndex, row, row ); m_collections.insert( collection.id(), collection ); Node *node = new Node; node->id = collection.id(); node->parent = parent.id(); node->type = Node::Collection; m_childEntities[ parent.id() ].prepend( node ); q->endInsertRows(); } void EntityTreeModelPrivate::monitoredCollectionAdded( const Akonadi::Collection& collection, const Akonadi::Collection& parent ) { if ( isHidden( collection ) ) return; // If the resource is removed while populating the model with it, we might still // get some monitor signals. These stale/out-of-order signals can't be completely eliminated // in the akonadi server due to implementation details, so we also handle such signals in the model silently // in all the monitored slots. // Stephen Kelly, 28, July 2009 // This is currently temporarily blocked by a uninitialized value bug in the server. // if ( !m_collections.contains( parent.id() ) ) // { // kWarning() << "Got a stale notification for a collection whose parent was already removed." << collection.id() << collection.remoteId(); // return; // } // Some collection trees contain multiple mimetypes. Even though server side filtering ensures we // only get the ones we're interested in from the job, we have to filter on collections received through signals too. if ( !m_mimeChecker.wantedMimeTypes().isEmpty() && !m_mimeChecker.isWantedCollection( collection ) ) return; if ( !m_collections.contains( parent.id() ) ) { // The collection we're interested in is contained in a collection we're not interested in. // We download the ancestors of the collection we're interested in to complete the tree. retrieveAncestors( collection ); return; } insertCollection( collection, parent ); } void EntityTreeModelPrivate::monitoredCollectionRemoved( const Akonadi::Collection& collection ) { if ( isHidden( collection ) ) return; Collection::Id parentId = collection.parentCollection().id(); if ( parentId < 0 ) parentId = -1; if ( !m_collections.contains( parentId ) ) return; Q_Q( EntityTreeModel ); // This may be a signal for a collection we've already removed by removing its ancestor. if ( !m_collections.contains( collection.id() ) ) { kWarning() << "Got a stale notification for a collection which was already removed." << collection.id() << collection.remoteId(); return; } Q_ASSERT( m_childEntities.contains( parentId ) ); const int row = indexOf( m_childEntities.value( parentId ), collection.id() ); Q_ASSERT( row >= 0 ); Q_ASSERT( m_collections.contains( parentId ) ); const QModelIndex parentIndex = indexForCollection( m_collections.value( parentId ) ); q->beginRemoveRows( parentIndex, row, row ); // Delete all descendant collections and items. removeChildEntities( collection.id() ); // Remove deleted collection from its parent. m_childEntities[ parentId ].removeAt( row ); q->endRemoveRows(); } void EntityTreeModelPrivate::removeChildEntities( Collection::Id collectionId ) { QList::const_iterator it; QList childList = m_childEntities.value( collectionId ); const QList::const_iterator begin = childList.constBegin(); const QList::const_iterator end = childList.constEnd(); for ( it = begin; it != end; ++it ) { if ( Node::Item == (*it)->type ) m_items.remove( (*it)->id ); else { removeChildEntities( (*it)->id ); m_collections.remove( (*it)->id ); } } m_childEntities.remove( collectionId ); } void EntityTreeModelPrivate::monitoredCollectionMoved( const Akonadi::Collection& collection, const Akonadi::Collection& sourceCollection, const Akonadi::Collection& destCollection ) { if ( isHidden( collection ) ) return; if ( isHidden( sourceCollection ) ) { if ( isHidden( destCollection ) ) return; monitoredCollectionAdded( collection, destCollection ); return; } else if ( isHidden( destCollection ) ) { monitoredCollectionRemoved( collection ); return; } if ( !m_collections.contains( collection.id() ) ) { kWarning() << "Got a stale notification for a collection which was already removed." << collection.id() << collection.remoteId(); return; } Q_Q( EntityTreeModel ); const QModelIndex srcParentIndex = indexForCollection( sourceCollection ); const QModelIndex destParentIndex = indexForCollection( destCollection ); Q_ASSERT( collection.parentCollection() == destCollection ); const int srcRow = indexOf( m_childEntities.value( sourceCollection.id() ), collection.id() ); const int destRow = 0; // Prepend collections if ( !q->beginMoveRows( srcParentIndex, srcRow, srcRow, destParentIndex, destRow ) ) { kWarning() << "Invalid move"; return; } Node *node = m_childEntities[ sourceCollection.id() ].takeAt( srcRow ); // collection has the correct parentCollection etc. We need to set it on the // internal data structure to not corrupt things. m_collections.insert( collection.id(), collection ); node->parent = destCollection.id(); m_childEntities[ destCollection.id() ].prepend( node ); q->endMoveRows(); } void EntityTreeModelPrivate::monitoredCollectionChanged( const Akonadi::Collection &collection ) { if ( isHidden( collection ) ) return; if ( !m_collections.contains( collection.id() ) ) { kWarning() << "Got a stale notification for a collection which was already removed." << collection.id() << collection.remoteId(); return; } m_collections[ collection.id() ] = collection; const QModelIndex index = indexForCollection( collection ); Q_ASSERT( index.isValid() ); dataChanged( index, index ); } void EntityTreeModelPrivate::monitoredCollectionStatisticsChanged( Akonadi::Collection::Id id, const Akonadi::CollectionStatistics &statistics ) { return; // Temporarily disabled if ( !m_collections.contains( id ) ) { kWarning() << "Got statistics response for non-existing collection:" << id; } else { m_collections[ id ].setStatistics( statistics ); const QModelIndex index = indexForCollection( m_collections[ id ] ); dataChanged( index, index ); } } void EntityTreeModelPrivate::monitoredItemAdded( const Akonadi::Item& item, const Akonadi::Collection& collection ) { Q_Q( EntityTreeModel ); if ( isHidden( item ) ) return; if ( !m_collections.contains( collection.id() ) ) { kWarning() << "Got a stale notification for an item whose collection was already removed." << item.id() << item.remoteId(); return; } Q_ASSERT( m_collections.contains( collection.id() ) ); if ( !m_mimeChecker.wantedMimeTypes().isEmpty() && !m_mimeChecker.isWantedItem( item ) ) return; const int row = m_childEntities.value( collection.id() ).size(); const QModelIndex parentIndex = indexForCollection( m_collections.value( collection.id() ) ); q->beginInsertRows( parentIndex, row, row ); m_items.insert( item.id(), item ); Node *node = new Node; node->id = item.id(); node->parent = collection.id(); node->type = Node::Item; m_childEntities[ collection.id() ].append( node ); q->endInsertRows(); } void EntityTreeModelPrivate::monitoredItemRemoved( const Akonadi::Item &item ) { Q_Q( EntityTreeModel ); if ( isHidden( item ) ) return; const Collection::List parents = getParentCollections( item ); if ( parents.isEmpty() ) return; if ( !m_items.contains( item.id() ) ) { kWarning() << "Got a stale notification for an item which was already removed." << item.id() << item.remoteId(); return; } // TODO: Iterate over all (virtual) collections. const Collection collection = parents.first(); Q_ASSERT( m_collections.contains( collection.id() ) ); const int row = indexOf( m_childEntities.value( collection.id() ), item.id() ); const QModelIndex parentIndex = indexForCollection( m_collections.value( collection.id() ) ); q->beginRemoveRows( parentIndex, row, row ); m_items.remove( item.id() ); m_childEntities[ collection.id() ].removeAt( row ); q->endRemoveRows(); } void EntityTreeModelPrivate::monitoredItemChanged( const Akonadi::Item &item, const QSet& ) { if ( isHidden( item ) ) return; if ( !m_items.contains( item.id() ) ) { kWarning() << "Got a stale notification for an item which was already removed." << item.id() << item.remoteId(); return; } m_items[ item.id() ].apply( item ); const QModelIndexList indexes = indexesForItem( item ); foreach ( const QModelIndex &index, indexes ) { if ( !index.isValid() ) kWarning() << "item has invalid index:" << item.id() << item.remoteId(); else dataChanged( index, index ); } } void EntityTreeModelPrivate::monitoredItemMoved( const Akonadi::Item& item, const Akonadi::Collection& sourceCollection, const Akonadi::Collection& destCollection ) { Q_Q( EntityTreeModel ); if ( isHidden( item ) ) return; if ( isHidden( sourceCollection ) ) { if ( isHidden( destCollection ) ) return; monitoredItemAdded( item, destCollection ); return; } else if ( isHidden( destCollection ) ) { monitoredItemRemoved( item ); return; } if ( !m_items.contains( item.id() ) ) { kWarning() << "Got a stale notification for an item which was already removed." << item.id() << item.remoteId(); return; } Q_ASSERT( m_collections.contains( sourceCollection.id() ) ); Q_ASSERT( m_collections.contains( destCollection.id() ) ); const QModelIndex srcIndex = indexForCollection( sourceCollection ); const QModelIndex destIndex = indexForCollection( destCollection ); // Where should it go? Always append items and prepend collections and reorganize them with separate reactions to Attributes? const Item::Id itemId = item.id(); const int srcRow = indexOf( m_childEntities.value( sourceCollection.id() ), itemId ); const int destRow = q->rowCount( destIndex ); if ( !q->beginMoveRows( srcIndex, srcRow, srcRow, destIndex, destRow ) ) { kWarning() << "Invalid move"; return; } Node *node = m_childEntities[ sourceCollection.id() ].takeAt( srcRow ); m_items.insert( item.id(), item ); node->parent = destCollection.id(); m_childEntities[ destCollection.id() ].append( node ); q->endMoveRows(); } void EntityTreeModelPrivate::monitoredItemLinked( const Akonadi::Item& item, const Akonadi::Collection& collection ) { Q_Q( EntityTreeModel ); if ( isHidden( item ) ) return; if ( !m_items.contains( item.id() ) ) { kWarning() << "Got a stale notification for an item which was already removed." << item.id() << item.remoteId(); return; } Q_ASSERT( m_collections.contains( collection.id() ) ); if ( !m_mimeChecker.wantedMimeTypes().isEmpty() && !m_mimeChecker.isWantedItem( item ) ) return; const int row = m_childEntities.value( collection.id() ).size(); const QModelIndex parentIndex = indexForCollection( m_collections.value( collection.id() ) ); q->beginInsertRows( parentIndex, row, row ); Node *node = new Node; node->id = item.id(); node->parent = collection.id(); node->type = Node::Item; m_childEntities[ collection.id() ].append( node ); q->endInsertRows(); } void EntityTreeModelPrivate::monitoredItemUnlinked( const Akonadi::Item& item, const Akonadi::Collection& collection ) { Q_Q( EntityTreeModel ); if ( isHidden( item ) ) return; if ( !m_items.contains( item.id() ) ) { kWarning() << "Got a stale notification for an item which was already removed." << item.id() << item.remoteId(); return; } Q_ASSERT( m_collections.contains( collection.id() ) ); const int row = indexOf( m_childEntities.value( collection.id() ), item.id() ); const QModelIndex parentIndex = indexForCollection( m_collections.value( collection.id() ) ); q->beginRemoveRows( parentIndex, row, row ); m_childEntities[ collection.id() ].removeAt( row ); q->endRemoveRows(); } void EntityTreeModelPrivate::fetchJobDone( KJob *job ) { if ( job->error() ) kWarning() << "Job error: " << job->errorString() << endl; } void EntityTreeModelPrivate::pasteJobDone( KJob *job ) { if ( job->error() ) kWarning() << "Job error: " << job->errorString() << endl; } void EntityTreeModelPrivate::updateJobDone( KJob *job ) { if ( job->error() ) { // TODO: handle job errors kWarning() << "Job error:" << job->errorString(); } else { ItemModifyJob *modifyJob = qobject_cast( job ); if ( !modifyJob ) return; const Item item = modifyJob->item(); Q_ASSERT( item.isValid() ); m_items[ item.id() ].apply( item ); const QModelIndexList list = indexesForItem( item ); foreach ( const QModelIndex &index, list ) dataChanged( index, index ); // TODO: Is this trying to do the job of collectionstatisticschanged? // CollectionStatisticsJob *csjob = static_cast( job ); // Collection result = csjob->collection(); // collectionStatisticsChanged( result.id(), csjob->statistics() ); } } void EntityTreeModelPrivate::rootCollectionFetched( const Collection::List &list ) { Q_ASSERT( list.size() == 1 ); m_rootCollection = list.first(); startFirstListJob(); } void EntityTreeModelPrivate::startFirstListJob() { Q_Q( EntityTreeModel ); if ( m_collections.size() > 0 ) return; // Even if the root collection is the invalid collection, we still need to start // the first list job with Collection::root. if ( m_showRootCollection ) { // Notify the outside that we're putting collection::root into the model. q->beginInsertRows( QModelIndex(), 0, 0 ); m_collections.insert( m_rootCollection.id(), m_rootCollection ); m_rootNode = new Node; m_rootNode->id = m_rootCollection.id(); m_rootNode->parent = -1; m_rootNode->type = Node::Collection; m_childEntities[ -1 ].append( m_rootNode ); q->endInsertRows(); } else { // Otherwise store it silently because it's not part of the usable model. m_rootNode = new Node; m_rootNode->id = m_rootCollection.id(); m_rootNode->parent = -1; m_rootNode->type = Node::Collection; m_collections.insert( m_rootCollection.id(), m_rootCollection ); } // Includes recursive trees. Lower levels are fetched in the onRowsInserted slot if // necessary. // HACK: fix this for recursive listing if we filter on mimetypes that only exit deeper // in the hierarchy if ( ( m_collectionFetchStrategy == EntityTreeModel::FetchFirstLevelChildCollections ) /*|| ( m_collectionFetchStrategy == EntityTreeModel::FetchCollectionsRecursive )*/ ) { fetchCollections( m_rootCollection, CollectionFetchJob::FirstLevel ); } if ( m_collectionFetchStrategy == EntityTreeModel::FetchCollectionsRecursive ) fetchCollections( m_rootCollection, CollectionFetchJob::Recursive ); // If the root collection is not collection::root, then it could have items, and they will need to be // retrieved now. if ( m_itemPopulation != EntityTreeModel::NoItemPopulation ) { if ( m_rootCollection != Collection::root() ) fetchItems( m_rootCollection ); } // Resources which are explicitly monitored won't have appeared yet if their mimetype didn't match. // We fetch the top level collections and examine them for whether to add them. // This fetches virtual collections into the tree. if ( !m_monitor->resourcesMonitored().isEmpty() ) fetchTopLevelCollections(); } void EntityTreeModelPrivate::fetchTopLevelCollections() const { Q_Q( const EntityTreeModel ); CollectionFetchJob *job = new CollectionFetchJob( Collection::root(), CollectionFetchJob::FirstLevel, m_session ); q->connect( job, SIGNAL( collectionsReceived( const Akonadi::Collection::List& ) ), q, SLOT( topLevelCollectionsFetched( const Akonadi::Collection::List& ) ) ); q->connect( job, SIGNAL( result( KJob* ) ), q, SLOT( fetchJobDone( KJob* ) ) ); } void EntityTreeModelPrivate::topLevelCollectionsFetched( const Akonadi::Collection::List& list ) { Q_Q( EntityTreeModel ); foreach( const Collection &collection, list ) { // These collections have been explicitly shown in the Monitor, // but hidden trumps that for now. This may change in the future if we figure out a use for it. if ( isHidden( collection ) ) continue; if ( m_monitor->resourcesMonitored().contains( collection.resource().toUtf8() ) && !m_collections.contains( collection.id() ) ) { const QModelIndex parentIndex = indexForCollection( collection.parentCollection() ); // Prepending new collections. const int row = 0; q->beginInsertRows( parentIndex, row, row ); m_collections.insert( collection.id(), collection ); Node *node = new Node; node->id = collection.id(); node->parent = collection.parentCollection().id(); node->type = Node::Collection; m_childEntities[ collection.parentCollection().id() ].prepend( node ); q->endInsertRows(); CollectionFetchJob *job = new CollectionFetchJob( collection, CollectionFetchJob::FirstLevel, m_session ); job->fetchScope().setIncludeUnsubscribed( m_includeUnsubscribed ); job->fetchScope().setIncludeStatistics( m_includeStatistics ); job->fetchScope().setAncestorRetrieval( Akonadi::CollectionFetchScope::All ); q->connect( job, SIGNAL( collectionsReceived( const Akonadi::Collection::List& ) ), q, SLOT( collectionsFetched( const Akonadi::Collection::List& ) ) ); q->connect( job, SIGNAL( result( KJob* ) ), q, SLOT( fetchJobDone( KJob* ) ) ); } } } Collection EntityTreeModelPrivate::getParentCollection( Entity::Id id ) const { QHashIterator > iter( m_childEntities ); while ( iter.hasNext() ) { iter.next(); if ( indexOf( iter.value(), id ) != -1 ) { return m_collections.value( iter.key() ); } } return Collection(); } Collection::List EntityTreeModelPrivate::getParentCollections( const Item &item ) const { Collection::List list; QHashIterator > iter( m_childEntities ); while ( iter.hasNext() ) { iter.next(); if ( indexOf( iter.value(), item.id() ) != -1 ) { list << m_collections.value( iter.key() ); } } return list; } Collection EntityTreeModelPrivate::getParentCollection( const Collection &collection ) const { return m_collections.value( collection.parentCollection().id() ); } Entity::Id EntityTreeModelPrivate::childAt( Collection::Id id, int position, bool *ok ) const { const QList list = m_childEntities.value( id ); if ( list.size() <= position ) { *ok = false; return 0; } *ok = true; return list.at( position )->id; } int EntityTreeModelPrivate::indexOf( Collection::Id parent, Collection::Id collectionId ) const { return indexOf( m_childEntities.value( parent ), collectionId ); } Item EntityTreeModelPrivate::getItem( Item::Id id ) const { if ( id > 0 ) id *= -1; return m_items.value( id ); } void EntityTreeModelPrivate::ref( Collection::Id id ) { m_monitor->d_ptr->ref( id ); } bool EntityTreeModelPrivate::shouldPurge( Collection::Id id ) { if ( m_monitor->d_ptr->refCountMap.contains( id ) ) return false; if ( m_monitor->d_ptr->m_buffer.isBuffered( id ) ) return false; static const int MAXITEMS = 10000; if ( m_items.size() < MAXITEMS ) return false; return true; } void EntityTreeModelPrivate::deref( Collection::Id id ) { const Collection::Id bumpedId = m_monitor->d_ptr->deref( id ); if ( bumpedId < 0 ) return; if ( shouldPurge( bumpedId ) ) purgeItems( bumpedId ); } QList::iterator EntityTreeModelPrivate::skipCollections( QList::iterator it, QList::iterator end, int * pos ) { for ( ; it != end; ++it ) { if ( ( *it )->type == Node::Item ) break; ++( *pos ); } return it; } QList::iterator EntityTreeModelPrivate::removeItems( QList::iterator it, QList::iterator end, int *pos, const Collection &collection ) { Q_Q( EntityTreeModel ); QList::iterator startIt = it; int start = *pos; for ( ; it != end; ++it ) { if ( ( *it )->type != Node::Item ) break; ++(*pos); } const QModelIndex parentIndex = indexForCollection( collection ); q->beginRemoveRows( parentIndex, start, (*pos) - 1 ); m_childEntities[ collection.id() ].erase( startIt, it ); q->endRemoveRows(); return it; } void EntityTreeModelPrivate::purgeItems( Collection::Id id ) { QList &childEntities = m_childEntities[ id ]; const Collection collection = m_collections.value( id ); Q_ASSERT( collection.isValid() ); QList::iterator begin = childEntities.begin(); const QList::iterator end = childEntities.end(); int pos = 0; while ( (begin = skipCollections( begin, end, &pos )) != end ) begin = removeItems( begin, end, &pos, collection ); } void EntityTreeModelPrivate::dataChanged( const QModelIndex &top, const QModelIndex &bottom ) { Q_Q( EntityTreeModel ); QModelIndex rightIndex; Node* node = reinterpret_cast( bottom.internalPointer() ); if ( !node ) return; if ( node->type == Node::Collection ) rightIndex = bottom.sibling( bottom.row(), q->entityColumnCount( EntityTreeModel::CollectionTreeHeaders ) - 1 ); if ( node->type == Node::Item ) rightIndex = bottom.sibling( bottom.row(), q->entityColumnCount( EntityTreeModel::ItemListHeaders ) - 1 ); emit q->dataChanged( top, rightIndex ); } QModelIndex EntityTreeModelPrivate::indexForCollection( const Collection &collection ) const { Q_Q( const EntityTreeModel ); // The id of the parent of Collection::root is not guaranteed to be -1 as assumed by startFirstListJob, // we ensure that we use -1 for the invalid Collection. const Collection::Id parentId = collection.parentCollection().isValid() ? collection.parentCollection().id() : -1; const int row = indexOf( m_childEntities.value( parentId ), collection.id() ); if ( row < 0 ) return QModelIndex(); Node *node = m_childEntities.value( parentId ).at( row ); return q->createIndex( row, 0, reinterpret_cast( node ) ); } QModelIndexList EntityTreeModelPrivate::indexesForItem( const Item &item ) const { Q_Q( const EntityTreeModel ); QModelIndexList indexes; const Collection::List collections = getParentCollections( item ); const qint64 id = item.id(); foreach ( const Collection &collection, collections ) { const int row = indexOf( m_childEntities.value( collection.id() ), id ); Node *node = m_childEntities.value( collection.id() ).at( row ); indexes << q->createIndex( row, 0, reinterpret_cast( node ) ); } return indexes; } void EntityTreeModelPrivate::beginResetModel() { Q_Q( EntityTreeModel ); q->beginResetModel(); } void EntityTreeModelPrivate::endResetModel() { Q_Q( EntityTreeModel ); m_collections.clear(); m_items.clear(); m_childEntities.clear(); q->endResetModel(); fillModel(); } void EntityTreeModelPrivate::fillModel() { Q_Q( EntityTreeModel ); if ( m_rootCollection == Collection::root() ) { QTimer::singleShot( 0, q, SLOT( startFirstListJob() ) ); } else { CollectionFetchJob *rootFetchJob = new CollectionFetchJob( m_rootCollection, CollectionFetchJob::Base, m_session ); q->connect( rootFetchJob, SIGNAL(collectionsReceived(Akonadi::Collection::List)), SLOT(rootCollectionFetched(Akonadi::Collection::List)) ); q->connect( rootFetchJob, SIGNAL(result(KJob *)), SLOT(fetchJobDone(KJob *)) ); } } diff --git a/akonadi/entitytreemodel_p.h b/akonadi/entitytreemodel_p.h index 6e4d948dd..c9562a0f8 100644 --- a/akonadi/entitytreemodel_p.h +++ b/akonadi/entitytreemodel_p.h @@ -1,231 +1,231 @@ /* Copyright (c) 2008 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ENTITYTREEMODELPRIVATE_H #define ENTITYTREEMODELPRIVATE_H #include #include #include #include #include #include "entitytreemodel.h" #include "akonadiprivate_export.h" namespace Akonadi { class ItemFetchJob; class ChangeRecorder; } struct Node { Akonadi::Entity::Id id; Akonadi::Entity::Id parent; enum Type { Item, Collection }; int type; }; namespace Akonadi { /** * @internal */ class AKONADI_TESTS_EXPORT EntityTreeModelPrivate { public: EntityTreeModelPrivate( EntityTreeModel *parent ); EntityTreeModel *q_ptr; // void collectionStatisticsChanged( Collection::Id, const Akonadi::CollectionStatistics& ); enum RetrieveDepth { Base, Recursive }; - void init( ChangeRecorder *monitor, Session *session ); + void init( ChangeRecorder *monitor ); void fetchCollections( const Collection &collection, CollectionFetchJob::Type = CollectionFetchJob::FirstLevel ); void fetchItems( const Collection &collection ); void collectionsFetched( const Akonadi::Collection::List& ); // void resourceTopCollectionsFetched( const Akonadi::Collection::List& ); void itemsFetched( const Akonadi::Item::List& ); void monitoredCollectionAdded( const Akonadi::Collection&, const Akonadi::Collection& ); void monitoredCollectionRemoved( const Akonadi::Collection& ); void monitoredCollectionChanged( const Akonadi::Collection& ); void monitoredCollectionStatisticsChanged( Akonadi::Collection::Id, const Akonadi::CollectionStatistics& ); void monitoredCollectionMoved( const Akonadi::Collection&, const Akonadi::Collection&, const Akonadi::Collection& ); void monitoredItemAdded( const Akonadi::Item&, const Akonadi::Collection& ); void monitoredItemRemoved( const Akonadi::Item& ); void monitoredItemChanged( const Akonadi::Item&, const QSet& ); void monitoredItemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ); void monitoredItemLinked( const Akonadi::Item&, const Akonadi::Collection& ); void monitoredItemUnlinked( const Akonadi::Item&, const Akonadi::Collection& ); void monitoredMimeTypeChanged( const QString &mimeType, bool monitored ); Collection getParentCollection( Entity::Id id ) const; Collection::List getParentCollections( const Item &item ) const; Collection getParentCollection( const Collection &collection ) const; Entity::Id childAt( Collection::Id, int position, bool *ok ) const; int indexOf( Collection::Id parent, Collection::Id id ) const; Item getItem( Item::Id id ) const; void removeChildEntities( Collection::Id collectionId ); void retrieveAncestors( const Akonadi::Collection& collection ); void ancestorsFetched( const Akonadi::Collection::List& collectionList ); void insertCollection( const Akonadi::Collection &collection, const Akonadi::Collection& parent ); void insertPendingCollection( const Akonadi::Collection &collection, const Akonadi::Collection& parent, QMutableListIterator &it ); void beginResetModel(); void endResetModel(); void fillModel(); ItemFetchJob* getItemFetchJob( const Collection &parent, const ItemFetchScope &scope ) const; ItemFetchJob* getItemFetchJob( const Item &item, const ItemFetchScope &scope ) const; void runItemFetchJob( ItemFetchJob* itemFetchJob, const Collection &parent ) const; QHash m_collections; QHash m_items; QHash > m_childEntities; QSet m_populatedCols; QList m_pendingCutItems; QList m_pendingCutCollections; ChangeRecorder *m_monitor; Collection m_rootCollection; Node *m_rootNode; QString m_rootCollectionDisplayName; QStringList m_mimeTypeFilter; MimeTypeChecker m_mimeChecker; EntityTreeModel::CollectionFetchStrategy m_collectionFetchStrategy; EntityTreeModel::ItemPopulationStrategy m_itemPopulation; bool m_includeUnsubscribed; bool m_includeStatistics; bool m_showRootCollection; void rootCollectionFetched( const Collection::List &list ); void startFirstListJob(); void fetchJobDone( KJob *job ); void updateJobDone( KJob *job ); void pasteJobDone( KJob *job ); /** * Returns the index of the node in @p list with the id @p id. Returns -1 if not found. */ int indexOf( const QList &list, Entity::Id id ) const; /** * The id of the collection which starts an item fetch job. This is part of a hack with QObject::sender * in itemsReceivedFromJob to correctly insert items into the model. */ static QByteArray ItemFetchCollectionId() { return "ItemFetchCollectionId"; } Session *m_session; Q_DECLARE_PUBLIC( EntityTreeModel ) void fetchTopLevelCollections() const; void topLevelCollectionsFetched( const Akonadi::Collection::List& collectionList ); /** @returns True if @p entity or one of its descemdants is hidden. */ bool isHidden( const Entity &entity ) const; bool m_showSystemEntities; void ref( Collection::Id id ); void deref( Collection::Id id ); /** @returns true if the Collection with the id of @p id should be purged. */ bool shouldPurge( Collection::Id id ); /** Purges the items in the Collection @p id */ void purgeItems( Collection::Id id ); /** Removes the items starting from @p it and up to a maximum of @p end in Collection @p col. @p pos should be the index of @p it in the m_childEntities before calling, and is updated to the position of the next Collection in m_childEntities afterward. This is required to emit model remove signals properly. @returns an iterator pointing to the next Collection after @p it, or at @p end */ QList::iterator removeItems( QList::iterator it, QList::iterator end, int *pos, const Collection &col ); /** Skips over Collections in m_childEntities up to a maximum of @p end. @p it is an iterator pointing to the first Collection in a block of Collections, and @p pos initially describes the index of @p it in m_childEntities and is updated to point to the index of the next Item in the list. @returns an iterator pointing to the next Item after @p it, or at @p end */ QList::iterator skipCollections( QList::iterator it, QList::iterator end, int *pos ); /** Emits the data changed signal for the entire row as in the subclass, instead of just for the first column. */ void dataChanged( const QModelIndex &top, const QModelIndex &bottom ); /** * Returns the model index for the given @p collection. */ QModelIndex indexForCollection( const Collection &collection ) const; /** * Returns the model indexes for the given @p item. */ QModelIndexList indexesForItem( const Item &item ) const; /** * Returns the collection for the given collection @p id. */ Collection collectionForId( Collection::Id id ) const; /** * Returns the item for the given item @p id. */ Item itemForId( Item::Id id ) const; }; } #endif diff --git a/akonadi/monitor.cpp b/akonadi/monitor.cpp index 147742217..537f2d186 100644 --- a/akonadi/monitor.cpp +++ b/akonadi/monitor.cpp @@ -1,171 +1,190 @@ /* Copyright (c) 2006 - 2007 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "monitor.h" #include "monitor_p.h" #include "itemfetchjob.h" #include "notificationmessage_p.h" #include "session.h" #include #include #include #include #include #include "collectionfetchscope.h" using namespace Akonadi; #define d d_ptr Monitor::Monitor( QObject *parent ) : QObject( parent ), d_ptr( new MonitorPrivate( this ) ) { d_ptr->init(); d_ptr->connectToNotificationManager(); } //@cond PRIVATE Monitor::Monitor(MonitorPrivate * d, QObject *parent) : QObject( parent ), d_ptr( d ) { } //@endcond Monitor::~Monitor() { delete d; } void Monitor::setCollectionMonitored( const Collection &collection, bool monitored ) { if ( monitored ) d->collections << collection; else d->collections.removeAll( collection ); emit collectionMonitored( collection, monitored ); } void Monitor::setItemMonitored( const Item & item, bool monitored ) { if ( monitored ) d->items.insert( item.id() ); else d->items.remove( item.id() ); emit itemMonitored( item, monitored ); } void Monitor::setResourceMonitored( const QByteArray & resource, bool monitored ) { if ( monitored ) d->resources.insert( resource ); else d->resources.remove( resource ); emit resourceMonitored( resource, monitored ); } void Monitor::setMimeTypeMonitored( const QString & mimetype, bool monitored ) { if ( monitored ) d->mimetypes.insert( mimetype ); else d->mimetypes.remove( mimetype ); emit mimeTypeMonitored( mimetype, monitored ); } void Akonadi::Monitor::setAllMonitored( bool monitored ) { d->monitorAll = monitored; emit allMonitored( monitored ); } void Monitor::ignoreSession(Session * session) { d->sessions << session->sessionId(); connect( session, SIGNAL(destroyed(QObject*)), this, SLOT(slotSessionDestroyed(QObject*)) ); } void Monitor::fetchCollection(bool enable) { d->fetchCollection = enable; } void Monitor::fetchCollectionStatistics(bool enable) { d->fetchCollectionStatistics = enable; } void Monitor::setItemFetchScope( const ItemFetchScope &fetchScope ) { d->mItemFetchScope = fetchScope; } ItemFetchScope &Monitor::itemFetchScope() { return d->mItemFetchScope; } void Monitor::setCollectionFetchScope( const CollectionFetchScope &fetchScope ) { d->mCollectionFetchScope = fetchScope; } CollectionFetchScope& Monitor::collectionFetchScope() { return d->mCollectionFetchScope; } Collection::List Monitor::collectionsMonitored() const { return d->collections; } QList Monitor::itemsMonitored() const { return d->items.toList(); } QStringList Monitor::mimeTypesMonitored() const { return d->mimetypes.toList(); } QList Monitor::resourcesMonitored() const { return d->resources.toList(); } bool Monitor::isAllMonitored() const { return d->monitorAll; } +void Monitor::setSession( Akonadi::Session *session ) +{ + if (session == d->session) + return; + + if (!session) + d->session = Session::defaultSession(); + else + d->session = session; + + d->itemCache.setSession(d->session); + d->collectionCache.setSession(d->session); +} + +Session* Monitor::session() const +{ + return d->session; +} + #undef d #include "monitor.moc" diff --git a/akonadi/monitor.h b/akonadi/monitor.h index fb6e84d4c..7d26ce58d 100644 --- a/akonadi/monitor.h +++ b/akonadi/monitor.h @@ -1,422 +1,433 @@ /* Copyright (c) 2006 - 2007 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_MONITOR_H #define AKONADI_MONITOR_H #include #include #include namespace Akonadi { class CollectionFetchScope; class CollectionStatistics; class Item; class ItemFetchScope; class MonitorPrivate; class Session; /** * @short Monitors an item or collection for changes. * * The Monitor emits signals if some of these objects are changed or * removed or new ones are added to the Akonadi storage. * * Optionally, the changed objects can be fetched automatically from the server. * To enable this, see itemFetchScope() and collectionFetchScope(). * * @todo Distinguish between monitoring collection properties and collection content. * @todo Special case for collection content counts changed * * @author Volker Krause */ class AKONADI_EXPORT Monitor : public QObject { Q_OBJECT public: /** * Creates a new monitor. * * @param parent The parent object. */ explicit Monitor( QObject *parent = 0 ); /** * Destroys the monitor. */ virtual ~Monitor(); /** * Sets whether the specified collection shall be monitored for changes. If * monitoring is turned on for the collection, all notifications for items * in that collection will be emitted, and its child collections will also * be monitored. Note that move notifications will be emitted if either one * of the collections involved is being monitored. * * Note that if a session is being ignored, this takes precedence over * setCollectionMonitored() on that session. * * @param collection The collection to monitor. * If this collection is Collection::root(), all collections * in the Akonadi storage will be monitored. * @param monitored Whether to monitor the collection. */ void setCollectionMonitored( const Collection &collection, bool monitored = true ); /** * Sets whether the specified item shall be monitored for changes. * * Note that if a session is being ignored, this takes precedence over * setItemMonitored() on that session. * * @param item The item to monitor. * @param monitored Whether to monitor the item. */ void setItemMonitored( const Item &item, bool monitored = true ); /** * Sets whether the specified resource shall be monitored for changes. If * monitoring is turned on for the resource, all notifications for * collections and items in that resource will be emitted. * * Note that if a session is being ignored, this takes precedence over * setResourceMonitored() on that session. * * @param resource The resource identifier. * @param monitored Whether to monitor the resource. */ void setResourceMonitored( const QByteArray &resource, bool monitored = true ); /** * Sets whether items of the specified mime type shall be monitored for changes. * If monitoring is turned on for the mime type, all notifications for items * matching that mime type will be emitted, but notifications for collections * matching that mime type will only be emitted if this is otherwise specified, * for example by setCollectionMonitored(). * * Note that if a session is being ignored, this takes precedence over * setMimeTypeMonitored() on that session. * * @param mimetype The mime type to monitor. * @param monitored Whether to monitor the mime type. */ void setMimeTypeMonitored( const QString &mimetype, bool monitored = true ); /** * Sets whether all items shall be monitored. * * Note that if a session is being ignored, this takes precedence over * setAllMonitored() on that session. */ void setAllMonitored( bool monitored = true ); /** * Ignores all change notifications caused by the given session. This * overrides all other settings on this session. * * @param session The session you want to ignore. */ void ignoreSession( Session *session ); /** * Enables automatic fetching of changed collections from the Akonadi storage. * * @param enable @c true enables automatic fetching, @c false disables automatic fetching. */ void fetchCollection( bool enable ); /** * Enables automatic fetching of changed collection statistics information from * the Akonadi storage. * * @param enable @c true to enables automatic fetching, @c false disables automatic fetching. */ void fetchCollectionStatistics( bool enable ); /** * Sets the item fetch scope. * * Controls how much of an item's data is fetched from the server, e.g. * whether to fetch the full item payload or only meta data. * * @param fetchScope The new scope for item fetch operations. * * @see itemFetchScope() */ void setItemFetchScope( const ItemFetchScope &fetchScope ); /** * Returns the item fetch scope. * * Since this returns a reference it can be used to conveniently modify the * current scope in-place, i.e. by calling a method on the returned reference * without storing it in a local variable. See the ItemFetchScope documentation * for an example. * * @return a reference to the current item fetch scope * * @see setItemFetchScope() for replacing the current item fetch scope */ ItemFetchScope &itemFetchScope(); /** * Sets the collection fetch scope. * * Controls which collections are monitored and how much of a collection's data * is fetched from the server. * * @param fetchScope The new scope for collection fetch operations. * * @see collectionFetchScope() * @since 4.4 */ void setCollectionFetchScope( const CollectionFetchScope &fetchScope ); /** * Returns the collection fetch scope. * * Since this returns a reference it can be used to conveniently modify the * current scope in-place, i.e. by calling a method on the returned reference * without storing it in a local variable. See the CollectionFetchScope documentation * for an example. * * @return a reference to the current collection fetch scope * * @see setCollectionFetchScope() for replacing the current collection fetch scope * @since 4.4 */ CollectionFetchScope &collectionFetchScope(); /** * Returns the list of collections being monitored. * * @since 4.3 */ Collection::List collectionsMonitored() const; /** * Returns the set of items being monitored. * * @since 4.3 */ QList itemsMonitored() const; /** * Returns the set of mimetypes being monitored. * * @since 4.3 */ QStringList mimeTypesMonitored() const; /** * Returns the set of identifiers for resources being monitored. * * @since 4.3 */ QList resourcesMonitored() const; /** * Returns true if everything is being monitored. * * @since 4.3 */ bool isAllMonitored() const; + /** + * Sets the session used by the Monitor to communicate with the %Akonadi server. + * If not set, the Akonadi::Session::defaultSession is used. + */ + void setSession(Akonadi::Session *session); + + /** + * Returns the Session used by the monitor to communicate with Akonadi. + */ + Session* session() const; + Q_SIGNALS: /** * This signal is emitted if a monitored item has changed, e.g. item parts have been modified. * * @param item The changed item. * @param partIdentifiers The identifiers of the item parts that has been changed. */ void itemChanged( const Akonadi::Item &item, const QSet &partIdentifiers ); /** * This signal is emitted if a monitored item has been moved between two collections * * @param item The moved item. * @param collectionSource The collection the item has been moved from. * @param collectionDestination The collection the item has been moved to. */ void itemMoved( const Akonadi::Item &item, const Akonadi::Collection &collectionSource, const Akonadi::Collection &collectionDestination ); /** * This signal is emitted if an item has been added to a monitored collection in the Akonadi storage. * * @param item The new item. * @param collection The collection the item has been added to. */ void itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ); /** * This signal is emitted if * - a monitored item has been removed from the Akonadi storage * or * - a item has been removed from a monitored collection. * * @param item The removed item. */ void itemRemoved( const Akonadi::Item &item ); /** * This signal is emitted if a reference to an item is added to a virtual collection. * @param item The linked item. * @param collection The collection the item is linked to. * * @since 4.2 */ void itemLinked( const Akonadi::Item &item, const Akonadi::Collection &collection ); /** * This signal is emitted if a reference to an item is removed from a virtual collection. * @param item The unlinked item. * @param collection The collection the item is unlinked from. * * @since 4.2 */ void itemUnlinked( const Akonadi::Item &item, const Akonadi::Collection &collection ); /** * This signal is emitted if a new collection has been added to a monitored collection in the Akonadi storage. * * @param collection The new collection. * @param parent The parent collection. */ void collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent ); /** * This signal is emitted if a monitored collection has been changed (properties or content). * * @param collection The changed collection. */ void collectionChanged( const Akonadi::Collection &collection ); /** * This signal is emitted if a monitored collection has been changed (properties or attributes). * * @param collection The changed collection. * @param attributeNames The names of the collection attributes that have been changed. * * @since 4.4 */ void collectionChanged( const Akonadi::Collection &collection, const QSet &attributeNames ); /** * This signals is emitted if a monitored collection has been moved. * * @param collection The moved collection. * @param source The previous parent collection. * @param distination The new parent collection. * * @since 4.4 */ void collectionMoved( const Akonadi::Collection &collection, const Akonadi::Collection &source, const Akonadi::Collection &destination ); /** * This signal is emitted if a monitored collection has been removed from the Akonadi storage. * * @param collection The removed collection. */ void collectionRemoved( const Akonadi::Collection &collection ); /** * This signal is emitted if the statistics information of a monitored collection * has changed. * * @param id The collection identifier of the changed collection. * @param statistics The updated collection statistics, invalid if automatic * fetching of statistics changes is disabled. */ void collectionStatisticsChanged( Akonadi::Collection::Id id, const Akonadi::CollectionStatistics &statistics ); /** * This signal is emitted if the Monitor starts or stops monitoring @p collection explicitly. * @param collection The collection * @param monitored Whether the collection is now being monitored or not. * * @since 4.3 */ void collectionMonitored( const Akonadi::Collection &collection, bool monitored ); /** * This signal is emitted if the Monitor starts or stops monitoring @p item explicitly. * @param item The item * @param monitored Whether the item is now being monitored or not. * * @since 4.3 */ void itemMonitored( const Akonadi::Item &item, bool monitored ); /** * This signal is emitted if the Monitor starts or stops monitoring the resource with the identifier @p identifier explicitly. * @param identifier The identifier of the resource. * @param monitored Whether the resource is now being monitored or not. * * @since 4.3 */ void resourceMonitored( const QByteArray &identifier, bool monitored ); /** * This signal is emitted if the Monitor starts or stops monitoring @p mimeType explicitly. * @param mimeType The mimeType. * @param monitored Whether the mimeType is now being monitored or not. * * @since 4.3 */ void mimeTypeMonitored( const QString &mimeType, bool monitored ); /** * This signal is emitted if the Monitor starts or stops monitoring everything. * @param monitored Whether everything is now being monitored or not. * * @since 4.3 */ void allMonitored( bool monitored ); protected: //@cond PRIVATE friend class EntityTreeModel; friend class EntityTreeModelPrivate; MonitorPrivate *d_ptr; explicit Monitor( MonitorPrivate *d, QObject *parent = 0 ); //@endcond private: Q_DECLARE_PRIVATE( Monitor ) //@cond PRIVATE Q_PRIVATE_SLOT( d_ptr, void slotSessionDestroyed( QObject* ) ) Q_PRIVATE_SLOT( d_ptr, void slotStatisticsChangedFinished( KJob* ) ) Q_PRIVATE_SLOT( d_ptr, void slotFlushRecentlyChangedCollections() ) Q_PRIVATE_SLOT( d_ptr, void slotNotify( const Akonadi::NotificationMessage::List& ) ) Q_PRIVATE_SLOT( d_ptr, void dataAvailable() ) friend class ResourceBasePrivate; //@endcond }; } #endif diff --git a/akonadi/monitor_p.cpp b/akonadi/monitor_p.cpp index 2d1c71c2d..5baf1e928 100644 --- a/akonadi/monitor_p.cpp +++ b/akonadi/monitor_p.cpp @@ -1,477 +1,478 @@ /* Copyright (c) 2007 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // @cond PRIVATE #include "monitor_p.h" #include "collectionfetchjob.h" #include "collectionstatistics.h" #include "itemfetchjob.h" #include "notificationmessage_p.h" #include "session.h" #include using namespace Akonadi; static const int PipelineSize = 5; MonitorPrivate::MonitorPrivate(Monitor * parent) : q_ptr( parent ), nm( 0 ), monitorAll( false ), - collectionCache( 3*PipelineSize ), // needs to be at least 3x pipeline size for the collection move case - itemCache( PipelineSize ), // needs to be at least 1x pipeline size + session( Session::defaultSession() ), + collectionCache( 3*PipelineSize, session ), // needs to be at least 3x pipeline size for the collection move case + itemCache( PipelineSize, session ), // needs to be at least 1x pipeline size fetchCollection( false ), fetchCollectionStatistics( false ), useRefCounting( false ) { } void MonitorPrivate::init() { QObject::connect( &collectionCache, SIGNAL(dataAvailable()), q_ptr, SLOT(dataAvailable()) ); QObject::connect( &itemCache, SIGNAL(dataAvailable()), q_ptr, SLOT(dataAvailable()) ); } bool MonitorPrivate::connectToNotificationManager() { NotificationMessage::registerDBusTypes(); if ( !nm ) nm = new org::freedesktop::Akonadi::NotificationManager( QLatin1String( "org.freedesktop.Akonadi" ), QLatin1String( "/notifications" ), QDBusConnection::sessionBus(), q_ptr ); else return true; if ( !nm ) { kWarning() << "Unable to connect to notification manager"; } else { QObject::connect( nm, SIGNAL(notify(Akonadi::NotificationMessage::List)), q_ptr, SLOT(slotNotify(Akonadi::NotificationMessage::List)) ); return true; } return false; } int MonitorPrivate::pipelineSize() const { return PipelineSize; } bool MonitorPrivate::isLazilyIgnored( const NotificationMessage & msg ) const { NotificationMessage::Operation op = msg.operation(); if ( ( msg.type() == NotificationMessage::Item ) && ( ( op == NotificationMessage::Add && q_ptr->receivers( SIGNAL(itemAdded(const Akonadi::Item &,const Akonadi::Collection &)) ) == 0 ) || ( op == NotificationMessage::Remove && q_ptr->receivers( SIGNAL(itemRemoved(const Akonadi::Item &)) ) == 0 ) || ( op == NotificationMessage::Modify && q_ptr->receivers( SIGNAL(itemChanged(const Akonadi::Item &,const QSet &)) ) == 0 ) || ( op == NotificationMessage::Move && q_ptr->receivers( SIGNAL(itemMoved(const Akonadi::Item &, const Akonadi::Collection &, const Akonadi::Collection &)) ) == 0 ) || ( op == NotificationMessage::Link && q_ptr->receivers( SIGNAL(itemLinked(const Akonadi::Item &,const Akonadi::Collection &)) ) == 0 ) || ( op == NotificationMessage::Unlink && q_ptr->receivers( SIGNAL(itemUnlinked(const Akonadi::Item &,const Akonadi::Collection &)) ) == 0 ) ) ) { return true; } if ( !useRefCounting ) return false; if ( msg.type() == NotificationMessage::Collection ) // Lazy fetching can only affects items. return false; Collection::Id parentCollectionId = msg.parentCollection(); if ( ( op == NotificationMessage::Add ) || ( op == NotificationMessage::Remove ) || ( op == NotificationMessage::Modify ) || ( op == NotificationMessage::Link ) || ( op == NotificationMessage::Unlink ) ) { if ( refCountMap.contains( parentCollectionId ) || m_buffer.isBuffered( parentCollectionId ) ) return false; } if ( op == NotificationMessage::Move ) { if ( !refCountMap.contains( parentCollectionId ) && !m_buffer.isBuffered( parentCollectionId ) ) if ( !refCountMap.contains( msg.parentDestCollection() ) && !m_buffer.isBuffered( msg.parentDestCollection() ) ) return true; // We can't ignore the move. It must be transformed later into a removal or insertion. return false; } return true; } bool MonitorPrivate::acceptNotification( const NotificationMessage & msg ) { if ( isSessionIgnored( msg.sessionId() ) ) return false; if ( isLazilyIgnored( msg ) ) return false; switch ( msg.type() ) { case NotificationMessage::InvalidType: kWarning() << "Received invalid change notification!"; return false; case NotificationMessage::Item: return isItemMonitored( msg.uid(), msg.parentCollection(), msg.parentDestCollection(), msg.mimeType(), msg.resource() ) || isCollectionMonitored( msg.parentCollection(), msg.resource() ) || isCollectionMonitored( msg.parentDestCollection(), msg.resource() ); case NotificationMessage::Collection: return isCollectionMonitored( msg.uid(), msg.resource() ) || isCollectionMonitored( msg.parentCollection(), msg.resource() ) || isCollectionMonitored( msg.parentDestCollection(), msg.resource() ); } Q_ASSERT( false ); return false; } void MonitorPrivate::dispatchNotifications() { while ( pipeline.size() < pipelineSize() && !pendingNotifications.isEmpty() ) { const NotificationMessage msg = pendingNotifications.dequeue(); if ( ensureDataAvailable( msg ) && pipeline.isEmpty() ) emitNotification( msg ); else pipeline.enqueue( msg ); } } bool MonitorPrivate::ensureDataAvailable( const NotificationMessage &msg ) { bool allCached = true; if ( fetchCollection ) { if ( !collectionCache.ensureCached( msg.parentCollection(), mCollectionFetchScope ) ) allCached = false; if ( msg.operation() == NotificationMessage::Move && !collectionCache.ensureCached( msg.parentDestCollection(), mCollectionFetchScope ) ) allCached = false; } if ( msg.operation() == NotificationMessage::Remove ) return allCached; // the actual object is gone already, nothing to fetch there if ( msg.type() == NotificationMessage::Item && !mItemFetchScope.isEmpty() ) { if ( !itemCache.ensureCached( msg.uid(), mItemFetchScope ) ) allCached = false; } else if ( msg.type() == NotificationMessage::Collection && fetchCollection ) { if ( !collectionCache.ensureCached( msg.uid(), mCollectionFetchScope ) ) allCached = false; } return allCached; } void MonitorPrivate::emitNotification( const NotificationMessage &msg ) { const Collection parent = collectionCache.retrieve( msg.parentCollection() ); Collection destParent; if ( msg.operation() == NotificationMessage::Move ) destParent = collectionCache.retrieve( msg.parentDestCollection() ); if ( msg.type() == NotificationMessage::Collection ) { const Collection col = collectionCache.retrieve( msg.uid() ); emitCollectionNotification( msg, col, parent, destParent ); } else if ( msg.type() == NotificationMessage::Item ) { const Item item = itemCache.retrieve( msg.uid() ); emitItemNotification( msg, item, parent, destParent ); } } void MonitorPrivate::dataAvailable() { while ( !pipeline.isEmpty() ) { const NotificationMessage msg = pipeline.head(); if ( ensureDataAvailable( msg ) ) { emitNotification( msg ); pipeline.dequeue(); } else { break; } } dispatchNotifications(); } void MonitorPrivate::updatePendingStatistics( const NotificationMessage &msg ) { if ( msg.type() == NotificationMessage::Item ) { notifyCollectionStatisticsWatchers( msg.parentCollection(), msg.resource() ); } else if ( msg.type() == NotificationMessage::Collection && msg.operation() == NotificationMessage::Remove ) { // no need for statistics updates anymore recentlyChangedCollections.remove( msg.uid() ); } } void MonitorPrivate::slotSessionDestroyed( QObject * object ) { Session* session = qobject_cast( object ); if ( session ) sessions.removeAll( session->sessionId() ); } void MonitorPrivate::slotStatisticsChangedFinished( KJob* job ) { if ( job->error() ) { kWarning() << "Error on fetching collection statistics: " << job->errorText(); } else { CollectionStatisticsJob *statisticsJob = static_cast( job ); emit q_ptr->collectionStatisticsChanged( statisticsJob->collection().id(), statisticsJob->statistics() ); } } void MonitorPrivate::slotFlushRecentlyChangedCollections() { foreach( Collection::Id collection, recentlyChangedCollections ) { if ( fetchCollectionStatistics ) { fetchStatistics( collection ); } else { static const CollectionStatistics dummyStatistics; emit q_ptr->collectionStatisticsChanged( collection, dummyStatistics ); } } recentlyChangedCollections.clear(); } void MonitorPrivate::appendAndCompress( const NotificationMessage &msg ) { if ( !useRefCounting || msg.operation() != NotificationMessage::Move || msg.type() != NotificationMessage::Item ) return NotificationMessage::appendAndCompress( pendingNotifications, msg ); bool sourceWatched = refCountMap.contains( msg.parentCollection() ) || m_buffer.isBuffered( msg.parentCollection() ); bool destWatched = refCountMap.contains( msg.parentDestCollection() ) || m_buffer.isBuffered( msg.parentDestCollection() ); if ( sourceWatched && destWatched ) return NotificationMessage::appendAndCompress( pendingNotifications, msg ); if ( sourceWatched ) { // Transform into a removal NotificationMessage removalMessage = msg; removalMessage.setOperation( NotificationMessage::Remove ); removalMessage.setParentDestCollection( -1 ); return NotificationMessage::appendAndCompress( pendingNotifications, removalMessage ); } // Transform into an insertion NotificationMessage insertionMessage = msg; insertionMessage.setOperation( NotificationMessage::Add ); insertionMessage.setParentCollection( msg.parentDestCollection() ); insertionMessage.setParentDestCollection( -1 ); NotificationMessage::appendAndCompress( pendingNotifications, insertionMessage ); } void MonitorPrivate::slotNotify( const NotificationMessage::List &msgs ) { foreach ( const NotificationMessage &msg, msgs ) { invalidateCaches( msg ); if ( acceptNotification( msg ) ) { updatePendingStatistics( msg ); appendAndCompress( msg ); } } dispatchNotifications(); } void MonitorPrivate::emitItemNotification( const NotificationMessage &msg, const Item &item, const Collection &collection, const Collection &collectionDest ) { Q_ASSERT( msg.type() == NotificationMessage::Item ); Collection col = collection; Collection colDest = collectionDest; if ( !col.isValid() ) { col = Collection( msg.parentCollection() ); col.setResource( QString::fromUtf8( msg.resource() ) ); } if ( !colDest.isValid() ) { colDest = Collection( msg.parentDestCollection() ); // FIXME setResource here required ? } Item it = item; if ( !it.isValid() || msg.operation() == NotificationMessage::Remove ) { it = Item( msg.uid() ); it.setRemoteId( msg.remoteId() ); it.setMimeType( msg.mimeType() ); } if ( !it.parentCollection().isValid() ) { if ( msg.operation() == NotificationMessage::Move ) it.setParentCollection( colDest ); else it.setParentCollection( col ); } switch ( msg.operation() ) { case NotificationMessage::Add: emit q_ptr->itemAdded( it, col ); break; case NotificationMessage::Modify: emit q_ptr->itemChanged( it, msg.itemParts() ); break; case NotificationMessage::Move: emit q_ptr->itemMoved( it, col, colDest ); break; case NotificationMessage::Remove: emit q_ptr->itemRemoved( it ); break; case NotificationMessage::Link: emit q_ptr->itemLinked( it, col ); break; case NotificationMessage::Unlink: emit q_ptr->itemUnlinked( it, col ); break; default: kDebug() << "Unknown operation type" << msg.operation() << "in item change notification"; break; } } void MonitorPrivate::emitCollectionNotification( const NotificationMessage &msg, const Collection &col, const Collection &par, const Collection &dest ) { Q_ASSERT( msg.type() == NotificationMessage::Collection ); Collection collection = col; if ( !collection.isValid() || msg.operation() == NotificationMessage::Remove ) { collection = Collection( msg.uid() ); collection.setResource( QString::fromUtf8( msg.resource() ) ); collection.setRemoteId( msg.remoteId() ); } Collection parent = par; if ( !parent.isValid() ) parent = Collection( msg.parentCollection() ); Collection destination = dest; if ( !destination.isValid() ) destination = Collection( msg.parentDestCollection() ); if ( !collection.parentCollection().isValid() ) { if ( msg.operation() == NotificationMessage::Move ) collection.setParentCollection( destination ); else collection.setParentCollection( parent ); } switch ( msg.operation() ) { case NotificationMessage::Add: emit q_ptr->collectionAdded( collection, parent ); break; case NotificationMessage::Modify: emit q_ptr->collectionChanged( collection ); emit q_ptr->collectionChanged( collection, msg.itemParts() ); break; case NotificationMessage::Move: emit q_ptr->collectionMoved( collection, parent, destination ); break; case NotificationMessage::Remove: emit q_ptr->collectionRemoved( collection ); break; default: kDebug() << "Unknown operation type" << msg.operation() << "in collection change notification"; } } void MonitorPrivate::invalidateCaches( const NotificationMessage &msg ) { // remove invalidates if ( msg.operation() == NotificationMessage::Remove ) { if ( msg.type() == NotificationMessage::Collection ) { collectionCache.invalidate( msg.uid() ); } else if ( msg.type() == NotificationMessage::Item ) { itemCache.invalidate( msg.uid() ); } } // modify removes the cache entry, as we need to re-fetch if ( msg.operation() == NotificationMessage::Modify || msg.operation() == NotificationMessage::Move ) { if ( msg.type() == NotificationMessage::Collection ) { collectionCache.update( msg.uid(), mCollectionFetchScope ); } else if ( msg.type() == NotificationMessage::Item ) { itemCache.update( msg.uid(), mItemFetchScope ); } } } void MonitorPrivate::invalidateCache( const Collection &col ) { collectionCache.update( col.id(), mCollectionFetchScope ); } void MonitorPrivate::ref( Collection::Id id ) { if ( !refCountMap.contains( id ) ) { refCountMap.insert( id, 0 ); } ++refCountMap[ id ]; if ( m_buffer.isBuffered( id ) ) m_buffer.purge( id ); } Collection::Id MonitorPrivate::deref( Collection::Id id ) { Q_ASSERT( refCountMap.contains( id ) ); if ( --refCountMap[ id ] == 0 ) { refCountMap.remove( id ); } return m_buffer.buffer( id ); } void MonitorPrivate::PurgeBuffer::purge( Collection::Id id ) { int idx = m_buffer.indexOf( id, 0 ); while ( idx <= m_index ) { if ( idx < 0 ) break; m_buffer.removeAt( idx ); if ( m_index > 0 ) --m_index; idx = m_buffer.indexOf( id, idx ); } while ( int idx = m_buffer.indexOf( id, m_index ) > -1 ) { m_buffer.removeAt( idx ); } } Collection::Id MonitorPrivate::PurgeBuffer::buffer( Collection::Id id ) { if ( m_index == MAXBUFFERSIZE ) { m_index = 0; } Collection::Id bumpedId = -1; if ( m_buffer.size() == MAXBUFFERSIZE ) { bumpedId = m_buffer.takeAt( m_index ); } // Ensure that we don't put a duplicate @p id into the buffer. purge( id ); m_buffer.insert( m_index, id ); ++m_index; return bumpedId; } // @endcond diff --git a/akonadi/monitor_p.h b/akonadi/monitor_p.h index ffca55654..5db1158ab 100644 --- a/akonadi/monitor_p.h +++ b/akonadi/monitor_p.h @@ -1,229 +1,230 @@ /* Copyright (c) 2007 Tobias Koenig This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_MONITOR_P_H #define AKONADI_MONITOR_P_H #include "monitor.h" #include "collection.h" #include "collectionstatisticsjob.h" #include "collectionfetchscope.h" #include "item.h" #include "itemfetchscope.h" #include "job.h" #include #include "notificationmanagerinterface.h" #include "entitycache_p.h" #include #include #include namespace Akonadi { class Monitor; /** * @internal */ class MonitorPrivate { public: MonitorPrivate( Monitor *parent ); virtual ~MonitorPrivate() {} void init(); Monitor *q_ptr; Q_DECLARE_PUBLIC( Monitor ) org::freedesktop::Akonadi::NotificationManager *nm; Collection::List collections; QSet resources; QSet items; QSet mimetypes; bool monitorAll; QList sessions; ItemFetchScope mItemFetchScope; CollectionFetchScope mCollectionFetchScope; + Session *session; CollectionCache collectionCache; ItemCache itemCache; QQueue pendingNotifications; QQueue pipeline; bool fetchCollection; bool fetchCollectionStatistics; bool isCollectionMonitored( Collection::Id collection, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || resources.contains( resource ) ) return true; return false; } bool isItemMonitored( Item::Id item, Collection::Id collection, Collection::Id collectionDest, const QString &mimetype, const QByteArray &resource ) const { if ( monitorAll || isCollectionMonitored( collection ) || isCollectionMonitored( collectionDest ) ||items.contains( item ) || resources.contains( resource ) || isMimeTypeMonitored( mimetype ) ) return true; return false; } bool isSessionIgnored( const QByteArray &sessionId ) const { return sessions.contains( sessionId ); } bool connectToNotificationManager(); bool acceptNotification( const NotificationMessage &msg ); void dispatchNotifications(); bool ensureDataAvailable( const NotificationMessage &msg ); void emitNotification( const NotificationMessage &msg ); void updatePendingStatistics( const NotificationMessage &msg ); void invalidateCaches( const NotificationMessage &msg ); /** Used by ResourceBase to inform us about collection changes before the notifications are emitted, needed to avoid the missing RID race on change replay. */ void invalidateCache( const Collection &col ); virtual int pipelineSize() const; // private slots void dataAvailable(); void slotSessionDestroyed( QObject* ); void slotStatisticsChangedFinished( KJob* ); void slotFlushRecentlyChangedCollections(); void appendAndCompress( const NotificationMessage &msg ); virtual void slotNotify( const NotificationMessage::List &msgs ); void emitItemNotification( const NotificationMessage &msg, const Item &item = Item(), const Collection &collection = Collection(), const Collection &collectionDest = Collection() ); void emitCollectionNotification( const NotificationMessage &msg, const Collection &col = Collection(), const Collection &par = Collection(), const Collection &dest = Collection() ); /** @brief Class used to determine when to purge items in a Collection The buffer method can be used to buffer a Collection. This may cause another Collection to be purged if it is removed from the buffer. The purge method is used to purge a Collection from the buffer, but not the model. This is used for example, to not buffer Collections anymore if they get referenced, and to ensure that one Collection does not appear twice in the buffer. Check whether a Collection is buffered using the isBuffered method. */ class PurgeBuffer { // Buffer the most recent 10 unreferenced Collections static const int MAXBUFFERSIZE = 10; public: explicit PurgeBuffer() : m_index( 0 ), m_bufferSize( MAXBUFFERSIZE ) { } /** Adds @p id to the Collections to be buffered @returns The collection id which was removed form the buffer or -1 if none. */ Collection::Id buffer( Collection::Id id ); /** Removes @p id from the Collections being buffered */ void purge( Collection::Id id ); bool isBuffered( Collection::Id id ) const { return m_buffer.contains( id ); } private: QList m_buffer; int m_index; int m_bufferSize; } m_buffer; QHash refCountMap; bool useRefCounting; void ref( Collection::Id id ); Collection::Id deref( Collection::Id id ); private: // collections that need a statistics update QSet recentlyChangedCollections; /** @returns True if @p msg should be ignored. Otherwise appropriate signals are emitted for it. */ bool isLazilyIgnored( const NotificationMessage & msg ) const; bool isCollectionMonitored( Collection::Id collection ) const { if ( collections.contains( Collection( collection ) ) ) return true; if ( collections.contains( Collection::root() ) ) return true; return false; } bool isMimeTypeMonitored( const QString& mimetype ) const { if ( mimetypes.contains( mimetype ) ) return true; KMimeType::Ptr mimeType = KMimeType::mimeType( mimetype, KMimeType::ResolveAliases ); if ( mimeType.isNull() ) return false; foreach ( const QString &mt, mimetypes ) { if ( mimeType->is( mt ) ) return true; } return false; } void fetchStatistics( Collection::Id colId ) { - CollectionStatisticsJob *job = new CollectionStatisticsJob( Collection( colId ), q_ptr ); + CollectionStatisticsJob *job = new CollectionStatisticsJob( Collection( colId ), session ); QObject::connect( job, SIGNAL(result(KJob*)), q_ptr, SLOT(slotStatisticsChangedFinished(KJob*)) ); } void notifyCollectionStatisticsWatchers( Collection::Id collection, const QByteArray &resource ) { if ( isCollectionMonitored( collection, resource ) ) { if (recentlyChangedCollections.empty() ) QTimer::singleShot( 500, q_ptr, SLOT(slotFlushRecentlyChangedCollections()) ); recentlyChangedCollections.insert( collection ); } } }; } #endif diff --git a/akonadi/tests/entitytreemodeltest.cpp b/akonadi/tests/entitytreemodeltest.cpp index 3211f1261..292e66c6c 100644 --- a/akonadi/tests/entitytreemodeltest.cpp +++ b/akonadi/tests/entitytreemodeltest.cpp @@ -1,396 +1,397 @@ /* Copyright (c) 2009 Stephen Kelly This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include "fakeserver.h" #include "fakesession.h" #include "fakemonitor.h" #include "akonadieventqueue.h" #include "modelspy.h" #include "imapparser_p.h" #include "entitytreemodel.h" #include #include #include class PublicETMPrivate; class PublicETM : public EntityTreeModel { Q_OBJECT Q_DECLARE_PRIVATE(PublicETM) public: - PublicETM( Session *session, ChangeRecorder *monitor, QObject *parent ); + PublicETM( ChangeRecorder *monitor, QObject *parent ); EntityTreeModelPrivate *privateClass() const { return d_ptr; } }; class PublicETMPrivate : public EntityTreeModelPrivate { Q_DECLARE_PUBLIC(PublicETM) public: PublicETMPrivate( PublicETM *p ); }; -PublicETM::PublicETM( Session *session, ChangeRecorder *monitor, QObject *parent ) - : EntityTreeModel( session, monitor, new PublicETMPrivate( this ), parent ) +PublicETM::PublicETM( ChangeRecorder *monitor, QObject *parent ) + : EntityTreeModel( monitor, new PublicETMPrivate( this ), parent ) { } -PublicETMPrivate::PublicETMPrivate(PublicETM *p) +PublicETMPrivate::PublicETMPrivate( PublicETM *p ) : EntityTreeModelPrivate( p ) { } class EntityTreeModelTest : public QObject { Q_OBJECT protected: Collection getCollection(const Collection parent, const QString &name, const QByteArray displayName = QByteArray(), const QByteArray displayDecoration = QByteArray(), const QByteArray resourceName = "testresource1", const QStringList &mimetypeList = QStringList() << "inode/directory" << "application/x-vnd.akonadi-testitem" ) { Collection col; col.setName( name ); col.setId( getCollectionId() ); col.setRemoteId( name + "RemoteId" ); col.setContentMimeTypes( mimetypeList ); col.setParentCollection( parent ); col.setResource( resourceName ); EntityDisplayAttribute *eda = col.attribute( Entity::AddIfMissing ); if (!displayName.isEmpty()) eda->setDisplayName( displayName ); else eda->setDisplayName( name ); if ( !displayDecoration.isEmpty() ) eda->setIconName( displayDecoration ); else eda->setIconName( "x-akonadi-test-icon" ); return col; } Entity::Id getCollectionId() { return m_collectionId++; } private slots: void initTestCase(); void init(); void testCollectionFetch(); void testCollectionAdded(); void testCollectionMoved(); private: PublicETM *m_model; ModelSpy *m_modelSpy; FakeSession *m_fakeSession; FakeMonitor *m_fakeMonitor; QByteArray m_sessionName; Entity::Id m_collectionId; }; void EntityTreeModelTest::initTestCase() { m_collectionId = 1; m_sessionName = "EntityTreeModelTest fake session"; m_fakeSession = new FakeSession( m_sessionName, this); qRegisterMetaType("QModelIndex"); } void EntityTreeModelTest::init() { FakeMonitor *fakeMonitor = new FakeMonitor(this); + fakeMonitor->setSession( m_fakeSession ); fakeMonitor->setCollectionMonitored(Collection::root()); - m_model = new PublicETM( m_fakeSession, fakeMonitor, this ); + m_model = new PublicETM( fakeMonitor, this ); m_model->setItemPopulationStrategy( EntityTreeModel::NoItemPopulation ); m_modelSpy = new ModelSpy(this); m_modelSpy->setModel(m_model); m_modelSpy->startSpying(); } void EntityTreeModelTest::testCollectionFetch() { Collection::List collectionList; collectionList << getCollection(Collection::root(), "Col0"); collectionList << getCollection(Collection::root(), "Col1"); collectionList << getCollection(Collection::root(), "Col2"); collectionList << getCollection(Collection::root(), "Col3"); // Give the collection 'col0' four child collections. Collection col0 = collectionList.at( 0 ); collectionList << getCollection(col0, "Col4"); collectionList << getCollection(col0, "Col5"); collectionList << getCollection(col0, "Col6"); collectionList << getCollection(col0, "Col7"); Collection col5 = collectionList.at( 5 ); collectionList << getCollection(col5, "Col8"); collectionList << getCollection(col5, "Col9"); collectionList << getCollection(col5, "Col10"); collectionList << getCollection(col5, "Col11"); Collection col6 = collectionList.at( 6 ); collectionList << getCollection(col6, "Col12"); collectionList << getCollection(col6, "Col13"); collectionList << getCollection(col6, "Col14"); collectionList << getCollection(col6, "Col15"); Collection::List collectionListReversed; foreach(const Collection &c, collectionList) collectionListReversed.prepend(c); // The first list job is started with a single shot. // Give it time to set the root collection. QTest::qWait(1); m_model->privateClass()->collectionsFetched(collectionListReversed); QVERIFY( m_modelSpy->size() == 8 ); for (int i = 0; i < m_modelSpy->size(); ++i) { QVERIFY( m_modelSpy->at( i ).at( 0 ) == ( i % 2 == 0 ? RowsAboutToBeInserted : RowsInserted ) ); } QVERIFY( m_model->rowCount() == 4 ); QSet expectedRowData; QSet rowData; expectedRowData << "Col0" << "Col1" << "Col2" << "Col3"; for ( int row = 0; row < m_model->rowCount(); ++row ) { rowData.insert(m_model->index(row, 0).data().toString()); } QCOMPARE(rowData, expectedRowData); rowData.clear(); expectedRowData.clear(); // Col0 is at row index 3 by the end QModelIndex col0Index = m_model->match(m_model->index(0, 0), Qt::DisplayRole, "Col0", 1).first(); expectedRowData << "Col4" << "Col5" << "Col6" << "Col7"; QVERIFY( m_model->rowCount( col0Index ) == 4 ); for ( int row = 0; row < m_model->rowCount(col0Index); ++row ) { rowData.insert(m_model->index(row, 0, col0Index).data().toString()); } QCOMPARE(rowData, expectedRowData); rowData.clear(); expectedRowData.clear(); QModelIndex col5Index = m_model->match(m_model->index(0, 0, col0Index), Qt::DisplayRole, "Col5", 1).first(); expectedRowData << "Col8" << "Col9" << "Col10" << "Col11"; QVERIFY( m_model->rowCount( col5Index ) == 4 ); for ( int row = 0; row < m_model->rowCount(col5Index); ++row ) { rowData.insert(m_model->index(row, 0, col5Index).data().toString()); } QCOMPARE(rowData, expectedRowData); rowData.clear(); expectedRowData.clear(); QModelIndex col6Index = m_model->match(m_model->index(0, 0, col0Index), Qt::DisplayRole, "Col6", 1).first(); expectedRowData << "Col12" << "Col13" << "Col14" << "Col15"; QVERIFY( m_model->rowCount( col6Index ) == 4 ); for ( int row = 0; row < m_model->rowCount(col6Index); ++row ) { rowData.insert(m_model->index(row, 0, col6Index).data().toString()); } QCOMPARE(rowData, expectedRowData); rowData.clear(); expectedRowData.clear(); } void EntityTreeModelTest::testCollectionAdded() { Collection::List collectionList; collectionList << getCollection(Collection::root(), "Col0"); collectionList << getCollection(Collection::root(), "Col1"); collectionList << getCollection(Collection::root(), "Col2"); collectionList << getCollection(Collection::root(), "Col3"); // Give the collection 'col0' four child collections. Collection col0 = collectionList.at( 0 ); collectionList << getCollection(col0, "Col4"); collectionList << getCollection(col0, "Col5"); collectionList << getCollection(col0, "Col6"); collectionList << getCollection(col0, "Col7"); Collection col5 = collectionList.at( 5 ); collectionList << getCollection(col5, "Col8"); collectionList << getCollection(col5, "Col9"); collectionList << getCollection(col5, "Col10"); collectionList << getCollection(col5, "Col11"); Collection col6 = collectionList.at( 6 ); collectionList << getCollection(col6, "Col12"); collectionList << getCollection(col6, "Col13"); collectionList << getCollection(col6, "Col14"); collectionList << getCollection(col6, "Col15"); Collection::List collectionListReversed; foreach(const Collection &c, collectionList) collectionListReversed.prepend(c); // The first list job is started with a single shot. // Give it time to set the root collection. QTest::qWait(1); m_modelSpy->stopSpying(); m_model->privateClass()->collectionsFetched(collectionListReversed); m_modelSpy->startSpying(); Collection newCol1 = getCollection(Collection::root(), "NewCollection"); m_model->privateClass()->monitoredCollectionAdded(newCol1, Collection::root()); QVERIFY(m_modelSpy->size() == 2); for (int i = 0; i < m_modelSpy->size(); ++i) { QVERIFY( m_modelSpy->at( i ).at( 0 ) == ( i % 2 == 0 ? RowsAboutToBeInserted : RowsInserted ) ); } int start = m_modelSpy->at( 1 ).at( 2 ).toInt(); int end = m_modelSpy->at( 1 ).at( 3 ).toInt(); QCOMPARE(m_model->rowCount(), 5); QCOMPARE(start, end); QCOMPARE(m_model->index(start, 0).data().toString(), QLatin1String("NewCollection")); } void EntityTreeModelTest::testCollectionMoved() { Collection::List collectionList; collectionList << getCollection(Collection::root(), "Col0"); collectionList << getCollection(Collection::root(), "Col1"); collectionList << getCollection(Collection::root(), "Col2"); collectionList << getCollection(Collection::root(), "Col3"); // Give the collection 'col0' four child collections. Collection col0 = collectionList.at( 0 ); collectionList << getCollection(col0, "Col4"); collectionList << getCollection(col0, "Col5"); collectionList << getCollection(col0, "Col6"); collectionList << getCollection(col0, "Col7"); Collection col5 = collectionList.at( 5 ); collectionList << getCollection(col5, "Col8"); collectionList << getCollection(col5, "Col9"); collectionList << getCollection(col5, "Col10"); collectionList << getCollection(col5, "Col11"); Collection col6 = collectionList.at( 6 ); collectionList << getCollection(col6, "Col12"); Collection col13 = getCollection(col6, "Col13"); collectionList << col13; collectionList << getCollection(col6, "Col14"); collectionList << getCollection(col6, "Col15"); Collection::List collectionListReversed; foreach(const Collection &c, collectionList) collectionListReversed.prepend(c); // The first list job is started with a single shot. // Give it time to set the root collection. QTest::qWait(1); m_modelSpy->stopSpying(); m_model->privateClass()->collectionsFetched(collectionListReversed); m_modelSpy->startSpying(); // Move col13 to col5 col13.setParentCollection( col5 ); m_model->privateClass()->monitoredCollectionMoved(col13, col6, col5); QVERIFY(m_modelSpy->size() == 2); for (int i = 0; i < m_modelSpy->size(); ++i) { QVERIFY( m_modelSpy->at( i ).at( 0 ) == ( i % 2 == 0 ? RowsAboutToBeMoved : RowsMoved ) ); } int start = m_modelSpy->at( 1 ).at( 2 ).toInt(); int end = m_modelSpy->at( 1 ).at( 3 ).toInt(); int dest = m_modelSpy->at( 1 ).at( 5 ).toInt(); QModelIndex src = qvariant_cast( m_modelSpy->at( 1 ).at( 1 ) ); QModelIndex destIdx = qvariant_cast( m_modelSpy->at( 1 ).at( 4 ) ); QCOMPARE(start, end); QCOMPARE(src.data().toString(), QLatin1String("Col6")); QCOMPARE(destIdx.data().toString(), QLatin1String("Col5")); QCOMPARE(m_model->index(dest, 0, destIdx).data().toString(), QLatin1String("Col13")); } #include "entitytreemodeltest.moc" QTEST_KDEMAIN(EntityTreeModelTest, NoGUI)