QGIS API Documentation  2.99.0-Master (d55fa22)
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 #include <QUrl>
20 
21 #include "qgis.h"
22 #include "qgsapplication.h"
23 #include "qgsdataitemprovider.h"
25 #include "qgsdataprovider.h"
26 #include "qgsmimedatautils.h"
27 #include "qgslogger.h"
28 #include "qgsproviderregistry.h"
29 #include "qgsbrowsermodel.h"
30 #include "qgsproject.h"
31 #include "qgssettings.h"
32 
34  : mItem( item )
35 {
36 }
37 
38 // sort function for QList<QgsDataItem*>, e.g. sorted/grouped provider listings
39 static bool cmpByDataItemName_( QgsDataItem *a, QgsDataItem *b )
40 {
41  return QString::localeAwareCompare( a->name(), b->name() ) < 0;
42 }
43 
45  : QAbstractItemModel( parent )
46  , mFavorites( nullptr )
47  , mProjectHome( nullptr )
48 {
51  addRootItems();
52 }
53 
55 {
57 }
58 
60 {
61  QString home = QgsProject::instance()->homePath();
62  if ( mProjectHome && mProjectHome->path() == home )
63  return;
64 
65  int idx = mRootItems.indexOf( mProjectHome );
66 
67  // using layoutAboutToBeChanged() was messing expanded items
68  if ( idx >= 0 )
69  {
70  beginRemoveRows( QModelIndex(), idx, idx );
71  mRootItems.remove( idx );
72  endRemoveRows();
73  }
74  delete mProjectHome;
75  mProjectHome = home.isNull() ? nullptr : new QgsDirectoryItem( nullptr, tr( "Project home" ), home, "project:" + home );
76  if ( mProjectHome )
77  {
79 
80  beginInsertRows( QModelIndex(), 0, 0 );
81  mRootItems.insert( 0, mProjectHome );
82  endInsertRows();
83  }
84 }
85 
87 {
89 
90  // give the home directory a prominent second place
91  QgsDirectoryItem *item = new QgsDirectoryItem( nullptr, tr( "Home" ), QDir::homePath(), "home:" + QDir::homePath() );
92  QStyle *style = QApplication::style();
93  QIcon homeIcon( style->standardPixmap( QStyle::SP_DirHomeIcon ) );
94  item->setIcon( homeIcon );
95  connectItem( item );
96  mRootItems << item;
97 
98  // add favorite directories
99  mFavorites = new QgsFavoritesItem( nullptr, tr( "Favorites" ) );
100  if ( mFavorites )
101  {
104  }
105 
106  // add drives
107  Q_FOREACH ( const QFileInfo &drive, QDir::drives() )
108  {
109  QString path = drive.absolutePath();
110 
111  if ( QgsDirectoryItem::hiddenPath( path ) )
112  continue;
113 
114  QgsDirectoryItem *item = new QgsDirectoryItem( nullptr, path, path );
115 
116  connectItem( item );
117  mRootItems << item;
118  }
119 
120 #ifdef Q_OS_MAC
121  QString path = QString( "/Volumes" );
122  QgsDirectoryItem *vols = new QgsDirectoryItem( nullptr, path, path );
123  connectItem( vols );
124  mRootItems << vols;
125 #endif
126 
127  // container for displaying providers as sorted groups (by QgsDataProvider::DataCapability enum)
128  QMap<int, QgsDataItem *> providerMap;
129 
130  Q_FOREACH ( QgsDataItemProvider *pr, QgsApplication::dataItemProviderRegistry()->providers() )
131  {
132  int capabilities = pr->capabilities();
133  if ( capabilities == QgsDataProvider::NoDataCapabilities )
134  {
135  QgsDebugMsgLevel( pr->name() + " does not have any dataCapabilities", 4 );
136  continue;
137  }
138 
139  QgsDataItem *item = pr->createDataItem( QLatin1String( "" ), nullptr ); // empty path -> top level
140  if ( item )
141  {
142  QgsDebugMsgLevel( "Add new top level item : " + item->name(), 4 );
143  connectItem( item );
144  providerMap.insertMulti( capabilities, item );
145  }
146  }
147 
148  // add as sorted groups by QgsDataProvider::DataCapability enum
149  Q_FOREACH ( int key, providerMap.uniqueKeys() )
150  {
151  QList<QgsDataItem *> providerGroup = providerMap.values( key );
152  if ( providerGroup.size() > 1 )
153  {
154  std::sort( providerGroup.begin(), providerGroup.end(), cmpByDataItemName_ );
155  }
156 
157  Q_FOREACH ( QgsDataItem *ditem, providerGroup )
158  {
159  mRootItems << ditem;
160  }
161  }
162 }
163 
165 {
166  Q_FOREACH ( QgsDataItem *item, mRootItems )
167  {
168  delete item;
169  }
170 
171  mRootItems.clear();
172 }
173 
174 
175 Qt::ItemFlags QgsBrowserModel::flags( const QModelIndex &index ) const
176 {
177  if ( !index.isValid() )
178  return Qt::ItemFlags();
179 
180  Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
181 
182  QgsDataItem *ptr = reinterpret_cast< QgsDataItem * >( index.internalPointer() );
183  if ( ptr->hasDragEnabled() )
184  flags |= Qt::ItemIsDragEnabled;
185 
186  if ( ptr->acceptDrop() )
187  flags |= Qt::ItemIsDropEnabled;
188  return flags;
189 }
190 
191 QVariant QgsBrowserModel::data( const QModelIndex &index, int role ) const
192 {
193  if ( !index.isValid() )
194  return QVariant();
195 
196  QgsDataItem *item = dataItem( index );
197  if ( !item )
198  {
199  return QVariant();
200  }
201  else if ( role == Qt::DisplayRole )
202  {
203  return item->name();
204  }
205  else if ( role == Qt::ToolTipRole )
206  {
207  return item->toolTip();
208  }
209  else if ( role == Qt::DecorationRole && index.column() == 0 )
210  {
211  return item->icon();
212  }
213  else if ( role == QgsBrowserModel::PathRole )
214  {
215  return item->path();
216  }
217  else if ( role == QgsBrowserModel::CommentRole )
218  {
219  if ( item->type() == QgsDataItem::Layer )
220  {
221  QgsLayerItem *lyrItem = qobject_cast<QgsLayerItem *>( item );
222  return lyrItem->comments();
223  }
224  return QVariant();
225  }
226  else
227  {
228  // unsupported role
229  return QVariant();
230  }
231 }
232 
233 QVariant QgsBrowserModel::headerData( int section, Qt::Orientation orientation, int role ) const
234 {
235  Q_UNUSED( section );
236  if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )
237  {
238  return QVariant( "header" );
239  }
240 
241  return QVariant();
242 }
243 
244 int QgsBrowserModel::rowCount( const QModelIndex &parent ) const
245 {
246  //QgsDebugMsg(QString("isValid = %1 row = %2 column = %3").arg(parent.isValid()).arg(parent.row()).arg(parent.column()));
247 
248  if ( !parent.isValid() )
249  {
250  // root item: its children are top level items
251  return mRootItems.count(); // mRoot
252  }
253  else
254  {
255  // ordinary item: number of its children
256  QgsDataItem *item = dataItem( parent );
257  //if ( item ) QgsDebugMsg(QString("path = %1 rowCount = %2").arg(item->path()).arg(item->rowCount()) );
258  return item ? item->rowCount() : 0;
259  }
260 }
261 
262 bool QgsBrowserModel::hasChildren( const QModelIndex &parent ) const
263 {
264  if ( !parent.isValid() )
265  return true; // root item: its children are top level items
266 
267  QgsDataItem *item = dataItem( parent );
268  return item && item->hasChildren();
269 }
270 
271 int QgsBrowserModel::columnCount( const QModelIndex &parent ) const
272 {
273  Q_UNUSED( parent );
274  return 1;
275 }
276 
277 QModelIndex QgsBrowserModel::findPath( const QString &path, Qt::MatchFlag matchFlag )
278 {
279  return findPath( this, path, matchFlag );
280 }
281 
282 QModelIndex QgsBrowserModel::findPath( QAbstractItemModel *model, const QString &path, Qt::MatchFlag matchFlag )
283 {
284  if ( !model )
285  return QModelIndex();
286 
287  QModelIndex index; // starting from root
288  bool foundChild = true;
289 
290  while ( foundChild )
291  {
292  foundChild = false; // assume that the next child item will not be found
293 
294  for ( int i = 0; i < model->rowCount( index ); i++ )
295  {
296  QModelIndex idx = model->index( i, 0, index );
297 
298  QString itemPath = model->data( idx, PathRole ).toString();
299  if ( itemPath == path )
300  {
301  QgsDebugMsgLevel( "Arrived " + itemPath, 4 );
302  return idx; // we have found the item we have been looking for
303  }
304 
305  // paths are slash separated identifier
306  if ( path.startsWith( itemPath + '/' ) )
307  {
308  foundChild = true;
309  index = idx;
310  break;
311  }
312  }
313  }
314 
315  if ( matchFlag == Qt::MatchStartsWith )
316  return index;
317 
318  QgsDebugMsgLevel( "path not found", 4 );
319  return QModelIndex(); // not found
320 }
321 
323 {
324  // TODO: put items creating currently children in threads to deleteLater (does not seem urget because reload() is not used in QGIS)
325  beginResetModel();
326  removeRootItems();
327  addRootItems();
328  endResetModel();
329 }
330 
331 QModelIndex QgsBrowserModel::index( int row, int column, const QModelIndex &parent ) const
332 {
333  if ( column < 0 || column >= columnCount() || row < 0 )
334  return QModelIndex();
335 
336  QgsDataItem *p = dataItem( parent );
337  const QVector<QgsDataItem *> &items = p ? p->children() : mRootItems;
338  QgsDataItem *item = items.value( row, nullptr );
339  return item ? createIndex( row, column, item ) : QModelIndex();
340 }
341 
342 QModelIndex QgsBrowserModel::parent( const QModelIndex &index ) const
343 {
344  QgsDataItem *item = dataItem( index );
345  if ( !item )
346  return QModelIndex();
347 
348  return findItem( item->parent() );
349 }
350 
352 {
353  const QVector<QgsDataItem *> &items = parent ? parent->children() : mRootItems;
354 
355  for ( int i = 0; i < items.size(); i++ )
356  {
357  if ( items[i] == item )
358  return createIndex( i, 0, item );
359 
360  QModelIndex childIndex = findItem( item, items[i] );
361  if ( childIndex.isValid() )
362  return childIndex;
363  }
364 
365  return QModelIndex();
366 }
367 
369 {
370  QgsDebugMsgLevel( "parent mPath = " + parent->path(), 3 );
371  QModelIndex idx = findItem( parent );
372  if ( !idx.isValid() )
373  return;
374  QgsDebugMsgLevel( "valid", 3 );
375  beginInsertRows( idx, first, last );
376  QgsDebugMsgLevel( "end", 3 );
377 }
379 {
380  QgsDebugMsgLevel( "Entered", 3 );
381  endInsertRows();
382 }
384 {
385  QgsDebugMsgLevel( "parent mPath = " + parent->path(), 3 );
386  QModelIndex idx = findItem( parent );
387  if ( !idx.isValid() )
388  return;
389  beginRemoveRows( idx, first, last );
390 }
392 {
393  QgsDebugMsgLevel( "Entered", 3 );
394  endRemoveRows();
395 }
397 {
398  QgsDebugMsgLevel( "Entered", 3 );
399  QModelIndex idx = findItem( item );
400  if ( !idx.isValid() )
401  return;
402  emit dataChanged( idx, idx );
403 }
405 {
406  if ( !item )
407  return;
408  QModelIndex idx = findItem( item );
409  if ( !idx.isValid() )
410  return;
411  QgsDebugMsgLevel( QString( "item %1 state changed %2 -> %3" ).arg( item->path() ).arg( oldState ).arg( item->state() ), 4 );
412  emit stateChanged( idx, oldState );
413 }
415 {
416  connect( item, &QgsDataItem::beginInsertItems,
418  connect( item, &QgsDataItem::endInsertItems,
420  connect( item, &QgsDataItem::beginRemoveItems,
422  connect( item, &QgsDataItem::endRemoveItems,
424  connect( item, &QgsDataItem::dataChanged,
426  connect( item, &QgsDataItem::stateChanged,
428 }
429 
430 QStringList QgsBrowserModel::mimeTypes() const
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 << QStringLiteral( "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 = reinterpret_cast< QgsDataItem * >( index.internalPointer() );
447  if ( ptr->type() == QgsDataItem::Project )
448  {
449  QMimeData *mimeData = new QMimeData();
450  QUrl url = QUrl::fromLocalFile( ptr->path() );
451  QList<QUrl> urls;
452  urls << url;
453  mimeData->setUrls( urls );
454  return mimeData;
455  }
456 
457  QgsMimeDataUtils::Uri uri = ptr->mimeUri();
458  if ( uri.isValid() )
459  lst.append( uri );
460  }
461  }
462  return QgsMimeDataUtils::encodeUriList( lst );
463 }
464 
465 bool QgsBrowserModel::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent )
466 {
467  Q_UNUSED( row );
468  Q_UNUSED( column );
469 
470  QgsDataItem *destItem = dataItem( parent );
471  if ( !destItem )
472  {
473  QgsDebugMsgLevel( "DROP PROBLEM!", 4 );
474  return false;
475  }
476 
477  return destItem->handleDrop( data, action );
478 }
479 
480 QgsDataItem *QgsBrowserModel::dataItem( const QModelIndex &idx ) const
481 {
482  void *v = idx.internalPointer();
483  QgsDataItem *d = reinterpret_cast<QgsDataItem *>( v );
484  Q_ASSERT( !v || d );
485  return d;
486 }
487 
488 bool QgsBrowserModel::canFetchMore( const QModelIndex &parent ) const
489 {
490  QgsDataItem *item = dataItem( parent );
491  // if ( item )
492  // QgsDebugMsg( QString( "path = %1 canFetchMore = %2" ).arg( item->path() ).arg( item && ! item->isPopulated() ) );
493  return ( item && item->state() == QgsDataItem::NotPopulated );
494 }
495 
496 void QgsBrowserModel::fetchMore( const QModelIndex &parent )
497 {
498  QgsDataItem *item = dataItem( parent );
499 
500  if ( !item || item->state() == QgsDataItem::Populating || item->state() == QgsDataItem::Populated )
501  return;
502 
503  QgsDebugMsgLevel( "path = " + item->path(), 4 );
504 
505  item->populate();
506 }
507 
508 /* Refresh dir path */
509 void QgsBrowserModel::refresh( const QString &path )
510 {
511  QModelIndex index = findPath( path );
512  refresh( index );
513 }
514 
515 /* Refresh item */
516 void QgsBrowserModel::refresh( const QModelIndex &index )
517 {
518  QgsDataItem *item = dataItem( index );
519  if ( !item || item->state() == QgsDataItem::Populating )
520  return;
521 
522  QgsDebugMsgLevel( "Refresh " + item->path(), 4 );
523 
524  item->refresh();
525 }
526 
527 void QgsBrowserModel::addFavoriteDirectory( const QString &directory )
528 {
529  Q_ASSERT( mFavorites );
530  mFavorites->addDirectory( directory );
531 }
532 
533 void QgsBrowserModel::removeFavorite( const QModelIndex &index )
534 {
535  QgsDirectoryItem *item = dynamic_cast<QgsDirectoryItem *>( dataItem( index ) );
536  if ( !item )
537  return;
538 
539  mFavorites->removeDirectory( item );
540 }
541 
543 {
544  QgsSettings settings;
545  QStringList hiddenItems = settings.value( QStringLiteral( "browser/hiddenPaths" ),
546  QStringList() ).toStringList();
547  int idx = hiddenItems.indexOf( item->path() );
548  if ( idx != -1 )
549  {
550  hiddenItems.removeAt( idx );
551  }
552  else
553  {
554  hiddenItems << item->path();
555  }
556  settings.setValue( QStringLiteral( "browser/hiddenPaths" ), hiddenItems );
557  if ( item->parent() )
558  {
559  item->parent()->deleteChildItem( item );
560  }
561  else
562  {
563  int i = mRootItems.indexOf( item );
564  emit beginRemoveRows( QModelIndex(), i, i );
565  mRootItems.remove( i );
566  item->deleteLater();
567  emit endRemoveRows();
568  }
569 }
void beginInsertItems(QgsDataItem *parent, int first, int last)
QString path() const
Definition: qgsdataitem.h:213
bool canFetchMore(const QModelIndex &parent) const override
QString name() const
Definition: qgsdataitem.h:211
void dataChanged(QgsDataItem *item)
QString toolTip() const
Definition: qgsdataitem.h:225
void hidePath(QgsDataItem *item)
Hide the given path in the browser model.
QgsBrowserModel(QObject *parent=nullptr)
This class is a composition of two QSettings instances:
Definition: qgssettings.h:54
virtual QgsDataItem * createDataItem(const QString &path, QgsDataItem *parentItem)=0
Create a new instance of QgsDataItem (or null) for given path and parent item.
void addDirectory(const QString &directory)
Adds a new directory to the favorites group.
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.
virtual bool handleDrop(const QMimeData *, Qt::DropAction)
Attempts to process the mime data dropped on this item.
Definition: qgsdataitem.h:153
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)
Type type() const
Definition: qgsdataitem.h:200
static QMimeData * encodeUriList(const UriList &layers)
void setIcon(const QIcon &icon)
Definition: qgsdataitem.h:221
bool isValid() const
Returns whether the object contains valid data.
void itemStateChanged(QgsDataItem *item, QgsDataItem::State oldState)
virtual QStringList mimeTypes() const override
Returns a list of mime that can describe model indexes.
bool hasChildren(const QModelIndex &parent=QModelIndex()) const override
void endRemoveItems()
State state() const
Item path used to access path in the tree, see QgsDataItem::mPath.
QString homePath
Definition: qgsproject.h:83
QgsDirectoryItem * mProjectHome
void setValue(const QString &key, const QVariant &value, const QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static void deleteLater(QVector< QgsDataItem *> &items)
QgsDataItem * parent() const
Get item parent.
Definition: qgsdataitem.h:204
QgsFavoritesItem * mFavorites
void beginRemoveItems(QgsDataItem *parent, int first, int last)
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:38
virtual QModelIndex parent(const QModelIndex &index) const override
Returns the parent of the model item with the given index.
QVector< QgsDataItem * > mRootItems
void readProject(const QDomDocument &)
emitted when project is being read
Children not yet created.
Definition: qgsdataitem.h:99
Creating children in separate thread (populating or refreshing)
Definition: qgsdataitem.h:100
QgsDataItem * dataItem(const QModelIndex &idx) const
void removeFavorite(const QModelIndex &index)
Removes a favorite directory from its corresponding model index.
virtual bool hasDragEnabled() const
Returns true if the item may be dragged.
Definition: qgsdataitem.h:161
virtual int capabilities()=0
Return combination of flags from QgsDataProvider::DataCapabilities.
virtual QgsMimeDataUtils::Uri mimeUri() const
Return mime URI for the data item.
Definition: qgsdataitem.h:168
QgsBrowserWatcher(QgsDataItem *item)
bool hasChildren()
static bool hiddenPath(const QString &path)
Check if the given path is hidden from the browser model.
void reload()
Reload the whole model.
A directory: contains subdirectories and layers.
Definition: qgsdataitem.h:418
Base class for all items in the model.
Definition: qgsdataitem.h:47
QVector< QgsDataItem * > children() const
Definition: qgsdataitem.h:209
QModelIndex findItem(QgsDataItem *item, QgsDataItem *parent=nullptr) const
void writeProject(QDomDocument &)
emitted when project is being written
virtual QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const override
Provides views with information to show in their headers.
void beginInsertItems(QgsDataItem *parent, int first, int last)
Contains various Favorites directories.
Definition: qgsdataitem.h:523
void removeDirectory(QgsDirectoryItem *item)
Removes an existing directory from the favorites group.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), const Section section=NoSection) const
Returns the value for setting key.
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...
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:377
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)
Refresh item specified by path.
QList< QgsMimeDataUtils::Uri > UriList
void endInsertItems()
virtual QMimeData * mimeData(const QModelIndexList &indexes) const override
Returns an object that contains serialized items of data corresponding to the list of indexes specifi...
Represents a QGIS project.
Definition: qgsdataitem.h:82
Item that represents a layer that can be opened with one of the providers.
Definition: qgsdataitem.h:319
virtual void deleteChildItem(QgsDataItem *child)
Removes and deletes a child item, emitting relevant signals to the model.
virtual QString name()=0
Human-readable name of the provider name.
void itemDataChanged(QgsDataItem *item)
void addFavoriteDirectory(const QString &directory)
Adds a directory to the favorites group.
virtual Qt::ItemFlags flags(const QModelIndex &index) const override
Used by other components to obtain information about each item provided by the model.
virtual void populate(const QVector< QgsDataItem *> &children)
Children created.
Definition: qgsdataitem.h:101
virtual bool acceptDrop()
Returns whether the item accepts drag and dropped layers - e.g.
Definition: qgsdataitem.h:147
virtual QString comments() const
Returns comments of the layer.
Definition: qgsdataitem.h:371
void addRootItems()
Populates the model.
static QgsDataItemProviderRegistry * dataItemProviderRegistry()
Returns the application&#39;s data item provider registry, which keeps a list of data item providers that...
virtual void refresh(const QVector< QgsDataItem *> &children)
Refresh the items from a specified list of child items.
This is the interface for those who want to add custom data items to the browser tree.
void stateChanged(QgsDataItem *item, QgsDataItem::State oldState)