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