QGIS API Documentation  3.6.0-Noosa (5873452)
qgslayerdefinition.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgslayerdefinition.cpp
3  ---------------------
4  begin : January 2015
5  copyright : (C) 2015 by Nathan Woodrow
6  email : woodrow dot nathan 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 <QFileInfo>
16 #include <QFile>
17 #include <QDir>
18 #include <QTextStream>
19 
20 #include "qgslayerdefinition.h"
21 #include "qgslayertree.h"
22 #include "qgslogger.h"
23 #include "qgsmaplayer.h"
24 #include "qgspathresolver.h"
25 #include "qgspluginlayer.h"
26 #include "qgspluginlayerregistry.h"
27 #include "qgsproject.h"
28 #include "qgsrasterlayer.h"
29 #include "qgsreadwritecontext.h"
30 #include "qgsvectorlayer.h"
31 #include "qgsapplication.h"
32 
33 bool QgsLayerDefinition::loadLayerDefinition( const QString &path, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage )
34 {
35  QFile file( path );
36  if ( !file.open( QIODevice::ReadOnly ) )
37  {
38  errorMessage = QStringLiteral( "Can not open file" );
39  return false;
40  }
41 
42  QDomDocument doc;
43  QString message;
44  if ( !doc.setContent( &file, &message ) )
45  {
46  errorMessage = message;
47  return false;
48  }
49 
50  QFileInfo fileinfo( file );
51  QDir::setCurrent( fileinfo.absoluteDir().path() );
52 
53  QgsReadWriteContext context;
54  context.setPathResolver( QgsPathResolver( path ) );
55  context.setProjectTranslator( project );
56 
57  return loadLayerDefinition( doc, project, rootGroup, errorMessage, context );
58 }
59 
60 bool QgsLayerDefinition::loadLayerDefinition( QDomDocument doc, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage, QgsReadWriteContext &context )
61 {
62  Q_UNUSED( errorMessage );
63 
65 
66  // reorder maplayer nodes based on dependencies
67  // dependencies have to be resolved before IDs get changed
68  DependencySorter depSorter( doc );
69  if ( !depSorter.hasMissingDependency() )
70  {
71  QVector<QDomNode> sortedLayerNodes = depSorter.sortedLayerNodes();
72  QVector<QDomNode> clonedSorted;
73  Q_FOREACH ( const QDomNode &node, sortedLayerNodes )
74  {
75  clonedSorted << node.cloneNode();
76  }
77  QDomNode layersNode = doc.elementsByTagName( QStringLiteral( "maplayers" ) ).at( 0 );
78  // replace old children with new ones
79  QDomNodeList childNodes = layersNode.childNodes();
80  for ( int i = 0; i < childNodes.size(); i++ )
81  {
82  layersNode.replaceChild( clonedSorted.at( i ), childNodes.at( i ) );
83  }
84  }
85  // if a dependency is missing, we still try to load layers, since dependencies may already be loaded
86 
87  // IDs of layers should be changed otherwise we may have more then one layer with the same id
88  // We have to replace the IDs before we load them because it's too late once they are loaded
89  QDomNodeList ids = doc.elementsByTagName( QStringLiteral( "id" ) );
90  for ( int i = 0; i < ids.size(); ++i )
91  {
92  QDomNode idnode = ids.at( i );
93  QDomElement idElem = idnode.toElement();
94  QString oldid = idElem.text();
95  // Strip the date part because we will replace it.
96  QString layername = oldid.left( oldid.length() - 17 );
97  QDateTime dt = QDateTime::currentDateTime();
98  QString newid = layername + dt.toString( QStringLiteral( "yyyyMMddhhmmsszzz" ) ) + QString::number( qrand() );
99  idElem.firstChild().setNodeValue( newid );
100  QDomNodeList treeLayerNodes = doc.elementsByTagName( QStringLiteral( "layer-tree-layer" ) );
101 
102  for ( int i = 0; i < treeLayerNodes.count(); ++i )
103  {
104  QDomNode layerNode = treeLayerNodes.at( i );
105  QDomElement layerElem = layerNode.toElement();
106  if ( layerElem.attribute( QStringLiteral( "id" ) ) == oldid )
107  {
108  layerNode.toElement().setAttribute( QStringLiteral( "id" ), newid );
109  }
110  }
111 
112  // change layer IDs for vector joins
113  QDomNodeList vectorJoinNodes = doc.elementsByTagName( QStringLiteral( "join" ) ); // TODO: Find a better way of searching for vectorjoins, there might be other <join> elements within the project.
114  for ( int j = 0; j < vectorJoinNodes.size(); ++j )
115  {
116  QDomNode joinNode = vectorJoinNodes.at( j );
117  QDomElement joinElement = joinNode.toElement();
118  if ( joinElement.attribute( QStringLiteral( "joinLayerId" ) ) == oldid )
119  {
120  joinNode.toElement().setAttribute( QStringLiteral( "joinLayerId" ), newid );
121  }
122  }
123 
124  // change IDs of dependencies
125  QDomNodeList dataDeps = doc.elementsByTagName( QStringLiteral( "dataDependencies" ) );
126  for ( int i = 0; i < dataDeps.size(); i++ )
127  {
128  QDomNodeList layers = dataDeps.at( i ).childNodes();
129  for ( int j = 0; j < layers.size(); j++ )
130  {
131  QDomElement elt = layers.at( j ).toElement();
132  if ( elt.attribute( QStringLiteral( "id" ) ) == oldid )
133  {
134  elt.setAttribute( QStringLiteral( "id" ), newid );
135  }
136  }
137  }
138 
139  }
140 
141  QDomElement layerTreeElem = doc.documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) );
142  bool loadInLegend = true;
143  if ( !layerTreeElem.isNull() )
144  {
145  root->readChildrenFromXml( layerTreeElem, context );
146  loadInLegend = false;
147  }
148 
149  QList<QgsMapLayer *> layers = QgsLayerDefinition::loadLayerDefinitionLayers( doc, context );
150 
151  project->addMapLayers( layers, loadInLegend );
152 
153  // Now that all layers are loaded, refresh the vectorjoins to get the joined fields
154  Q_FOREACH ( QgsMapLayer *layer, layers )
155  {
156  if ( QgsVectorLayer *vlayer = qobject_cast< QgsVectorLayer * >( layer ) )
157  {
158  vlayer->resolveReferences( project );
159  }
160  }
161 
162  root->resolveReferences( project );
163 
164  QList<QgsLayerTreeNode *> nodes = root->children();
165  Q_FOREACH ( QgsLayerTreeNode *node, nodes )
166  root->takeChild( node );
167  delete root;
168 
169  rootGroup->insertChildNodes( -1, nodes );
170 
171  return true;
172 
173 }
174 
175 bool QgsLayerDefinition::exportLayerDefinition( QString path, const QList<QgsLayerTreeNode *> &selectedTreeNodes, QString &errorMessage )
176 {
177  if ( !path.endsWith( QLatin1String( ".qlr" ) ) )
178  path = path.append( ".qlr" );
179 
180  QFile file( path );
181 
182  if ( !file.open( QFile::WriteOnly | QFile::Truncate ) )
183  {
184  errorMessage = file.errorString();
185  return false;
186  }
187 
188  QgsReadWriteContext context;
189  context.setPathResolver( QgsPathResolver( path ) );
190 
191  QDomDocument doc( QStringLiteral( "qgis-layer-definition" ) );
192  if ( !exportLayerDefinition( doc, selectedTreeNodes, errorMessage, context ) )
193  return false;
194 
195  QTextStream qlayerstream( &file );
196  doc.save( qlayerstream, 2 );
197  return true;
198 }
199 
200 bool QgsLayerDefinition::exportLayerDefinition( QDomDocument doc, const QList<QgsLayerTreeNode *> &selectedTreeNodes, QString &errorMessage, const QgsReadWriteContext &context )
201 {
202  Q_UNUSED( errorMessage );
203  QDomElement qgiselm = doc.createElement( QStringLiteral( "qlr" ) );
204  doc.appendChild( qgiselm );
205  QList<QgsLayerTreeNode *> nodes = selectedTreeNodes;
207  Q_FOREACH ( QgsLayerTreeNode *node, nodes )
208  {
209  QgsLayerTreeNode *newnode = node->clone();
210  root->addChildNode( newnode );
211  }
212  root->writeXml( qgiselm, context );
213 
214  QDomElement layerselm = doc.createElement( QStringLiteral( "maplayers" ) );
215  QList<QgsLayerTreeLayer *> layers = root->findLayers();
216  Q_FOREACH ( QgsLayerTreeLayer *layer, layers )
217  {
218  if ( ! layer->layer() )
219  {
220  QgsDebugMsgLevel( QStringLiteral( "Not a valid map layer: skipping %1" ).arg( layer->name( ) ), 4 );
221  continue;
222  }
223  QDomElement layerelm = doc.createElement( QStringLiteral( "maplayer" ) );
224  layer->layer()->writeLayerXml( layerelm, doc, context );
225  layerselm.appendChild( layerelm );
226  }
227  qgiselm.appendChild( layerselm );
228  return true;
229 }
230 
231 QDomDocument QgsLayerDefinition::exportLayerDefinitionLayers( const QList<QgsMapLayer *> &layers, const QgsReadWriteContext &context )
232 {
233  QDomDocument doc( QStringLiteral( "qgis-layer-definition" ) );
234  QDomElement qgiselm = doc.createElement( QStringLiteral( "qlr" ) );
235  doc.appendChild( qgiselm );
236  QDomElement layerselm = doc.createElement( QStringLiteral( "maplayers" ) );
237  Q_FOREACH ( QgsMapLayer *layer, layers )
238  {
239  QDomElement layerelm = doc.createElement( QStringLiteral( "maplayer" ) );
240  layer->writeLayerXml( layerelm, doc, context );
241  layerselm.appendChild( layerelm );
242  }
243  qgiselm.appendChild( layerselm );
244  return doc;
245 }
246 
247 QList<QgsMapLayer *> QgsLayerDefinition::loadLayerDefinitionLayers( QDomDocument &document, QgsReadWriteContext &context )
248 {
249  QList<QgsMapLayer *> layers;
250  QDomNodeList layernodes = document.elementsByTagName( QStringLiteral( "maplayer" ) );
251  for ( int i = 0; i < layernodes.size(); ++i )
252  {
253  QDomNode layernode = layernodes.at( i );
254  QDomElement layerElem = layernode.toElement();
255 
256  QString type = layerElem.attribute( QStringLiteral( "type" ) );
257  QgsDebugMsg( type );
258  QgsMapLayer *layer = nullptr;
259 
260  if ( type == QLatin1String( "vector" ) )
261  {
262  layer = new QgsVectorLayer;
263  }
264  else if ( type == QLatin1String( "raster" ) )
265  {
266  layer = new QgsRasterLayer;
267  }
268  else if ( type == QLatin1String( "plugin" ) )
269  {
270  QString typeName = layerElem.attribute( QStringLiteral( "name" ) );
271  layer = QgsApplication::pluginLayerRegistry()->createLayer( typeName );
272  }
273 
274  if ( !layer )
275  continue;
276 
277  if ( layer->readLayerXml( layerElem, context ) )
278  {
279  layers << layer;
280  }
281  }
282  return layers;
283 }
284 
285 QList<QgsMapLayer *> QgsLayerDefinition::loadLayerDefinitionLayers( const QString &qlrfile )
286 {
287  QFile file( qlrfile );
288  if ( !file.open( QIODevice::ReadOnly ) )
289  {
290  QgsDebugMsg( QStringLiteral( "Can't open file" ) );
291  return QList<QgsMapLayer *>();
292  }
293 
294  QDomDocument doc;
295  if ( !doc.setContent( &file ) )
296  {
297  QgsDebugMsg( QStringLiteral( "Can't set content" ) );
298  return QList<QgsMapLayer *>();
299  }
300 
301  QgsReadWriteContext context;
302  context.setPathResolver( QgsPathResolver( qlrfile ) );
303  //no project translator defined here
304  return QgsLayerDefinition::loadLayerDefinitionLayers( doc, context );
305 }
306 
307 
308 void QgsLayerDefinition::DependencySorter::init( const QDomDocument &doc )
309 {
310  // Determine a loading order of layers based on a graph of dependencies
311  QMap< QString, QVector< QString > > dependencies;
312  QStringList sortedLayers;
313  QList< QPair<QString, QDomNode> > layersToSort;
314  QStringList layerIds;
315 
316  QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "maplayer" ) );
317  layerIds.reserve( nl.count() );
318  QVector<QString> deps; //avoid expensive allocation for list for every iteration
319  for ( int i = 0; i < nl.count(); i++ )
320  {
321  deps.resize( 0 ); // preserve capacity - don't use clear
322  QDomNode node = nl.item( i );
323 
324  QString id = node.namedItem( QStringLiteral( "id" ) ).toElement().text();
325  layerIds << id;
326 
327  // dependencies for this layer
328  QDomElement layerDependenciesElem = node.firstChildElement( QStringLiteral( "layerDependencies" ) );
329  if ( !layerDependenciesElem.isNull() )
330  {
331  QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( QStringLiteral( "layer" ) );
332  for ( int j = 0; j < dependencyList.size(); ++j )
333  {
334  QDomElement depElem = dependencyList.at( j ).toElement();
335  deps << depElem.attribute( QStringLiteral( "id" ) );
336  }
337  }
338  dependencies[id] = deps;
339 
340  if ( deps.empty() )
341  {
342  sortedLayers << id;
343  mSortedLayerNodes << node;
344  mSortedLayerIds << id;
345  }
346  else
347  layersToSort << qMakePair( id, node );
348  }
349 
350  // check that all dependencies are present
351  Q_FOREACH ( const QVector< QString > &ids, dependencies )
352  {
353  Q_FOREACH ( const QString &depId, ids )
354  {
355  if ( !dependencies.contains( depId ) )
356  {
357  // some dependencies are not satisfied
358  mHasMissingDependency = true;
359  for ( int i = 0; i < nl.size(); i++ )
360  mSortedLayerNodes << nl.at( i );
361  mSortedLayerIds = layerIds;
362  return;
363  }
364  }
365  }
366 
367  // cycles should be very rare, since layers with cyclic dependencies may only be created by
368  // manually modifying the project file
369  mHasCycle = false;
370 
371  while ( !layersToSort.empty() && !mHasCycle )
372  {
373  QList< QPair<QString, QDomNode> >::iterator it = layersToSort.begin();
374  while ( it != layersToSort.end() )
375  {
376  QString idToSort = it->first;
377  QDomNode node = it->second;
378  mHasCycle = true;
379  bool resolved = true;
380  Q_FOREACH ( const QString &dep, dependencies[idToSort] )
381  {
382  if ( !sortedLayers.contains( dep ) )
383  {
384  resolved = false;
385  break;
386  }
387  }
388  if ( resolved ) // dependencies for this layer are resolved
389  {
390  sortedLayers << idToSort;
391  mSortedLayerNodes << node;
392  mSortedLayerIds << idToSort;
393  it = layersToSort.erase( it ); // erase and go to the next
394  mHasCycle = false;
395  }
396  else
397  {
398  ++it;
399  }
400  }
401  }
402 }
403 
405  : mHasCycle( false )
406  , mHasMissingDependency( false )
407 {
408  init( doc );
409 }
410 
412  : mHasCycle( false )
413  , mHasMissingDependency( false )
414 {
415  QDomDocument doc;
416  QFile pFile( fileName );
417  ( void )pFile.open( QIODevice::ReadOnly );
418  ( void )doc.setContent( &pFile );
419  init( doc );
420 }
421 
422 
Layer tree group node serves as a container for layers and further groups.
The class is used as a container of context for various read/write operations on other objects...
void readChildrenFromXml(QDomElement &element, const QgsReadWriteContext &context)
Read children from XML and append them to the group.
static QDomDocument exportLayerDefinitionLayers(const QList< QgsMapLayer *> &layers, const QgsReadWriteContext &context)
Returns the given layer as a layer definition document Layer definitions store the data source as wel...
QList< QgsMapLayer * > addMapLayers(const QList< QgsMapLayer *> &mapLayers, bool addToLegend=true, bool takeOwnership=true)
Add a list of layers to the map of loaded layers.
Base class for all map layer types.
Definition: qgsmaplayer.h:64
void setPathResolver(const QgsPathResolver &resolver)
Sets up path resolver for conversion between relative and absolute paths.
bool takeChild(QgsLayerTreeNode *node)
Remove a child from a node.
static bool loadLayerDefinition(const QString &path, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage)
Loads the QLR at path into QGIS. New layers are added to given project into layer tree specified by r...
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
This class provides qgis with the ability to render raster datasets onto the mapcanvas.
virtual QgsLayerTreeNode * clone() const =0
Create a copy of the node. Returns new instance.
Class used to work with layer dependencies stored in a XML project or layer definition file...
QVector< QDomNode > sortedLayerNodes() const
Gets the layer nodes in an order where they can be loaded incrementally without dependency break...
void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context) override
Write group (tree) as XML element <layer-tree-group> and add it to the given parent element...
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context)
Sets state from DOM document.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application&#39;s plugin layer registry, used for managing plugin layer types.
void resolveReferences(const QgsProject *project, bool looseMatching=false) override
Calls resolveReferences() on child tree nodes.
DependencySorter(const QDomDocument &doc)
Constructor.
QString name() const override
Returns the layer&#39;s name.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
const QString & typeName
This class is a base class for nodes in a layer tree.
Reads and writes project states.
Definition: qgsproject.h:89
static QList< QgsMapLayer * > loadLayerDefinitionLayers(QDomDocument &document, QgsReadWriteContext &context)
Creates new layers from a layer definition document.
void insertChildNodes(int index, const QList< QgsLayerTreeNode *> &nodes)
Insert existing nodes at specified position.
bool hasMissingDependency() const
Whether some dependency is missing.
QgsMapLayer * layer() const
Returns the map layer associated with this node.
static bool exportLayerDefinition(QString path, const QList< QgsLayerTreeNode *> &selectedTreeNodes, QString &errorMessage)
Export the selected layer tree nodes to a QLR file.
void addChildNode(QgsLayerTreeNode *node)
Append an existing node.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
Resolves relative paths into absolute paths and vice versa.
Represents a vector layer which manages a vector based data sets.
bool writeLayerXml(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores state in DOM node.
QgsPluginLayer * createLayer(const QString &typeName, const QString &uri=QString())
Returns new layer if corresponding plugin has been found else returns a nullptr.
Layer tree node points to a map layer.