18 #include <QTextStream>
42 if ( !file.open( QIODevice::ReadOnly ) )
44 errorMessage = QStringLiteral(
"Can not open file" );
50 if ( !doc.setContent( &file, &message ) )
52 errorMessage = message;
56 const QFileInfo fileinfo( file );
57 QDir::setCurrent( fileinfo.absoluteDir().path() );
78 QVector<QDomNode> clonedSorted;
79 const auto constSortedLayerNodes = sortedLayerNodes;
80 for (
const QDomNode &node : constSortedLayerNodes )
82 clonedSorted << node.cloneNode();
84 QDomNode layersNode = doc.elementsByTagName( QStringLiteral(
"maplayers" ) ).at( 0 );
86 QDomNode childNode = layersNode.firstChild();
87 for (
int i = 0; ! childNode.isNull(); i++ )
89 layersNode.replaceChild( clonedSorted.at( i ), childNode );
90 childNode = childNode.nextSibling();
97 const QDomNodeList treeLayerNodes = doc.elementsByTagName( QStringLiteral(
"layer-tree-layer" ) );
98 for (
int i = 0; i < treeLayerNodes.length(); ++i )
100 const QDomNode treeLayerNode = treeLayerNodes.item( i );
101 QDomElement treeLayerElem = treeLayerNode.toElement();
102 const QString oldid = treeLayerElem.attribute( QStringLiteral(
"id" ) );
103 const QString layername = treeLayerElem.attribute( QStringLiteral(
"name" ) );
105 treeLayerElem.setAttribute( QStringLiteral(
"id" ), newid );
108 const QDomNodeList ids = doc.elementsByTagName( QStringLiteral(
"id" ) );
109 QDomNode idnode = ids.at( 0 );
110 for (
int j = 0; ! idnode.isNull() ; ++j )
112 idnode = ids.at( j );
113 const QDomElement idElem = idnode.toElement();
114 if ( idElem.text() == oldid )
116 idElem.firstChild().setNodeValue( newid );
121 const QDomNodeList vectorJoinNodes = doc.elementsByTagName( QStringLiteral(
"join" ) );
122 for (
int j = 0; j < vectorJoinNodes.size(); ++j )
124 const QDomNode joinNode = vectorJoinNodes.at( j );
125 const QDomElement joinElement = joinNode.toElement();
126 if ( joinElement.attribute( QStringLiteral(
"joinLayerId" ) ) == oldid )
128 joinNode.toElement().setAttribute( QStringLiteral(
"joinLayerId" ), newid );
133 const QDomNodeList dataDeps = doc.elementsByTagName( QStringLiteral(
"dataDependencies" ) );
134 for (
int i = 0; i < dataDeps.size(); i++ )
136 const QDomNodeList layers = dataDeps.at( i ).childNodes();
137 for (
int j = 0; j < layers.size(); j++ )
139 QDomElement elt = layers.at( j ).toElement();
140 if ( elt.attribute( QStringLiteral(
"id" ) ) == oldid )
142 elt.setAttribute( QStringLiteral(
"id" ), newid );
148 const QDomNodeList widgetConfig = doc.elementsByTagName( QStringLiteral(
"editWidget" ) );
149 for (
int i = 0; i < widgetConfig.size(); i++ )
151 const QDomNodeList config = widgetConfig.at( i ).childNodes();
152 for (
int j = 0; j < config.size(); j++ )
154 const QDomNodeList optMap = config.at( j ).childNodes();
155 for (
int z = 0; z < optMap.size(); z++ )
157 const QDomNodeList opts = optMap.at( z ).childNodes();
158 for (
int k = 0; k < opts.size(); k++ )
160 QDomElement opt = opts.at( k ).toElement();
161 if ( opt.attribute( QStringLiteral(
"value" ) ) == oldid )
163 opt.setAttribute( QStringLiteral(
"value" ), newid );
171 QDomElement layerTreeElem = doc.documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
172 bool loadInLegend =
true;
173 if ( !layerTreeElem.isNull() )
176 loadInLegend =
false;
179 const QList<QgsMapLayer *> layers = QgsLayerDefinition::loadLayerDefinitionLayersInternal( doc, context, errorMessage );
184 const auto constLayers = layers;
187 if (
QgsVectorLayer *vlayer = qobject_cast< QgsVectorLayer * >( layer ) )
189 vlayer->resolveReferences( project );
195 const QList<QgsLayerTreeNode *> nodes = root->
children();
214 if ( !file.open( QFile::WriteOnly | QFile::Truncate ) )
216 errorMessage = file.errorString();
231 const QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
235 QTextStream qlayerstream( &file );
236 doc.save( qlayerstream, 2 );
242 Q_UNUSED( errorMessage )
243 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
244 doc.appendChild( qgiselm );
245 const QList<QgsLayerTreeNode *> nodes = selectedTreeNodes;
247 const auto constNodes = nodes;
255 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
256 const QList<QgsLayerTreeLayer *> layers = root->
findLayers();
257 const auto constLayers = layers;
260 if ( ! layer->layer() )
262 QgsDebugMsgLevel( QStringLiteral(
"Not a valid map layer: skipping %1" ).arg( layer->name( ) ), 4 );
265 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
266 layer->layer()->writeLayerXml( layerelm, doc, context );
267 layerselm.appendChild( layerelm );
269 qgiselm.appendChild( layerselm );
275 QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
276 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
277 doc.appendChild( qgiselm );
278 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
279 const auto constLayers = layers;
282 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
283 layer->writeLayerXml( layerelm, doc, context );
284 layerselm.appendChild( layerelm );
286 qgiselm.appendChild( layerselm );
292 QString errorMessage;
293 return loadLayerDefinitionLayersInternal( document, context, errorMessage );
296 QList<QgsMapLayer *> QgsLayerDefinition::loadLayerDefinitionLayersInternal( QDomDocument &document,
QgsReadWriteContext &context, QString &errorMessage )
298 QList<QgsMapLayer *> layers;
299 QDomElement layerElem = document.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
301 if ( layerElem.isNull() )
303 layerElem = document.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
306 while ( ! layerElem.isNull() )
308 const QString type = layerElem.attribute( QStringLiteral(
"type" ) );
327 const QString
typeName = layerElem.attribute( QStringLiteral(
"name" ) );
358 errorMessage = QObject::tr(
"Unsupported layer type: %1" ).arg( type );
360 layerElem = layerElem.nextSiblingElement( QStringLiteral(
"maplayer" ) );
367 QFile file( qlrfile );
368 if ( !file.open( QIODevice::ReadOnly ) )
370 QgsDebugMsg( QStringLiteral(
"Can't open file" ) );
371 return QList<QgsMapLayer *>();
375 if ( !doc.setContent( &file ) )
377 QgsDebugMsg( QStringLiteral(
"Can't set content" ) );
378 return QList<QgsMapLayer *>();
387 void QgsLayerDefinition::DependencySorter::init(
const QDomDocument &doc )
390 QMap< QString, QVector< QString > > dependencies;
391 QStringList sortedLayers;
392 QList< QPair<QString, QDomNode> > layersToSort;
393 QStringList layerIds;
395 QDomElement layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
397 if ( layerElem.isNull() )
399 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
402 if ( layerElem.isNull() )
404 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayer" ) );
407 const QDomElement &firstElement { layerElem };
409 QVector<QString> deps;
410 while ( !layerElem.isNull() )
414 const QString
id = layerElem.namedItem( QStringLiteral(
"id" ) ).toElement().text();
418 const QDomElement layerDependenciesElem = layerElem.firstChildElement( QStringLiteral(
"layerDependencies" ) );
419 if ( !layerDependenciesElem.isNull() )
421 const QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( QStringLiteral(
"layer" ) );
422 for (
int j = 0; j < dependencyList.size(); ++j )
424 const QDomElement depElem = dependencyList.at( j ).toElement();
425 deps << depElem.attribute( QStringLiteral(
"id" ) );
428 dependencies[id] = deps;
433 mSortedLayerNodes << layerElem;
434 mSortedLayerIds << id;
438 layersToSort << qMakePair(
id, layerElem );
440 layerElem = layerElem.nextSiblingElement( );
444 const auto constDependencies = dependencies;
445 for (
const QVector< QString > &ids : constDependencies )
447 const auto constIds = ids;
448 for (
const QString &depId : constIds )
450 if ( !dependencies.contains( depId ) )
453 mHasMissingDependency =
true;
454 layerElem = firstElement;
455 while ( ! layerElem.isNull() )
457 mSortedLayerNodes << layerElem;
458 layerElem = layerElem.nextSiblingElement( );
460 mSortedLayerIds = layerIds;
470 while ( !layersToSort.empty() && !mHasCycle )
472 QList< QPair<QString, QDomNode> >::iterator it = layersToSort.begin();
473 while ( it != layersToSort.end() )
475 const QString idToSort = it->first;
476 const QDomNode node = it->second;
478 bool resolved =
true;
479 const auto deps { dependencies.value( idToSort ) };
480 for (
const QString &dep : deps )
482 if ( !sortedLayers.contains( dep ) )
490 sortedLayers << idToSort;
491 mSortedLayerNodes << node;
492 mSortedLayerIds << idToSort;
493 it = layersToSort.erase( it );
506 , mHasMissingDependency( false )
513 , mHasMissingDependency( false )
515 QString qgsProjectFile = fileName;
517 if ( fileName.endsWith( QLatin1String(
".qgz" ), Qt::CaseInsensitive ) )
519 archive.
unzip( fileName );
524 QFile pFile( qgsProjectFile );
525 ( void )pFile.open( QIODevice::ReadOnly );
526 ( void )doc.setContent( &pFile );
FilePathType
File path types.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
static QString ensureFileNameHasExtension(const QString &fileName, const QStringList &extensions)
Ensures that a fileName ends with an extension from the provided list of extensions.
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.
bool hasMissingDependency() const
Whether some dependency is missing.
DependencySorter(const QDomDocument &doc)
Constructor.
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...
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...
static QList< QgsMapLayer * > loadLayerDefinitionLayers(QDomDocument &document, QgsReadWriteContext &context)
Creates new layers from a layer definition document.
static bool exportLayerDefinition(const QString &path, const QList< QgsLayerTreeNode * > &selectedTreeNodes, QString &errorMessage)
Exports the selected layer tree nodes to a QLR file.
Layer tree group node serves as a container for layers and further groups.
void resolveReferences(const QgsProject *project, bool looseMatching=false) override
Calls resolveReferences() on child tree nodes.
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.
void addChildNode(QgsLayerTreeNode *node)
Append an existing node.
void insertChildNodes(int index, const QList< QgsLayerTreeNode * > &nodes)
Insert existing nodes at specified position.
void readChildrenFromXml(QDomElement &element, const QgsReadWriteContext &context)
Read children from XML and append them to the group.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
Layer tree node points to a map layer.
This class is a base class for nodes in a layer tree.
QList< QgsLayerTreeNode * > abandonChildren()
Removes the childrens, disconnect all the forwarded and external signals and sets their parent to nul...
virtual QgsLayerTreeNode * clone() const =0
Create a copy of the node. Returns new instance.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
static QgsMapLayerType typeFromString(const QString &string, bool &ok)
Returns the map layer type corresponding a string value.
Base class for all map layer types.
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags=QgsMapLayer::ReadFlags())
Sets state from DOM document.
static QString generateId(const QString &layerName)
Generates an unique identifier for this layer, the generate ID is prefixed by layerName.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
Resolves relative paths into absolute paths and vice versa.
QgsPluginLayer * createLayer(const QString &typeName, const QString &uri=QString())
Returns new layer if corresponding plugin has been found else returns nullptr.
Represents a map layer supporting display of point clouds.
Class allowing to manage the zip/unzip actions on project file.
QString projectFile() const
Returns the current .qgs project file or an empty string if there's none.
bool unzip(const QString &zipFilename) override
Clear the current content of this archive and unzip.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QList< QgsMapLayer * > addMapLayers(const QList< QgsMapLayer * > &mapLayers, bool addToLegend=true, bool takeOwnership=true)
Add a list of layers to the map of loaded layers.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Represents a raster layer.
The class is used as a container of context for various read/write operations on other objects.
void setProjectTranslator(QgsProjectTranslator *projectTranslator)
Sets the project translator.
void setPathResolver(const QgsPathResolver &resolver)
Sets up path resolver for conversion between relative and absolute paths.
Represents a vector layer which manages a vector based data sets.
Implements a map layer that is dedicated to rendering of vector tiles.
QgsMapLayerType
Types of layers that can be added to a map.
@ PointCloudLayer
Added in 3.18.
@ VectorTileLayer
Added in 3.14.
@ AnnotationLayer
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
#define QgsDebugMsgLevel(str, level)