44 if ( !file.open( QIODevice::ReadOnly ) )
46 errorMessage = QStringLiteral(
"Can not open file" );
52 if ( !doc.setContent( &file, &message ) )
54 errorMessage = message;
58 const QFileInfo fileinfo( file );
59 QDir::setCurrent( fileinfo.absoluteDir().path() );
80 QVector<QDomNode> clonedSorted;
81 const auto constSortedLayerNodes = sortedLayerNodes;
82 for (
const QDomNode &node : constSortedLayerNodes )
84 clonedSorted << node.cloneNode();
86 QDomNode layersNode = doc.elementsByTagName( QStringLiteral(
"maplayers" ) ).at( 0 );
88 QDomNode childNode = layersNode.firstChild();
89 for (
int i = 0; ! childNode.isNull(); i++ )
91 layersNode.replaceChild( clonedSorted.at( i ), childNode );
92 childNode = childNode.nextSibling();
99 const QDomNodeList treeLayerNodes = doc.elementsByTagName( QStringLiteral(
"layer-tree-layer" ) );
100 for (
int i = 0; i < treeLayerNodes.length(); ++i )
102 const QDomNode treeLayerNode = treeLayerNodes.item( i );
103 QDomElement treeLayerElem = treeLayerNode.toElement();
104 const QString oldid = treeLayerElem.attribute( QStringLiteral(
"id" ) );
105 const QString layername = treeLayerElem.attribute( QStringLiteral(
"name" ) );
107 treeLayerElem.setAttribute( QStringLiteral(
"id" ), newid );
110 const QDomNodeList ids = doc.elementsByTagName( QStringLiteral(
"id" ) );
111 QDomNode idnode = ids.at( 0 );
112 for (
int j = 0; ! idnode.isNull() ; ++j )
114 idnode = ids.at( j );
115 const QDomElement idElem = idnode.toElement();
116 if ( idElem.text() == oldid )
118 idElem.firstChild().setNodeValue( newid );
123 const QDomNodeList vectorJoinNodes = doc.elementsByTagName( QStringLiteral(
"join" ) );
124 for (
int j = 0; j < vectorJoinNodes.size(); ++j )
126 const QDomNode joinNode = vectorJoinNodes.at( j );
127 const QDomElement joinElement = joinNode.toElement();
128 if ( joinElement.attribute( QStringLiteral(
"joinLayerId" ) ) == oldid )
130 joinNode.toElement().setAttribute( QStringLiteral(
"joinLayerId" ), newid );
135 const QDomNodeList dataDeps = doc.elementsByTagName( QStringLiteral(
"dataDependencies" ) );
136 for (
int i = 0; i < dataDeps.size(); i++ )
138 const QDomNodeList layers = dataDeps.at( i ).childNodes();
139 for (
int j = 0; j < layers.size(); j++ )
141 QDomElement elt = layers.at( j ).toElement();
142 if ( elt.attribute( QStringLiteral(
"id" ) ) == oldid )
144 elt.setAttribute( QStringLiteral(
"id" ), newid );
150 const QDomNodeList widgetConfig = doc.elementsByTagName( QStringLiteral(
"editWidget" ) );
151 for (
int i = 0; i < widgetConfig.size(); i++ )
153 const QDomNodeList config = widgetConfig.at( i ).childNodes();
154 for (
int j = 0; j < config.size(); j++ )
156 const QDomNodeList optMap = config.at( j ).childNodes();
157 for (
int z = 0; z < optMap.size(); z++ )
159 const QDomNodeList opts = optMap.at( z ).childNodes();
160 for (
int k = 0; k < opts.size(); k++ )
162 QDomElement opt = opts.at( k ).toElement();
163 if ( opt.attribute( QStringLiteral(
"value" ) ) == oldid )
165 opt.setAttribute( QStringLiteral(
"value" ), newid );
173 QDomElement layerTreeElem = doc.documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
174 bool loadInLegend =
true;
175 if ( !layerTreeElem.isNull() )
178 loadInLegend =
false;
181 const QList<QgsMapLayer *> layers = QgsLayerDefinition::loadLayerDefinitionLayersInternal( doc, context, errorMessage );
186 const auto constLayers = layers;
189 layer->resolveReferences( project );
194 const QList<QgsLayerTreeNode *> nodes = root->
children();
213 if ( !file.open( QFile::WriteOnly | QFile::Truncate ) )
215 errorMessage = file.errorString();
230 const QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
234 QTextStream qlayerstream( &file );
235 doc.save( qlayerstream, 2 );
241 Q_UNUSED( errorMessage )
242 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
243 doc.appendChild( qgiselm );
244 const QList<QgsLayerTreeNode *> nodes = selectedTreeNodes;
246 const auto constNodes = nodes;
254 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
255 const QList<QgsLayerTreeLayer *> layers = root->
findLayers();
256 const auto constLayers = layers;
259 if ( ! layer->layer() )
261 QgsDebugMsgLevel( QStringLiteral(
"Not a valid map layer: skipping %1" ).arg( layer->name( ) ), 4 );
264 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
265 layer->layer()->writeLayerXml( layerelm, doc, context );
266 layerselm.appendChild( layerelm );
268 qgiselm.appendChild( layerselm );
274 QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
275 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
276 doc.appendChild( qgiselm );
277 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
278 const auto constLayers = layers;
281 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
282 layer->writeLayerXml( layerelm, doc, context );
283 layerselm.appendChild( layerelm );
285 qgiselm.appendChild( layerselm );
291 QString errorMessage;
292 return loadLayerDefinitionLayersInternal( document, context, errorMessage );
295QList<QgsMapLayer *> QgsLayerDefinition::loadLayerDefinitionLayersInternal( QDomDocument &document,
QgsReadWriteContext &context, QString &errorMessage )
297 QList<QgsMapLayer *> layers;
298 QDomElement layerElem = document.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
300 if ( layerElem.isNull() )
302 layerElem = document.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
305 while ( ! layerElem.isNull() )
307 const QString type = layerElem.attribute( QStringLiteral(
"type" ) );
326 const QString
typeName = layerElem.attribute( QStringLiteral(
"name" ) );
365 errorMessage = QObject::tr(
"Unsupported layer type: %1" ).arg( type );
367 layerElem = layerElem.nextSiblingElement( QStringLiteral(
"maplayer" ) );
374 QFile file( qlrfile );
375 if ( !file.open( QIODevice::ReadOnly ) )
378 return QList<QgsMapLayer *>();
382 if ( !doc.setContent( &file ) )
385 return QList<QgsMapLayer *>();
394void QgsLayerDefinition::DependencySorter::init(
const QDomDocument &doc )
397 QMap< QString, QVector< QString > > dependencies;
398 QStringList sortedLayers;
399 QList< QPair<QString, QDomNode> > layersToSort;
400 QStringList layerIds;
402 QDomElement layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
404 if ( layerElem.isNull() )
406 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
409 if ( layerElem.isNull() )
411 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayer" ) );
414 const QDomElement &firstElement { layerElem };
416 QVector<QString> deps;
417 while ( !layerElem.isNull() )
421 const QString
id = layerElem.namedItem( QStringLiteral(
"id" ) ).toElement().text();
425 const QDomElement layerDependenciesElem = layerElem.firstChildElement( QStringLiteral(
"layerDependencies" ) );
426 if ( !layerDependenciesElem.isNull() )
428 const QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( QStringLiteral(
"layer" ) );
429 for (
int j = 0; j < dependencyList.size(); ++j )
431 const QDomElement depElem = dependencyList.at( j ).toElement();
432 deps << depElem.attribute( QStringLiteral(
"id" ) );
435 dependencies[id] = deps;
440 mSortedLayerNodes << layerElem;
441 mSortedLayerIds << id;
445 layersToSort << qMakePair(
id, layerElem );
446 mDependentLayerIds.insert(
id );
448 layerElem = layerElem.nextSiblingElement( );
452 const auto constDependencies = dependencies;
453 for (
const QVector< QString > &ids : constDependencies )
455 const auto constIds = ids;
456 for (
const QString &depId : constIds )
458 if ( !dependencies.contains( depId ) )
461 mHasMissingDependency =
true;
462 layerElem = firstElement;
463 while ( ! layerElem.isNull() )
465 mSortedLayerNodes << layerElem;
466 layerElem = layerElem.nextSiblingElement( );
468 mSortedLayerIds = layerIds;
478 while ( !layersToSort.empty() && !mHasCycle )
480 QList< QPair<QString, QDomNode> >::iterator it = layersToSort.begin();
481 while ( it != layersToSort.end() )
483 const QString idToSort = it->first;
484 const QDomNode node = it->second;
486 bool resolved =
true;
487 const auto deps { dependencies.value( idToSort ) };
488 for (
const QString &dep : deps )
490 if ( !sortedLayers.contains( dep ) )
498 sortedLayers << idToSort;
499 mSortedLayerNodes << node;
500 mSortedLayerIds << idToSort;
501 it = layersToSort.erase( it );
514 , mHasMissingDependency( false )
521 , mHasMissingDependency( false )
523 QString qgsProjectFile = fileName;
525 if ( fileName.endsWith( QLatin1String(
".qgz" ), Qt::CaseInsensitive ) )
527 archive.
unzip( fileName );
532 QFile pFile( qgsProjectFile );
533 ( void )pFile.open( QIODevice::ReadOnly );
534 ( void )doc.setContent( &pFile );
540 return mDependentLayerIds.contains( layerId );
FilePathType
File path types.
LayerType
Types of layers that can be added to a map.
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
Contains information about the context in which a coordinate transform is executed.
static QString ensureFileNameHasExtension(const QString &fileName, const QStringList &extensions)
Ensures that a fileName ends with an extension from the provided list of extensions.
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
Class used to work with layer dependencies stored in a XML project or layer definition file.
bool hasMissingDependency() const
Whether some dependency is missing.
bool isLayerDependent(const QString &layerId) const
Returns whether the layer associated with thelayerId is dependent from another layer.
DependencySorter(const QDomDocument &doc)
Constructor.
QVector< QDomNode > sortedLayerNodes() const
Gets the layer nodes in an order where they can be loaded incrementally without dependency break.
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...
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
virtual QgsLayerTreeNode * clone() const =0
Create a copy of the node. Returns new instance.
static Qgis::LayerType typeFromString(const QString &string, bool &ok)
Returns the map layer type corresponding a string value.
Base class for all map layer types.
static QString generateId(const QString &layerName)
Generates an unique identifier for this layer, the generate ID is prefixed by layerName.
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags=QgsMapLayer::ReadFlags(), QgsDataProvider *preloadedProvider=nullptr)
Sets state from DOM document.
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 map layer supporting display of tiled scene objects.
Represents a vector layer which manages a vector based data sets.
Implements a map layer that is dedicated to rendering of vector tiles.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
Setting options for loading group layers.