QGIS API Documentation  2.12.0-Lyon
qgsbrowsermodel.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsbrowsermodel.cpp
3  ---------------------
4  begin : July 2011
5  copyright : (C) 2011 by Martin Dobias
6  email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 #include <QDir>
16 #include <QApplication>
17 #include <QStyle>
18 #include <QtConcurrentMap>
19 
20 #include "qgis.h"
21 #include "qgsapplication.h"
22 #include "qgsdataitemprovider.h"
24 #include "qgsdataprovider.h"
25 #include "qgsmimedatautils.h"
26 #include "qgslogger.h"
27 #include "qgsproviderregistry.h"
28 
29 #include "qgsbrowsermodel.h"
30 #include "qgsproject.h"
31 
32 #include <QSettings>
33 
35  : mItem( item )
36 {
37 }
38 
40 {
41 }
42 
43 // sort function for QList<QgsDataItem*>, e.g. sorted/grouped provider listings
45 {
46  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
47 }
48 
50  : QAbstractItemModel( parent )
51  , mFavourites( 0 )
52  , mProjectHome( 0 )
53 {
54  connect( QgsProject::instance(), SIGNAL( readProject( const QDomDocument & ) ), this, SLOT( updateProjectHome() ) );
55  connect( QgsProject::instance(), SIGNAL( writeProject( QDomDocument & ) ), this, SLOT( updateProjectHome() ) );
56  addRootItems();
57 }
58 
60 {
62 }
63 
65 {
67  if ( mProjectHome && mProjectHome->path() == home )
68  return;
69 
70  int idx = mRootItems.indexOf( mProjectHome );
71 
72  // using layoutAboutToBeChanged() was messing expanded items
73  if ( idx >= 0 )
74  {
75  beginRemoveRows( QModelIndex(), idx, idx );
76  mRootItems.remove( idx );
77  endRemoveRows();
78  }
79  delete mProjectHome;
80  mProjectHome = home.isNull() ? 0 : new QgsDirectoryItem( NULL, tr( "Project home" ), home, "project:" + home );
81  if ( mProjectHome )
82  {
84 
85  beginInsertRows( QModelIndex(), 0, 0 );
87  endInsertRows();
88  }
89 }
90 
92 {
94 
95  // give the home directory a prominent second place
96  QgsDirectoryItem *item = new QgsDirectoryItem( NULL, tr( "Home" ), QDir::homePath(), "home:" + QDir::homePath() );
97  QStyle *style = QApplication::style();
98  QIcon homeIcon( style->standardPixmap( QStyle::SP_DirHomeIcon ) );
99  item->setIcon( homeIcon );
100  connectItem( item );
101  mRootItems << item;
102 
103  // add favourite directories
104  mFavourites = new QgsFavouritesItem( NULL, tr( "Favourites" ) );
105  if ( mFavourites )
106  {
109  }
110 
111  // add drives
112  Q_FOREACH ( const QFileInfo& drive, QDir::drives() )
113  {
114  QString path = drive.absolutePath();
115  QgsDirectoryItem *item = new QgsDirectoryItem( NULL, path, path );
116 
117  connectItem( item );
118  mRootItems << item;
119  }
120 
121 #ifdef Q_OS_MAC
122  QString path = QString( "/Volumes" );
123  QgsDirectoryItem *vols = new QgsDirectoryItem( NULL, path, path );
124  connectItem( vols );
125  mRootItems << vols;
126 #endif
127 
128  // container for displaying providers as sorted groups (by QgsDataProvider::DataCapability enum)
129  QMap<int, QgsDataItem *> providerMap;
130 
131  Q_FOREACH ( QgsDataItemProvider* pr, QgsDataItemProviderRegistry::instance()->providers() )
132  {
133  int capabilities = pr->capabilities();
134  if ( capabilities == QgsDataProvider::NoDataCapabilities )
135  {
136  QgsDebugMsg( pr->name() + " does not have any dataCapabilities" );
137  continue;
138  }
139 
140  QgsDataItem *item = pr->createDataItem( "", NULL ); // empty path -> top level
141  if ( item )
142  {
143  QgsDebugMsg( "Add new top level item : " + item->name() );
144  connectItem( item );
145  providerMap.insertMulti( capabilities, item );
146  }
147  }
148 
149  // add as sorted groups by QgsDataProvider::DataCapability enum
150  Q_FOREACH ( int key, providerMap.uniqueKeys() )
151  {
152  QList<QgsDataItem *> providerGroup = providerMap.values( key );
153  if ( providerGroup.size() > 1 )
154  {
155  qSort( providerGroup.begin(), providerGroup.end(), cmpByDataItemName_ );
156  }
157 
158  Q_FOREACH ( QgsDataItem * ditem, providerGroup )
159  {
160  mRootItems << ditem;
161  }
162  }
163 }
164 
166 {
167  Q_FOREACH ( QgsDataItem* item, mRootItems )
168  {
169  delete item;
170  }
171 
172  mRootItems.clear();
173 }
174 
175 
177 {
178  if ( !index.isValid() )
179  return 0;
180 
181  Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
182 
183  QgsDataItem* ptr = ( QgsDataItem* ) index.internalPointer();
184  if ( ptr->type() == QgsDataItem::Layer )
185  {
186  flags |= Qt::ItemIsDragEnabled;
187  }
188  if ( ptr->acceptDrop() )
189  flags |= Qt::ItemIsDropEnabled;
190  return flags;
191 }
192 
194 {
195  if ( !index.isValid() )
196  return QVariant();
197 
198  QgsDataItem *item = dataItem( index );
199  if ( !item )
200  {
201  return QVariant();
202  }
203  else if ( role == Qt::DisplayRole )
204  {
205  if ( index.column() == 0 )
206  {
207  return item->name();
208  }
209  if ( item->type() == QgsDataItem::Layer )
210  {
211  QgsLayerItem* lyrItem = qobject_cast<QgsLayerItem*>( item );
212  return lyrItem->comments();
213  }
214  return "";
215  }
216  else if ( role == Qt::ToolTipRole )
217  {
218  return item->toolTip();
219  }
220  else if ( role == Qt::DecorationRole && index.column() == 0 )
221  {
222  return item->icon();
223  }
224  else if ( role == QgsBrowserModel::PathRole )
225  {
226  return item->path();
227  }
228  else
229  {
230  // unsupported role
231  return QVariant();
232  }
233 }
234 
235 QVariant QgsBrowserModel::headerData( int section, Qt::Orientation orientation, int role ) const
236 {
237  Q_UNUSED( section );
238  if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )
239  {
240  return QVariant( "header" );
241  }
242 
243  return QVariant();
244 }
245 
246 int QgsBrowserModel::rowCount( const QModelIndex &parent ) const
247 {
248  //QgsDebugMsg(QString("isValid = %1 row = %2 column = %3").arg(parent.isValid()).arg(parent.row()).arg(parent.column()));
249 
250  if ( !parent.isValid() )
251  {
252  // root item: its children are top level items
253  return mRootItems.count(); // mRoot
254  }
255  else
256  {
257  // ordinary item: number of its children
258  QgsDataItem *item = dataItem( parent );
259  //if ( item ) QgsDebugMsg(QString("path = %1 rowCount = %2").arg(item->path()).arg(item->rowCount()) );
260  return item ? item->rowCount() : 0;
261  }
262 }
263 
264 bool QgsBrowserModel::hasChildren( const QModelIndex &parent ) const
265 {
266  if ( !parent.isValid() )
267  return true; // root item: its children are top level items
268 
269  QgsDataItem *item = dataItem( parent );
270  return item && item->hasChildren();
271 }
272 
273 int QgsBrowserModel::columnCount( const QModelIndex &parent ) const
274 {
275  Q_UNUSED( parent );
276  return 1;
277 }
278 
279 QModelIndex QgsBrowserModel::findPath( const QString& path, Qt::MatchFlag matchFlag )
280 {
281  return findPath( this, path, matchFlag );
282 }
283 
284 QModelIndex QgsBrowserModel::findPath( QAbstractItemModel *model, const QString& path, Qt::MatchFlag matchFlag )
285 {
286  if ( !model )
287  return QModelIndex();
288 
289  QModelIndex theIndex; // starting from root
290  bool foundChild = true;
291 
292  while ( foundChild )
293  {
294  foundChild = false; // assume that the next child item will not be found
295 
296  for ( int i = 0; i < model->rowCount( theIndex ); i++ )
297  {
298  QModelIndex idx = model->index( i, 0, theIndex );
299 
300  QString itemPath = model->data( idx, PathRole ).toString();
301  if ( itemPath == path )
302  {
303  QgsDebugMsg( "Arrived " + itemPath );
304  return idx; // we have found the item we have been looking for
305  }
306 
307  // paths are slash separated identifier
308  if ( path.startsWith( itemPath + "/" ) )
309  {
310  foundChild = true;
311  theIndex = idx;
312  break;
313  }
314  }
315  }
316 
317  if ( matchFlag == Qt::MatchStartsWith )
318  return theIndex;
319 
320  QgsDebugMsg( "path not found" );
321  return QModelIndex(); // not found
322 }
323 
325 {
326  // TODO: put items creating currently children in threads to deleteLater (does not seem urget because reload() is not used in QGIS)
327  beginResetModel();
328  removeRootItems();
329  addRootItems();
330  endResetModel();
331 }
332 
333 QModelIndex QgsBrowserModel::index( int row, int column, const QModelIndex &parent ) const
334 {
335  QgsDataItem *p = dataItem( parent );
336  const QVector<QgsDataItem*> &items = p ? p->children() : mRootItems;
337  QgsDataItem *item = items.value( row, 0 );
338  return item ? createIndex( row, column, item ) : QModelIndex();
339 }
340 
342 {
343  QgsDataItem *item = dataItem( index );
344  if ( !item )
345  return QModelIndex();
346 
347  return findItem( item->parent() );
348 }
349 
351 {
352  const QVector<QgsDataItem*> &items = parent ? parent->children() : mRootItems;
353 
354  for ( int i = 0; i < items.size(); i++ )
355  {
356  if ( items[i] == item )
357  return createIndex( i, 0, item );
358 
359  QModelIndex childIndex = findItem( item, items[i] );
360  if ( childIndex.isValid() )
361  return childIndex;
362  }
363 
364  return QModelIndex();
365 }
366 
367 void QgsBrowserModel::beginInsertItems( QgsDataItem *parent, int first, int last )
368 {
369  QgsDebugMsgLevel( "parent mPath = " + parent->path(), 3 );
370  QModelIndex idx = findItem( parent );
371  if ( !idx.isValid() )
372  return;
373  QgsDebugMsgLevel( "valid", 3 );
374  beginInsertRows( idx, first, last );
375  QgsDebugMsgLevel( "end", 3 );
376 }
378 {
379  QgsDebugMsgLevel( "Entered", 3 );
380  endInsertRows();
381 }
382 void QgsBrowserModel::beginRemoveItems( QgsDataItem *parent, int first, int last )
383 {
384  QgsDebugMsgLevel( "parent mPath = " + parent->path(), 3 );
385  QModelIndex idx = findItem( parent );
386  if ( !idx.isValid() )
387  return;
388  beginRemoveRows( idx, first, last );
389 }
391 {
392  QgsDebugMsgLevel( "Entered", 3 );
393  endRemoveRows();
394 }
396 {
397  QgsDebugMsgLevel( "Entered", 3 );
398  QModelIndex idx = findItem( item );
399  if ( !idx.isValid() )
400  return;
401  emit dataChanged( idx, idx );
402 }
404 {
405  QgsDebugMsg( "Entered" );
406  if ( !item )
407  return;
408  QModelIndex idx = findItem( item );
409  if ( !idx.isValid() )
410  return;
411  QgsDebugMsg( QString( "item %1 state changed %2 -> %3" ).arg( item->path() ).arg( oldState ).arg( item->state() ) );
412  emit stateChanged( idx, oldState );
413 }
415 {
416  connect( item, SIGNAL( beginInsertItems( QgsDataItem*, int, int ) ),
417  this, SLOT( beginInsertItems( QgsDataItem*, int, int ) ) );
418  connect( item, SIGNAL( endInsertItems() ),
419  this, SLOT( endInsertItems() ) );
420  connect( item, SIGNAL( beginRemoveItems( QgsDataItem*, int, int ) ),
421  this, SLOT( beginRemoveItems( QgsDataItem*, int, int ) ) );
422  connect( item, SIGNAL( endRemoveItems() ),
423  this, SLOT( endRemoveItems() ) );
424  connect( item, SIGNAL( dataChanged( QgsDataItem* ) ),
425  this, SLOT( itemDataChanged( QgsDataItem* ) ) );
426  connect( item, SIGNAL( stateChanged( QgsDataItem*, QgsDataItem::State ) ),
427  this, SLOT( itemStateChanged( QgsDataItem*, QgsDataItem::State ) ) );
428 }
429 
431 {
432  QStringList types;
433  // In theory the mime type convention is: application/x-vnd.<vendor>.<application>.<type>
434  // but it seems a bit over formalized. Would be an application/x-qgis-uri better?
435  types << "application/x-vnd.qgis.qgis.uri";
436  return types;
437 }
438 
439 QMimeData * QgsBrowserModel::mimeData( const QModelIndexList &indexes ) const
440 {
442  Q_FOREACH ( const QModelIndex &index, indexes )
443  {
444  if ( index.isValid() )
445  {
446  QgsDataItem* ptr = ( QgsDataItem* ) index.internalPointer();
447  if ( ptr->type() != QgsDataItem::Layer ) continue;
448  QgsLayerItem *layer = ( QgsLayerItem* ) ptr;
449  lst.append( QgsMimeDataUtils::Uri( layer ) );
450  }
451  }
452  return QgsMimeDataUtils::encodeUriList( lst );
453 }
454 
455 bool QgsBrowserModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent )
456 {
457  Q_UNUSED( row );
458  Q_UNUSED( column );
459 
460  QgsDataItem* destItem = dataItem( parent );
461  if ( !destItem )
462  {
463  QgsDebugMsg( "DROP PROBLEM!" );
464  return false;
465  }
466 
467  return destItem->handleDrop( data, action );
468 }
469 
471 {
472  void *v = idx.internalPointer();
473  QgsDataItem *d = reinterpret_cast<QgsDataItem*>( v );
474  Q_ASSERT( !v || d );
475  return d;
476 }
477 
478 bool QgsBrowserModel::canFetchMore( const QModelIndex & parent ) const
479 {
480  QgsDataItem* item = dataItem( parent );
481  // if ( item )
482  // QgsDebugMsg( QString( "path = %1 canFetchMore = %2" ).arg( item->path() ).arg( item && ! item->isPopulated() ) );
483  return ( item && item->state() == QgsDataItem::NotPopulated );
484 }
485 
487 {
488  QgsDebugMsg( "Entered" );
489  QgsDataItem* item = dataItem( parent );
490 
491  if ( !item || item->state() == QgsDataItem::Populating || item->state() == QgsDataItem::Populated )
492  return;
493 
494  QgsDebugMsg( "path = " + item->path() );
495 
496  item->populate();
497 }
498 
499 /* Refresh dir path */
501 {
502  QModelIndex index = findPath( path );
503  refresh( index );
504 }
505 
506 /* Refresh item */
507 void QgsBrowserModel::refresh( const QModelIndex& theIndex )
508 {
509  QgsDataItem *item = dataItem( theIndex );
510  if ( !item || item->state() == QgsDataItem::Populating )
511  return;
512 
513  QgsDebugMsg( "Refresh " + item->path() );
514 
515  item->refresh();
516 }
517 
519 {
520  Q_ASSERT( mFavourites );
521  mFavourites->addDirectory( favDir );
522 }
523 
525 {
526  QgsDirectoryItem *item = dynamic_cast<QgsDirectoryItem *>( dataItem( index ) );
527  if ( !item )
528  return;
529 
530  mFavourites->removeDirectory( item );
531 }
Contains various Favourites directories.
Definition: qgsdataitem.h:456
static unsigned index
virtual int rowCount(const QModelIndex &parent) const =0
void removeDirectory(QgsDirectoryItem *item)
static bool cmpByDataItemName_(QgsDataItem *a, QgsDataItem *b)
static QgsDataItemProviderRegistry * instance()
virtual QModelIndex index(int row, int column, const QModelIndex &parent) const =0
bool canFetchMore(const QModelIndex &parent) const override
int localeAwareCompare(const QString &other) const
QVector< QgsDataItem * > children() const
Definition: qgsdataitem.h:180
QString name() const
Definition: qgsdataitem.h:182
QList< T > values() const
QgsDataItem * parent() const
Get item parent.
Definition: qgsdataitem.h:176
virtual QgsDataItem * createDataItem(const QString &path, QgsDataItem *parentItem)=0
Create a new instance of QgsDataItem (or null) for given path and parent item.
virtual int rowCount(const QModelIndex &parent=QModelIndex()) const override
Provides the number of rows of data exposed by the model.
void fetchMore(const QModelIndex &parent) override
virtual QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
Used to supply item data to views and delegates.
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
int indexOf(const T &value, int from) const
void removeFavourite(const QModelIndex &index)
virtual bool handleDrop(const QMimeData *, Qt::DropAction)
Definition: qgsdataitem.h:143
QgsFavouritesItem * mFavourites
QModelIndex findPath(const QString &path, Qt::MatchFlag matchFlag=Qt::MatchExactly)
Return index of item with given path.
void beginRemoveItems(QgsDataItem *parent, int first, int last)
virtual QIcon icon()
void connectItem(QgsDataItem *item)
void insert(int i, const T &value)
State state() const
static QMimeData * encodeUriList(const UriList &layers)
void setIcon(const QIcon &icon)
Definition: qgsdataitem.h:192
void itemStateChanged(QgsDataItem *item, QgsDataItem::State oldState)
virtual QStringList mimeTypes() const override
Returns a list of mime that can describe model indexes.
QString homePath() const
Return project's home path.
QString homePath()
virtual void refresh(QVector< QgsDataItem * > children)
QString tr(const char *sourceText, const char *disambiguation, int n)
bool hasChildren(const QModelIndex &parent=QModelIndex()) const override
int size() const
bool isNull() const
T value(int i) const
QgsDirectoryItem * mProjectHome
void clear()
bool isValid() const
void append(const T &value)
iterator insertMulti(const Key &key, const T &value)
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
QgsBrowserModel(QObject *parent=0)
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:34
QgsDataItem * dataItem(const QModelIndex &idx) const
void remove(int i)
void beginRemoveRows(const QModelIndex &parent, int first, int last)
bool startsWith(const QString &s, Qt::CaseSensitivity cs) const
Children not yet created.
Definition: qgsdataitem.h:104
Creating children in separate thread (populating or refreshing)
Definition: qgsdataitem.h:105
QString path() const
Definition: qgsdataitem.h:184
void * internalPointer() const
Type type() const
Definition: qgsdataitem.h:172
QFileInfoList drives()
virtual int capabilities()=0
Return combination of flags from QgsDataProvider::DataCapabilities.
virtual QVariant data(const QModelIndex &index, int role) const =0
QgsBrowserWatcher(QgsDataItem *item)
bool hasChildren()
A directory: contains subdirectories and layers.
Definition: qgsdataitem.h:373
QModelIndex findItem(QgsDataItem *item, QgsDataItem *parent=0) const
QModelIndex createIndex(int row, int column, void *ptr) const
Base class for all items in the model.
Definition: qgsdataitem.h:75
iterator end()
void addDirectory(const QString &favIcon)
void beginInsertRows(const QModelIndex &parent, int first, int last)
virtual QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
Provides views with information to show in their headers.
void addFavouriteDirectory(const QString &favDir)
virtual void populate(const QVector< QgsDataItem * > &children)
void beginInsertItems(QgsDataItem *parent, int first, int last)
QStyle * style()
virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
Returns the index of the item in the model specified by the given row, column and parent index...
virtual QString comments() const
Returns comments of the layer.
Definition: qgsdataitem.h:330
static QgsProject * instance()
access to canonical QgsProject instance
Definition: qgsproject.cpp:353
int count(const T &value) const
virtual int columnCount(const QModelIndex &parent=QModelIndex()) const override
Provides the number of columns of data exposed by the model.
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
Handles the data supplied by a drag and drop operation that ended with the given action.
void stateChanged(const QModelIndex &index, QgsDataItem::State oldState)
Emitted when item children fetch was finished.
void refresh(const QString &path)
int column() const
virtual QMimeData * mimeData(const QModelIndexList &indexes) const override
Returns an object that contains serialized items of data corresponding to the list of indexes specifi...
Item that represents a layer that can be opened with one of the providers.
Definition: qgsdataitem.h:282
virtual QString name()=0
Human-readable name of the provider name.
void itemDataChanged(QgsDataItem *item)
QString toolTip() const
Definition: qgsdataitem.h:196
virtual Qt::ItemFlags flags(const QModelIndex &index) const override
Used by other components to obtain information about each item provided by the model.
children created
Definition: qgsdataitem.h:106
QString absolutePath() const
virtual bool acceptDrop()
Definition: qgsdataitem.h:140
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QObject * parent() const
int size() const
virtual QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option, const QWidget *widget) const =0
QString arg(qlonglong a, int fieldWidth, int base, const QChar &fillChar) const
QString toString() const
iterator begin()
This is the interface for those who want to add custom data items to the browser tree.
QList< Key > uniqueKeys() const
typedef ItemFlags
QVector< QgsDataItem * > mRootItems