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