54 #include <QApplication> 58 #include <QTextStream> 59 #include <QTemporaryFile> 64 #include <sys/utime.h> 82 QStringList keyTokens = QStringList( scope );
83 keyTokens += key.split(
'/', QString::SkipEmptyParts );
86 keyTokens.push_front( QStringLiteral(
"properties" ) );
89 for (
int i = 0; i < keyTokens.size(); ++i )
91 QString keyToken = keyTokens.at( i );
95 QString nameCharRegexp = QStringLiteral(
"[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD\\-\\.0-9\\xB7\\x0300-\\x036F\\x203F-\\x2040]" );
96 QString nameStartCharRegexp = QStringLiteral(
"^[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD]" );
98 if ( keyToken.contains( QRegExp( nameCharRegexp ) ) || keyToken.contains( QRegExp( nameStartCharRegexp ) ) )
101 QString errorString = QObject::tr(
"Entry token invalid : '%1'. The token will not be saved to file." ).arg( keyToken );
131 while ( !keySequence.isEmpty() )
135 if ( keySequence.first() == currentProperty->
name() )
138 keySequence.pop_front();
140 if ( 1 == keySequence.count() )
143 return currentProperty->
find( keySequence.front() );
145 else if ( keySequence.isEmpty() )
150 return currentProperty;
152 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
154 if ( nextProperty->
isKey() )
158 else if ( nextProperty->
isValue() && 1 == keySequence.count() )
164 return currentProperty;
201 const QVariant &value )
210 while ( ! keySequence.isEmpty() )
214 if ( keySequence.first() == currentProperty->
name() )
217 keySequence.pop_front();
221 if ( 1 == keySequence.count() )
223 currentProperty->
setValue( keySequence.front(), value );
224 return currentProperty;
228 else if ( keySequence.isEmpty() )
232 return currentProperty;
234 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
238 if ( currentProperty )
249 if ( ( newPropertyKey = currentProperty->
addKey( keySequence.first() ) ) )
251 currentProperty = newPropertyKey;
278 while ( ! keySequence.isEmpty() )
282 if ( keySequence.first() == currentProperty->
name() )
285 keySequence.pop_front();
289 if ( 1 == keySequence.count() )
291 currentProperty->
removeKey( keySequence.front() );
296 else if ( keySequence.isEmpty() )
298 previousQgsPropertyKey->
removeKey( currentProperty->
name() );
300 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
302 previousQgsPropertyKey = currentProperty;
305 if ( currentProperty )
332 , mSnappingConfig( this )
341 mProperties.
setName( QStringLiteral(
"properties" ) );
372 delete mBadLayerHandler;
373 delete mRelationManager;
374 delete mLayerTreeRegistryBridge;
376 if (
this == sProject )
394 if ( title == mTitle )
421 if ( name == mFile.fileName() )
426 mFile.setFileName( name );
430 if ( newHomePath != oldHomePath )
438 return mFile.fileName();
443 return QFileInfo( mFile );
454 writeEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectionsEnabled" ), crs.
isValid() ? 1 : 0 );
461 if ( !
crs().isValid() )
464 return readEntry( QStringLiteral(
"Measure" ), QStringLiteral(
"/Ellipsoid" ),
GEO_NONE );
469 writeEntry( QStringLiteral(
"Measure" ), QStringLiteral(
"/Ellipsoid" ), ellipsoid );
476 return mTransformContext;
481 mTransformContext = context;
487 mFile.setFileName( QString() );
490 mAutoTransaction =
false;
491 mEvaluateDefaultValues =
false;
493 mTrustLayerMetadata =
false;
494 mCustomVariables.clear();
500 mEmbeddedLayers.clear();
501 mRelationManager->
clear();
502 mAnnotationManager->clear();
503 mLayoutManager->clear();
504 mSnappingConfig.
reset();
510 mLabelingEngineSettings->clear();
519 writeEntry( QStringLiteral(
"PositionPrecision" ), QStringLiteral(
"/Automatic" ),
true );
520 writeEntry( QStringLiteral(
"PositionPrecision" ), QStringLiteral(
"/DecimalPlaces" ), 2 );
521 writeEntry( QStringLiteral(
"Paths" ), QStringLiteral(
"/Absolute" ),
false );
525 writeEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/DistanceUnits" ), s.
value( QStringLiteral(
"/qgis/measure/displayunits" ) ).toString() );
526 writeEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/AreaUnits" ), s.
value( QStringLiteral(
"/qgis/measure/areaunits" ) ).toString() );
538 topQgsPropertyKey.
dump();
574 QDomElement propertiesElem = doc.documentElement().firstChildElement( QStringLiteral(
"properties" ) );
576 if ( propertiesElem.isNull() )
581 QDomNodeList scopes = propertiesElem.childNodes();
583 if ( scopes.count() < 1 )
585 QgsDebugMsg(
"empty ``properties'' XML tag ... bailing" );
589 if ( ! project_properties.
readXml( propertiesElem ) )
591 QgsDebugMsg(
"Project_properties.readXml() failed" );
600 static void _getTitle(
const QDomDocument &doc, QString &
title )
602 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"title" ) );
612 QDomNode titleNode = nl.item( 0 );
614 if ( !titleNode.hasChildNodes() )
620 QDomNode titleTextNode = titleNode.firstChild();
622 if ( !titleTextNode.isText() )
628 QDomText titleText = titleTextNode.toText();
630 title = titleText.data();
636 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
640 QgsDebugMsg(
" unable to find qgis element in project file" );
644 QDomNode qgisNode = nl.item( 0 );
646 QDomElement qgisElement = qgisNode.toElement();
647 QgsProjectVersion projectVersion( qgisElement.attribute( QStringLiteral(
"version" ) ) );
648 return projectVersion;
654 return mSnappingConfig;
659 if ( mSnappingConfig == snappingConfig )
667 bool QgsProject::_getMapLayers(
const QDomDocument &doc, QList<QDomNode> &brokenNodes )
672 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"maplayer" ) );
676 if ( 0 == nl.count() )
686 bool returnStatus =
true;
692 if ( depSorter.hasCycle() || depSorter.hasMissingDependency() )
695 QVector<QDomNode> sortedLayerNodes = depSorter.sortedLayerNodes();
698 Q_FOREACH (
const QDomNode &node, sortedLayerNodes )
700 QDomElement element = node.toElement();
702 QString name = node.namedItem( QStringLiteral(
"layername" ) ).toElement().text();
703 if ( !name.isNull() )
704 emit
loadingLayer( tr(
"Loading layer %1" ).arg( name ) );
706 if ( element.attribute( QStringLiteral(
"embedded" ) ) == QLatin1String(
"1" ) )
708 createEmbeddedLayer( element.attribute( QStringLiteral(
"id" ) ),
readPath( element.attribute( QStringLiteral(
"project" ) ) ), brokenNodes );
715 if ( !addLayer( element, brokenNodes, context ) )
717 returnStatus =
false;
727 bool QgsProject::addLayer(
const QDomElement &layerElem, QList<QDomNode> &brokenNodes,
const QgsReadWriteContext &context )
729 QString type = layerElem.attribute( QStringLiteral(
"type" ) );
733 if ( type == QLatin1String(
"vector" ) )
738 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( mapLayer ) )
743 else if ( type == QLatin1String(
"raster" ) )
747 else if ( type == QLatin1String(
"plugin" ) )
749 QString typeName = layerElem.attribute( QStringLiteral(
"name" ) );
760 Q_CHECK_PTR( mapLayer );
767 QList<QgsMapLayer *> myLayers;
777 QgsDebugMsg(
"Unable to load " + type +
" layer" );
778 brokenNodes.push_back( layerElem );
785 mFile.setFileName( filename );
792 QString filename = mFile.fileName();
797 rc = unzip( mFile.fileName() );
802 rc = readProjectFile( mFile.fileName() );
805 mFile.setFileName( filename );
809 bool QgsProject::readProjectFile(
const QString &filename )
811 QFile projectFile( filename );
814 std::unique_ptr<QDomDocument> doc(
new QDomDocument( QStringLiteral(
"qgis" ) ) );
816 if ( !projectFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
820 setError( tr(
"Unable to open %1" ).arg( projectFile.fileName() ) );
829 if ( !doc->setContent( &projectFile, &errorMsg, &line, &column ) )
833 QMessageBox::critical( 0, tr(
"Read Project File" ),
834 tr(
"%1 at line %2 column %3" ).arg( errorMsg ).arg( line ).arg( column ) );
837 QString errorString = tr(
"Project file read error in file %1: %2 at line %3 column %4" )
838 .arg( projectFile.fileName(), errorMsg ).arg( line ).arg( column );
844 setError( tr(
"%1 for file %2" ).arg( errorString, projectFile.fileName() ) );
852 QgsDebugMsg(
"Opened document " + projectFile.fileName() );
859 if ( thisVersion > fileVersion )
862 "version of qgis (saved in " + fileVersion.
text() +
864 "). Problems may occur." );
870 QgsDebugMsg(
"Emitting oldProjectVersionWarning(oldVersion)." );
872 projectFile.updateRevision( thisVersion );
876 QString
fileName = mFile.fileName();
877 std::unique_ptr<QgsAuxiliaryStorage> aStorage = std::move( mAuxiliaryStorage );
879 mAuxiliaryStorage = std::move( aStorage );
880 mFile.setFileName( fileName );
887 dump_( mProperties );
890 _getTitle( *doc, mTitle );
897 if (
readNumEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectionsEnabled" ), 0 ) )
900 QDomNode srsNode = doc->documentElement().namedItem( QStringLiteral(
"projectCrs" ) );
901 if ( !srsNode.isNull() )
908 QString projCrsString =
readEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectCRSProj4String" ) );
909 long currentCRS =
readNumEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectCRSID" ), -1 );
912 if ( currentCRS >= 0 )
918 if ( !projCrsString.isEmpty() && ( !projectCrs.
isValid() || projectCrs.
toProj4() != projCrsString ) )
932 QStringList datumErrors;
933 if ( !mTransformContext.
readXml( doc->documentElement(), context, datumErrors ) )
939 QDomNodeList nl = doc->elementsByTagName( QStringLiteral(
"autotransaction" ) );
942 QDomElement transactionElement = nl.at( 0 ).toElement();
943 if ( transactionElement.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
944 mAutoTransaction =
true;
947 nl = doc->elementsByTagName( QStringLiteral(
"evaluateDefaultValues" ) );
950 QDomElement evaluateDefaultValuesElement = nl.at( 0 ).toElement();
951 if ( evaluateDefaultValuesElement.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
952 mEvaluateDefaultValues =
true;
955 nl = doc->elementsByTagName( QStringLiteral(
"trust" ) );
958 QDomElement trustElement = nl.at( 0 ).toElement();
959 if ( trustElement.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
960 mTrustLayerMetadata =
true;
967 QDomElement layerTreeElem = doc->documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
968 if ( !layerTreeElem.isNull() )
977 mLayerTreeRegistryBridge->
setEnabled(
false );
980 QList<QDomNode> brokenNodes;
981 bool clean = _getMapLayers( *doc, brokenNodes );
986 QgsDebugMsg(
"Unable to get map layers from project file." );
988 if ( !brokenNodes.isEmpty() )
990 QgsDebugMsg(
"there are " + QString::number( brokenNodes.size() ) +
" broken layers" );
1000 QMap<QString, QgsMapLayer *>
layers = mLayerStore->mapLayers();
1001 for ( QMap<QString, QgsMapLayer *>::iterator it = layers.begin(); it != layers.end(); it++ )
1003 it.value()->resolveReferences(
this );
1006 mLayerTreeRegistryBridge->
setEnabled(
true );
1009 loadEmbeddedNodes( mRootGroup );
1015 if ( !layerTreeElem.isNull() )
1021 QDomElement layerTreeCanvasElem = doc->documentElement().firstChildElement( QStringLiteral(
"layer-tree-canvas" ) );
1022 if ( !layerTreeCanvasElem.isNull( ) )
1034 mMapThemeCollection->readXml( *doc );
1036 mLabelingEngineSettings->readSettingsFromProject(
this );
1039 mAnnotationManager->readXml( doc->documentElement(), context );
1040 mLayoutManager->readXml( doc->documentElement(), *doc );
1043 QMap<QString, QgsMapLayer *> existingMaps =
mapLayers();
1044 for ( QMap<QString, QgsMapLayer *>::iterator it = existingMaps.begin(); it != existingMaps.end(); it++ )
1046 it.value()->setDependencies( it.value()->dependencies() );
1052 QStringList variableNames =
readListEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableNames" ) );
1053 QStringList variableValues =
readListEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableValues" ) );
1055 mCustomVariables.clear();
1056 if ( variableNames.length() == variableValues.length() )
1058 for (
int i = 0; i < variableNames.length(); ++i )
1060 mCustomVariables.insert( variableNames.at( i ), variableValues.at( i ) );
1065 QgsMessageLog::logMessage( tr(
"Project Variables Invalid" ), tr(
"The project contains invalid variable settings." ) );
1093 if ( childGroup->
customProperty( QStringLiteral(
"embedded" ) ).toInt() )
1096 QString projectPath =
readPath( childGroup->
customProperty( QStringLiteral(
"embedded_project" ) ).toString() );
1097 childGroup->
setCustomProperty( QStringLiteral(
"embedded_project" ), projectPath );
1101 QList<QgsLayerTreeNode *> clonedChildren;
1103 clonedChildren << newGroupChild->
clone();
1111 loadEmbeddedNodes( childGroup );
1116 if ( child->
customProperty( QStringLiteral(
"embedded" ) ).toInt() )
1118 QList<QDomNode> brokenNodes;
1128 return mCustomVariables;
1133 if ( variables == mCustomVariables )
1137 QStringList variableNames;
1138 QStringList variableValues;
1140 QVariantMap::const_iterator it = variables.constBegin();
1141 for ( ; it != variables.constEnd(); ++it )
1143 variableNames << it.key();
1144 variableValues << it.value().toString();
1147 writeEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableNames" ), variableNames );
1148 writeEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableValues" ), variableValues );
1150 mCustomVariables = variables;
1157 *mLabelingEngineSettings = settings;
1163 return *mLabelingEngineSettings;
1168 return mLayerStore.get();
1173 return mLayerStore.get();
1178 QList<QgsVectorLayer *>
layers;
1179 QStringList layerIds =
readListEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/AvoidIntersectionsList" ), QStringList() );
1180 Q_FOREACH (
const QString &layerId, layerIds )
1192 list << layer->
id();
1193 writeEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/AvoidIntersectionsList" ), list );
1207 void QgsProject::onMapLayersAdded(
const QList<QgsMapLayer *> &
layers )
1209 QMap<QString, QgsMapLayer *> existingMaps =
mapLayers();
1211 bool tgChanged =
false;
1230 mTransactionGroups.insert( qMakePair( key, connString ), tg );
1245 for ( QMap<QString, QgsMapLayer *>::iterator it = existingMaps.begin(); it != existingMaps.end(); it++ )
1247 QSet<QgsMapLayerDependency> deps = it.value()->dependencies();
1248 if ( deps.contains( layer->
id() ) )
1251 it.value()->setDependencies( deps );
1256 if ( mSnappingConfig.
addLayers( layers ) )
1260 void QgsProject::onMapLayersRemoved(
const QList<QgsMapLayer *> &
layers )
1266 void QgsProject::cleanTransactionGroups(
bool force )
1268 bool changed =
false;
1269 for ( QMap< QPair< QString, QString>,
QgsTransactionGroup *>::Iterator tg = mTransactionGroups.begin(); tg != mTransactionGroups.end(); )
1271 if ( tg.value()->isEmpty() || force )
1274 tg = mTransactionGroups.erase( tg );
1290 QList<QDomNode> brokenNodes;
1291 if ( addLayer( layerNode.toElement(), brokenNodes, context ) )
1295 QVector<QgsVectorLayer *> vectorLayers = layers<QgsVectorLayer *>();
1309 mFile.setFileName( filename );
1318 return zip( mFile.fileName() );
1324 const bool asOk = saveAuxiliaryStorage();
1325 const bool writeOk = writeProjectFile( mFile.fileName() );
1328 if ( !asOk && writeOk )
1329 setError( tr(
"Unable to save auxiliary storage" ) );
1331 return asOk && writeOk;
1335 bool QgsProject::writeProjectFile(
const QString &filename )
1337 QFile projectFile( filename );
1343 QFileInfo myFileInfo( projectFile );
1344 if ( myFileInfo.exists() && !myFileInfo.isWritable() )
1346 setError( tr(
"%1 is not writable. Please adjust permissions (if possible) and try again." )
1347 .arg( projectFile.fileName() ) );
1354 QDomImplementation DomImplementation;
1355 DomImplementation.setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
1357 QDomDocumentType documentType =
1358 DomImplementation.createDocumentType( QStringLiteral(
"qgis" ), QStringLiteral(
"http://mrcc.com/qgis.dtd" ),
1359 QStringLiteral(
"SYSTEM" ) );
1360 std::unique_ptr<QDomDocument> doc(
new QDomDocument( documentType ) );
1362 QDomElement qgisNode = doc->createElement( QStringLiteral(
"qgis" ) );
1363 qgisNode.setAttribute( QStringLiteral(
"projectname" ),
title() );
1364 qgisNode.setAttribute( QStringLiteral(
"version" ), QStringLiteral(
"%1" ).arg(
Qgis::QGIS_VERSION ) );
1366 doc->appendChild( qgisNode );
1369 QDomElement titleNode = doc->createElement( QStringLiteral(
"title" ) );
1370 qgisNode.appendChild( titleNode );
1372 QDomElement transactionNode = doc->createElement( QStringLiteral(
"autotransaction" ) );
1373 transactionNode.setAttribute( QStringLiteral(
"active" ), mAutoTransaction ?
"1" :
"0" );
1374 qgisNode.appendChild( transactionNode );
1376 QDomElement evaluateDefaultValuesNode = doc->createElement( QStringLiteral(
"evaluateDefaultValues" ) );
1377 evaluateDefaultValuesNode.setAttribute( QStringLiteral(
"active" ), mEvaluateDefaultValues ?
"1" :
"0" );
1378 qgisNode.appendChild( evaluateDefaultValuesNode );
1380 QDomElement trustNode = doc->createElement( QStringLiteral(
"trust" ) );
1381 trustNode.setAttribute( QStringLiteral(
"active" ), mTrustLayerMetadata ?
"1" :
"0" );
1382 qgisNode.appendChild( trustNode );
1384 QDomText titleText = doc->createTextNode(
title() );
1385 titleNode.appendChild( titleText );
1388 QDomElement srsNode = doc->createElement( QStringLiteral(
"projectCrs" ) );
1390 qgisNode.appendChild( srsNode );
1397 clonedRoot->
writeXml( qgisNode, context );
1410 QDomElement projectLayersNode = doc->createElement( QStringLiteral(
"projectlayers" ) );
1412 QMap<QString, QgsMapLayer *>::ConstIterator li = layers.constBegin();
1413 while ( li != layers.end() )
1419 QHash< QString, QPair< QString, bool> >::const_iterator emIt = mEmbeddedLayers.constFind( ml->
id() );
1420 if ( emIt == mEmbeddedLayers.constEnd() )
1423 QDomElement maplayerElem = doc->createElement( QStringLiteral(
"maplayer" ) );
1429 projectLayersNode.appendChild( maplayerElem );
1435 if ( emIt.value().second )
1437 QDomElement mapLayerElem = doc->createElement( QStringLiteral(
"maplayer" ) );
1438 mapLayerElem.setAttribute( QStringLiteral(
"embedded" ), 1 );
1439 mapLayerElem.setAttribute( QStringLiteral(
"project" ),
writePath( emIt.value().first ) );
1440 mapLayerElem.setAttribute( QStringLiteral(
"id" ), ml->
id() );
1441 projectLayersNode.appendChild( mapLayerElem );
1448 qgisNode.appendChild( projectLayersNode );
1450 QDomElement layerOrderNode = doc->createElement( QStringLiteral(
"layerorder" ) );
1453 QDomElement mapLayerElem = doc->createElement( QStringLiteral(
"layer" ) );
1454 mapLayerElem.setAttribute( QStringLiteral(
"id" ), layer->
id() );
1455 layerOrderNode.appendChild( mapLayerElem );
1457 qgisNode.appendChild( layerOrderNode );
1462 dump_( mProperties );
1464 QgsDebugMsg( QString(
"there are %1 property scopes" ).arg( static_cast<int>( mProperties.
count() ) ) );
1469 mProperties.
writeXml( QStringLiteral(
"properties" ), qgisNode, *doc );
1472 mMapThemeCollection->writeXml( *doc );
1474 mLabelingEngineSettings->writeSettingsToProject(
this );
1476 mTransformContext.
writeXml( qgisNode, context );
1478 QDomElement annotationsElem = mAnnotationManager->writeXml( *doc, context );
1479 qgisNode.appendChild( annotationsElem );
1481 QDomElement layoutElem = mLayoutManager->writeXml( *doc );
1482 qgisNode.appendChild( layoutElem );
1490 QFile backupFile( QStringLiteral(
"%1~" ).arg( filename ) );
1492 ok &= backupFile.open( QIODevice::WriteOnly | QIODevice::Truncate );
1493 ok &= projectFile.open( QIODevice::ReadOnly );
1496 while ( ok && !projectFile.atEnd() )
1498 ba = projectFile.read( 10240 );
1499 ok &= backupFile.write( ba ) == ba.size();
1502 projectFile.close();
1507 setError( tr(
"Unable to create backup file %1" ).arg( backupFile.fileName() ) );
1512 struct utimbuf tb = { fi.lastRead().toTime_t(), fi.lastModified().toTime_t() };
1513 utime( backupFile.fileName().toUtf8().constData(), &tb );
1516 if ( !projectFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1518 projectFile.close();
1521 setError( tr(
"Unable to save to file %1" ).arg( projectFile.fileName() ) );
1525 QTemporaryFile tempFile;
1526 bool ok = tempFile.open();
1529 QTextStream projectFileStream( &tempFile );
1530 doc->save( projectFileStream, 2 );
1531 ok &= projectFileStream.pos() > -1;
1533 ok &= tempFile.seek( 0 );
1536 while ( ok && !tempFile.atEnd() )
1538 ba = tempFile.read( 10240 );
1539 ok &= projectFile.write( ba ) == ba.size();
1542 ok &= projectFile.error() == QFile::NoError;
1544 projectFile.close();
1551 setError( tr(
"Unable to save to file %1. Your project " 1552 "may be corrupted on disk. Try clearing some space on the volume and " 1553 "check file permissions before pressing save again." )
1554 .arg( projectFile.fileName() ) );
1569 return addKey_( scope, key, &mProperties, value );
1576 return addKey_( scope, key, &mProperties, value );
1583 return addKey_( scope, key, &mProperties, value );
1590 return addKey_( scope, key, &mProperties, value );
1597 return addKey_( scope, key, &mProperties, value );
1602 const QStringList &def,
1611 value =
property->value();
1613 bool valid = QVariant::StringList == value.type();
1619 return value.toStringList();
1638 value =
property->value();
1640 bool valid = value.canConvert( QVariant::String );
1645 return value.toString();
1660 value =
property->value();
1663 bool valid = value.canConvert( QVariant::Int );
1672 return value.toInt();
1685 QVariant value =
property->value();
1687 bool valid = value.canConvert( QVariant::Double );
1692 return value.toDouble();
1705 QVariant value =
property->value();
1707 bool valid = value.canConvert( QVariant::Bool );
1712 return value.toBool();
1725 return !
findKey_( scope, key, mProperties );
1733 QStringList entries;
1735 if ( foundProperty )
1750 QStringList entries;
1752 if ( foundProperty )
1765 dump_( mProperties );
1770 bool absolutePaths =
readBoolEntry( QStringLiteral(
"Paths" ), QStringLiteral(
"/Absolute" ),
false );
1784 void QgsProject::setError(
const QString &errorMessage )
1786 mErrorMessage = errorMessage;
1791 return mErrorMessage;
1794 void QgsProject::clearError()
1796 setError( QString() );
1801 delete mBadLayerHandler;
1802 mBadLayerHandler = handler;
1807 QHash< QString, QPair< QString, bool > >::const_iterator it = mEmbeddedLayers.find(
id );
1808 if ( it == mEmbeddedLayers.constEnd() )
1812 return it.value().first;
1820 static QString sPrevProjectFilePath;
1821 static QDateTime sPrevProjectFileTimestamp;
1822 static QDomDocument sProjectDocument;
1824 QDateTime projectFileTimestamp = QFileInfo( projectFilePath ).lastModified();
1826 if ( projectFilePath != sPrevProjectFilePath || projectFileTimestamp != sPrevProjectFileTimestamp )
1828 sPrevProjectFilePath.clear();
1830 QFile projectFile( projectFilePath );
1831 if ( !projectFile.open( QIODevice::ReadOnly ) )
1836 if ( !sProjectDocument.setContent( &projectFile ) )
1841 sPrevProjectFilePath = projectFilePath;
1842 sPrevProjectFileTimestamp = projectFileTimestamp;
1846 bool useAbsolutePaths =
true;
1848 QDomElement propertiesElem = sProjectDocument.documentElement().firstChildElement( QStringLiteral(
"properties" ) );
1849 if ( !propertiesElem.isNull() )
1851 QDomElement absElem = propertiesElem.firstChildElement( QStringLiteral(
"Paths" ) ).firstChildElement( QStringLiteral(
"Absolute" ) );
1852 if ( !absElem.isNull() )
1854 useAbsolutePaths = absElem.text().compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0;
1859 if ( !useAbsolutePaths )
1862 QDomElement projectLayersElem = sProjectDocument.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) );
1863 if ( projectLayersElem.isNull() )
1868 QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( QStringLiteral(
"maplayer" ) );
1869 for (
int i = 0; i < mapLayerNodes.size(); ++i )
1872 QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
1873 QString
id = mapLayerElem.firstChildElement( QStringLiteral(
"id" ) ).text();
1874 if (
id == layerId )
1877 if ( mapLayerElem.attribute( QStringLiteral(
"embedded" ) ) == QLatin1String(
"1" ) )
1882 mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );
1884 if ( addLayer( mapLayerElem, brokenNodes, embeddedContext ) )
1890 mEmbeddedLayers.remove( layerId );
1903 QFile projectFile( projectFilePath );
1904 if ( !projectFile.open( QIODevice::ReadOnly ) )
1909 QDomDocument projectDocument;
1910 if ( !projectDocument.setContent( &projectFile ) )
1919 QSet<QString> embeddedIdentifyDisabledLayers;
1920 QDomElement disabledLayersElem = projectDocument.documentElement().firstChildElement( QStringLiteral(
"properties" ) ).firstChildElement( QStringLiteral(
"Identify" ) ).firstChildElement( QStringLiteral(
"disabledLayers" ) );
1921 if ( !disabledLayersElem.isNull() )
1923 QDomNodeList valueList = disabledLayersElem.elementsByTagName( QStringLiteral(
"value" ) );
1924 for (
int i = 0; i < valueList.size(); ++i )
1926 embeddedIdentifyDisabledLayers.insert( valueList.at( i ).toElement().text() );
1932 QDomElement layerTreeElem = projectDocument.documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
1933 if ( !layerTreeElem.isNull() )
1943 if ( !group || group->customProperty( QStringLiteral(
"embedded" ) ).toBool() )
1956 newGroup->
setCustomProperty( QStringLiteral(
"embedded_project" ), projectFilePath );
1959 mLayerTreeRegistryBridge->
setEnabled(
false );
1960 initializeEmbeddedSubtree( projectFilePath, newGroup );
1961 mLayerTreeRegistryBridge->
setEnabled(
true );
1966 Q_FOREACH (
const QString &layerId, newGroup->
findLayerIds() )
1968 if ( embeddedIdentifyDisabledLayers.contains( layerId ) )
1970 thisProjectIdentifyDisabledLayers.append( layerId );
1985 void QgsProject::initializeEmbeddedSubtree(
const QString &projectFilePath,
QgsLayerTreeGroup *group )
1999 QList<QDomNode> brokenNodes;
2007 return mEvaluateDefaultValues;
2013 QMap<QString, QgsMapLayer *>::const_iterator layerIt = layers.constBegin();
2014 for ( ; layerIt != layers.constEnd(); ++layerIt )
2028 writeEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/TopologicalEditing" ), ( enabled ? 1 : 0 ) );
2034 return readNumEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/TopologicalEditing" ), 0 );
2039 QString distanceUnitString =
readEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/DistanceUnits" ), QString() );
2040 if ( !distanceUnitString.isEmpty() )
2057 QString areaUnitString =
readEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/AreaUnits" ), QString() );
2058 if ( !areaUnitString.isEmpty() )
2076 if ( !pfi.exists() )
2079 return pfi.canonicalPath();
2084 return mRelationManager;
2089 return mLayoutManager.get();
2094 return mLayoutManager.get();
2104 return mMapThemeCollection.get();
2109 return mAnnotationManager.get();
2114 return mAnnotationManager.get();
2121 QStringList newLayers;
2124 newLayers << l->
id();
2127 if ( newLayers == currentLayers )
2130 QStringList disabledLayerIds;
2134 disabledLayerIds << l->
id();
2142 writeEntry( QStringLiteral(
"Identify" ), QStringLiteral(
"/disabledLayers" ), layerIds );
2149 return readListEntry( QStringLiteral(
"Identify" ), QStringLiteral(
"/disabledLayers" ) );
2154 return mAutoTransaction;
2159 if ( autoTransaction != mAutoTransaction )
2163 if ( autoTransaction )
2164 onMapLayersAdded(
mapLayers().values() );
2166 cleanTransactionGroups(
true );
2172 return mTransactionGroups;
2183 return mLayerStore->count();
2188 return mLayerStore->mapLayer( layerId );
2193 return mLayerStore->mapLayersByName( layerName );
2196 bool QgsProject::unzip(
const QString &filename )
2202 if ( !archive->unzip( filename ) )
2204 setError( tr(
"Unable to unzip file '%1'" ).arg( filename ) );
2209 if ( archive->projectFile().isEmpty() )
2211 setError( tr(
"Zip archive does not provide a project file" ) );
2216 if ( !archive->auxiliaryStorageFile().isEmpty() )
2220 mAuxiliaryStorage.reset(
new QgsAuxiliaryStorage( archive->auxiliaryStorageFile(), false ) );
2228 if ( ! readProjectFile( archive->projectFile() ) )
2230 setError( tr(
"Cannot read unzipped qgs project file" ) );
2235 mArchive = std::move( archive );
2236 mArchive->clearProjectFile();
2241 bool QgsProject::zip(
const QString &filename )
2247 const QString baseName = QFileInfo( filename ).baseName();
2248 const QString qgsFileName = QStringLiteral(
"%1.qgs" ).arg( baseName );
2249 QFile qgsFile( QDir( archive->dir() ).filePath( qgsFileName ) );
2251 bool writeOk =
false;
2252 if ( qgsFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
2254 writeOk = writeProjectFile( qgsFile.fileName() );
2261 setError( tr(
"Unable to write temporary qgs file" ) );
2266 const QFileInfo info( qgsFile );
2269 if ( ! saveAuxiliaryStorage( asFileName ) )
2271 setError( tr(
"Unable to save auxiliary storage" ) );
2276 archive->addFile( qgsFile.fileName() );
2277 archive->addFile( asFileName );
2280 if ( !archive->zip( filename ) )
2282 setError( tr(
"Unable to perform zip" ) );
2295 const QList<QgsMapLayer *> &
layers,
2297 bool takeOwnership )
2299 const QList<QgsMapLayer *> myResultList = mLayerStore->addMapLayers( layers, takeOwnership );
2300 if ( !myResultList.isEmpty() )
2306 if ( mAuxiliaryStorage )
2321 return myResultList;
2327 bool takeOwnership )
2329 QList<QgsMapLayer *> addedLayers;
2330 addedLayers =
addMapLayers( QList<QgsMapLayer *>() << layer, addToLegend, takeOwnership );
2331 return addedLayers.isEmpty() ? nullptr : addedLayers[0];
2336 mLayerStore->removeMapLayers( layerIds );
2341 mLayerStore->removeMapLayers( layers );
2346 mLayerStore->removeMapLayer( layerId );
2351 mLayerStore->removeMapLayer( layer );
2356 return mLayerStore->takeMapLayer( layer );
2361 mLayerStore->removeAllMapLayers();
2366 QMap<QString, QgsMapLayer *>
layers = mLayerStore->mapLayers();
2367 QMap<QString, QgsMapLayer *>::const_iterator it = layers.constBegin();
2368 for ( ; it != layers.constEnd(); ++it )
2370 it.value()->reload();
2376 return mLayerStore->mapLayers();
2384 if ( settings.
value( QStringLiteral(
"/Projections/defaultBehavior" ), QStringLiteral(
"prompt" ) ).toString() == QStringLiteral(
"useProject" )
2385 || settings.
value( QStringLiteral(
"/Projections/defaultBehavior" ), QStringLiteral(
"prompt" ) ).toString() == QStringLiteral(
"prompt" ) )
2394 QString layerDefaultCrs = settings.
value( QStringLiteral(
"/Projections/layerDefaultCrs" ),
GEO_EPSG_CRS_AUTHID ).toString();
2403 mTrustLayerMetadata = trust;
2406 for (
auto it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
2416 bool QgsProject::saveAuxiliaryStorage(
const QString &filename )
2419 for (
auto it = layers.constBegin(); it != layers.constEnd(); ++it )
2431 if ( !filename.isEmpty() )
2433 return mAuxiliaryStorage->saveAs( filename );
2437 return mAuxiliaryStorage->saveAs( *
this );
2443 return mAuxiliaryStorage.get();
2448 return mAuxiliaryStorage.get();
Layer tree group node serves as a container for layers and further groups.
void setDirty(bool b=true)
Flag the project as dirty (modified).
void setTrustLayerMetadata(bool trust)
Sets the trust option allowing to indicate if the extent has to be read from the XML document when da...
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.
QString error() const
Return error message from previous read/write.
bool isDirty() const
Returns true if the project has been modified since the last write()
static Q_INVOKABLE AreaUnit decodeAreaUnit(const QString &string, bool *ok=nullptr)
Decodes an areal unit from a string.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
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.
void layersAdded(const QList< QgsMapLayer *> &layers)
Emitted when one or more layers were added to the registry.
static void removeInvalidLayers(QgsLayerTreeGroup *group)
Remove layer nodes that refer to invalid layers.
static QgsCoordinateReferenceSystem fromProj4(const QString &proj4)
Creates a CRS from a proj4 style formatted string.
static const QString QGIS_VERSION
Version string.
void setPathResolver(const QgsPathResolver &resolver)
Sets up path resolver for conversion between relative and absolute paths.
void snappingConfigChanged(const QgsSnappingConfig &config)
emitted whenever the configuration for snapping has changed
QgsRelationManager * relationManager() const
const QgsAuxiliaryStorage * auxiliaryStorage() const
Returns the current const auxiliary storage.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
void loadingLayer(const QString &)
void setAvoidIntersectionsLayers(const QList< QgsVectorLayer *> &layers)
A list of layers with which intersections should be avoided.
QString readEntry(const QString &scope, const QString &key, const QString &def=QString(), bool *ok=nullptr) const
void layerWasAdded(QgsMapLayer *layer)
Emitted when a layer was added to the store.
bool save()
Commits changes and starts editing then.
Manages storage of a set of QgsAnnotation annotation objects.
void dump_(const QgsProjectPropertyKey &topQgsPropertyKey)
void setTopologicalEditing(bool enabled)
Convenience function to set topological editing.
bool readBoolEntry(const QString &scope, const QString &key, bool def=false, bool *ok=nullptr) const
This class is a composition of two QSettings instances:
void resolveReferences(QgsProject *project) override
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects...
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
void setSnappingConfig(const QgsSnappingConfig &snappingConfig)
The snapping configuration for this project.
virtual void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context)=0
Write layer tree to XML.
void writeProject(QDomDocument &doc)
Writes the configuration to the specified QGIS project document.
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.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
static void warning(const QString &msg)
Goes to qWarning.
Class used to work with layer dependencies stored in a XML project or layer definition file...
void layersRemoved(const QStringList &layerIds)
Emitted after one or more layers were removed from the registry.
QgsProjectPropertyKey * addKey(const QString &keyName)
Adds the specified property key as a sub-key.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
static bool readOldLegend(QgsLayerTreeGroup *root, const QDomElement &legendElem)
Try to load layer tree from.
QString toProj4() const
Returns a Proj4 string representation of this CRS.
void setFileName(const QString &name)
Sets the file name associated with the project.
Class providing some utility methods to manage auxiliary storage.
void crsChanged()
Emitted when the CRS of the project has changed.
void layersAdded(const QList< QgsMapLayer *> &layers)
Emitted when one or more layers were added to the store.
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the store.
void entryList(QStringList &entries) const
Returns any sub-keys contained by this property that do not contain other keys.
void configChanged()
Emitted whenever the configuration is changed.
void labelingEngineSettingsChanged()
Emitted when global configuration of the labeling engine changes.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all registered layers by layer ID.
void topologicalEditingChanged()
Emitted when the topological editing flag has changed.
int count() const
Returns the number of registered layers.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static Q_INVOKABLE QgsUnitTypes::DistanceUnit decodeDistanceUnit(const QString &string, bool *ok=nullptr)
Decodes a distance unit from a string.
void reloadAllLayers()
Reload all registered layer's provider data caches, synchronising the layer with any changes in the d...
void resolveReferences(const QgsProject *project, bool looseMatching=false) override
Calls resolveReferences() on child tree nodes.
void legendLayersAdded(const QList< QgsMapLayer *> &layers)
Emitted, when a layer was added to the registry and the legend.
bool isValid() const
Return the status of the layer.
void removeKey(const QString &keyName)
Removes the specified key.
void projectSaved()
emitted when the project file has been written and closed
void layerWillBeRemoved(const QString &layerId)
Emitted when a layer is about to be removed from the store.
QStringList nonIdentifiableLayers() const
Get the list of layers which currently should not be taken into account on map identification.
void reset()
reset to default values
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning)
add a message to the instance (and create it if necessary)
void allLayersRemoved()
Emitted when all layers are removed, before layersWillBeRemoved() and layerWillBeRemoved() signals ar...
QgsMapLayerStore * layerStore()
Returns a pointer to the project's internal layer store.
QgsCoordinateTransformContext transformContext() const
Returns a copy of the project's coordinate transform context, which stores various information regard...
QList< QgsMapLayer * > customLayerOrder() const
The order in which layers will be rendered on the canvas.
void clear()
Remove any relation managed by this class.
QgsProject(QObject *parent=nullptr)
Create a new QgsProject.
static QString extension()
Returns the extension used for auxiliary databases.
int readNumEntry(const QString &scope, const QString &key, int def=0, bool *ok=nullptr) const
QgsProjectVersion getVersion(const QDomDocument &doc)
Return the version string found in the given DOM document.
const QString GEO_NONE
Constant that holds the string representation for "No ellips/No CRS".
void fileNameChanged()
Emitted when the file name of the project changes.
void readProject(const QDomDocument &doc)
Reads the configuration from the specified QGIS project document.
Class allowing to manage the zip/unzip actions on project file.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context, QStringList &missingTransforms)
Reads the context's state from a DOM element.
QgsProjectProperty * find(const QString &propertyName) const
Attempts to find a property with a matching sub-key name.
void setNonIdentifiableLayers(const QList< QgsMapLayer *> &layers)
Set a list of layers which should not be taken into account on map identification.
virtual bool isKey() const =0
Returns true if the property is a QgsProjectPropertyKey.
bool writeEntry(const QString &scope, const QString &key, bool value)
Write a boolean entry to the project file.
QgsProjectPropertyValue * setValue(const QString &name, const QVariant &value)
Sets the value associated with this key.
void readSettings()
Reads the context's state from application settings.
void missingDatumTransforms(const QStringList &missingTransforms)
Emitted when datum transforms stored in the project are not available locally.
bool read()
Reads the project from its currently associated file (see fileName() ).
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
QList< QgsLayerTreeNode * > children()
Get list of children of the node. Children are owned by the parent.
bool evaluateDefaultValues() const
Should default values be evaluated on provider side when requested and not when committed.
QgsMapLayer * takeMapLayer(QgsMapLayer *layer)
Takes a layer from the registry.
QgsProjectProperty * addKey_(const QString &scope, const QString &key, QgsProjectPropertyKey *rootProperty, const QVariant &value)
Add the given key and value.
QString name() const
The name of the property is used as identifier.
Namespace with helper functions for layer tree operations.
QgsPathResolver pathResolver() const
Return path resolver object with considering whether the project uses absolute or relative paths and ...
#define QgsDebugMsgLevel(str, level)
QgsUnitTypes::AreaUnit areaUnits() const
Convenience function to query default area measurement units for project.
void setAreaUnits(QgsUnitTypes::AreaUnit unit)
Sets the default area measurement units for the project.
A class to describe the version of a project.
QString layerIsEmbedded(const QString &id) const
Returns project file path if layer is embedded from other project file. Returns empty string if layer...
int count() const
Returns the number of sub-keys contained by this property.
virtual void clearKeys()
Deletes any sub-nodes from the property.
void layerRemoved(const QString &layerId)
Emitted after a layer was removed from the store.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsCoordinateReferenceSystem defaultCrsForNewLayers() const
Returns the default CRS for new layers based on the settings and the current project CRS...
void setBadLayerHandler(QgsProjectBadLayerHandler *handler)
Change handler for missing layers.
void dumpProperties() const
Dump out current project properties to stderr.
void readProject(const QDomDocument &)
emitted when project is being read
Listens to the updates in map layer registry and does changes in layer tree.
bool addLayer(QgsVectorLayer *layer)
Add a layer to this transaction group.
QVariant customProperty(const QString &key, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer. Properties are stored in a map and saved in project file...
QStringList subkeyList(const QString &scope, const QString &key) const
Return keys with keys – do not return keys that contain only values.
void clear()
Clear any information from this layer tree.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the project's native coordinate reference system.
static void replaceChildrenOfEmbeddedGroups(QgsLayerTreeGroup *group)
Remove subtree of embedded groups and replaces it with a custom property embedded-visible-layers.
void layerLoaded(int i, int n)
Emitted when a layer from a projects was read.
void dump(int tabs=0) const override
Dumps out the keys and values.
QStringList readListEntry(const QString &scope, const QString &key, const QStringList &def=QStringList(), bool *ok=nullptr) const
Key value accessors.
void setDistanceUnits(QgsUnitTypes::DistanceUnit unit)
Sets the default distance measurement units for the project.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
This class is a base class for nodes in a layer tree.
bool removeEntry(const QString &scope, const QString &key)
Remove the given key.
Reads and writes project states.
const QString GEO_EPSG_CRS_AUTHID
Geographic coord sys from EPSG authority.
void setEllipsoid(const QString &ellipsoid)
Sets the project's ellipsoid from a proj string representation, e.g., "WGS84".
void insertChildNodes(int index, const QList< QgsLayerTreeNode *> &nodes)
Insert existing nodes at specified position.
static bool supportsTransaction(const QgsVectorLayer *layer)
Checks if the provider of a given layer supports transactions.
void writeMapLayer(QgsMapLayer *mapLayer, QDomElement &layerElem, QDomDocument &doc)
Emitted, when a layer is being saved.
void removeAllMapLayers()
Removes all registered layers.
void removeCustomProperty(const QString &key)
Remove a custom property from layer. Properties are stored in a map and saved in project file...
virtual bool isValue() const =0
Returns true if the property is a QgsProjectPropertyValue.
Contains information about the context in which a coordinate transform is executed.
void removeKey_(const QString &scope, const QString &key, QgsProjectPropertyKey &rootProperty)
void setCustomVariables(const QVariantMap &customVariables)
A map of custom project variables.
Manages storage of a set of layouts.
void layersRemoved(const QStringList &layerIds)
Emitted after one or more layers were removed from the store.
QList< QgsMapLayer * > mapLayersByName(const QString &layerName) const
Retrieve a list of matching registered layers by layer name.
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
void setProviderProperty(ProviderProperty property, const QVariant &value)
Allows setting arbitrary properties on the provider.
bool write()
Writes the project to its current associated file (see fileName() ).
QgsAnnotationManager * annotationManager()
Returns pointer to the project's annotation manager.
void readLayerOrderFromXml(const QDomElement &doc)
Load the layer order from an XML element.
const QgsLayoutManager * layoutManager() const
Returns the project's layout manager, which manages compositions within the project.
QStringList makeKeyTokens_(const QString &scope, const QString &key)
Take the given scope and key and convert them to a string list of key tokens that will be used to nav...
bool loadAuxiliaryLayer(const QgsAuxiliaryStorage &storage, const QString &key=QString())
Loads the auxiliary layer for this vector layer.
bool removeLayers(const QList< QgsMapLayer *> &layers)
Removes the specified layers from the individual layer configuration.
QgsLayerTreeGroup * createEmbeddedGroup(const QString &groupName, const QString &projectFilePath, const QStringList &invisibleLayers)
Create layer group instance defined in an arbitrary project file.
static Q_INVOKABLE QString encodeUnit(QgsUnitTypes::DistanceUnit unit)
Encodes a distance unit to a string.
void mapThemeCollectionChanged()
Emitted when the map theme collection changes.
bool topologicalEditing() const
Convenience function to query topological editing status.
bool readLayer(const QDomNode &layerNode)
Reads the layer described in the associated DOM node.
QString homePath() const
Return project's home path.
bool readLayerXml(const QDomElement &layerElement, const QgsReadWriteContext &context)
Sets state from Dom document.
bool isEmpty() const
Returns true if this property contains no sub-keys.
QgsMapThemeCollection * mapThemeCollection()
Returns pointer to the project's map theme collection.
QString fileName() const
Returns the project's file name.
Project property key node.
DistanceUnit
Units of distance.
QgsLayerTree * layerTreeRoot() const
Return pointer to the root (invisible) node of the project's layer tree.
void writeXml(QDomElement &element, const QgsReadWriteContext &context) const
Writes the context's state to a DOM element.
void transactionGroupsChanged()
Emitted whenever a new transaction group has been created or a transaction group has been removed...
void layerWillBeRemoved(const QString &layerId)
Emitted when a layer is about to be removed from the registry.
void writeProject(QDomDocument &)
emitted when project is being written
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
bool isZipped() const
Returns true if the project comes from a zip archive, false otherwise.
void oldProjectVersionWarning(const QString &)
emitted when an old project file is read.
void customVariablesChanged()
Emitted whenever the expression variables stored in the project have been changed.
QFileInfo fileInfo() const
Returns QFileInfo object for the project's associated file.
void layerRemoved(const QString &layerId)
Emitted after a layer was removed from the registry.
static QgsCoordinateReferenceSystem fromOgcWmsCrs(const QString &ogcCrs)
Creates a CRS from a given OGC WMS-format Coordinate Reference System string.
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the registry.
bool autoTransaction() const
Transactional editing means that on supported datasources (postgres databases) the edit state of all ...
void setAutoTransaction(bool autoTransaction)
Transactional editing means that on supported datasources (postgres databases) the edit state of all ...
QString source() const
Returns the source for the layer.
QMap< QPair< QString, QString >, QgsTransactionGroup * > transactionGroups()
Map of transaction groups.
virtual void handleBadLayers(const QList< QDomNode > &layers)
This method will be called whenever the project tries to load layers which cannot be accessed...
This class manages a set of relations between layers.
void nonIdentifiableLayersChanged(QStringList nonIdentifiableLayers)
Emitted when the list of layer which are excluded from map identification changes.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), const Section section=NoSection) const
Returns the value for setting key.
QgsLayerTreeGroup * findGroup(const QString &name)
Find group node with specified name.
QgsSnappingConfig snappingConfig() const
The snapping configuration for this project.
bool createEmbeddedLayer(const QString &layerId, const QString &projectFilePath, QList< QDomNode > &brokenNodes, bool saveFlag=true)
Creates a maplayer instance defined in an arbitrary project file.
Stores global configuration for labeling engine.
static QgsProject * instance()
Returns the QgsProject singleton instance.
void removeMapLayer(const QString &layerId)
Remove a layer from the registry by layer ID.
CORE_EXPORT bool isZipFile(const QString &filename)
Returns true if the file name is a zipped file ( i.e with a '.qgz' extension, false otherwise...
This class represents a coordinate reference system (CRS).
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the project's coordinate transform context, which stores various information regarding which dat...
void setTitle(const QString &title)
Sets the project's title.
QgsVectorDataProvider * dataProvider() override
Returns the layer's data provider.
QgsCoordinateReferenceSystem crs() const
Returns the project's native coordinate reference system.
void setEnabled(bool enabled)
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
An Abstract Base Class for QGIS project property hierarchys.
QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
void setItemVisibilityChecked(bool checked)
Check or uncheck a node (independently of its ancestors or children)
QgsMapLayer * addMapLayer(QgsMapLayer *mapLayer, bool addToLegend=true, bool takeOwnership=true)
Add a layer to the map of loaded layers.
void homePathChanged()
Emitted when the home path of the project changes.
void removeMapLayers(const QStringList &layerIds)
Remove a set of layers from the registry by layer ID.
double readDoubleEntry(const QString &scope, const QString &key, double def=0, bool *ok=nullptr) const
void subkeyList(QStringList &entries) const
Return any sub-keys contained by this property which themselves contain other keys.
bool readXml(const QDomNode &keyNode) override
Restores the property hierarchy from a specified DOM node.
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
QString name() const override
Returns the group's name.
void avoidIntersectionsLayersChanged()
Emitted whenever avoidIntersectionsLayers has changed.
QStringList findLayerIds() const
Find layer IDs used in all layer nodes.
Container class that allows storage of map themes consisting of visible map layers and layer styles...
void transformContextChanged()
Emitted when the project transformContext() is changed.
QString title() const
Returns the project's title.
This is a container for configuration of the snapping of the project.
QgsUnitTypes::DistanceUnit distanceUnits() const
Convenience function to query default distance measurement units for project.
QVariantMap customVariables() const
A map of custom project variables.
void readMapLayer(QgsMapLayer *mapLayer, const QDomElement &layerNode)
Emitted, after the basic initialization of a layer from the project file is done. ...
QString ellipsoid() const
Returns a proj string representing the project's ellipsoid setting, e.g., "WGS84".
QgsLayerTreeLayer * findLayer(QgsMapLayer *layer) const
Find layer node representing the map layer.
QString providerType() const
Return the provider type for this layer.
Resolves relative paths into absolute paths and vice versa.
bool addLayers(const QList< QgsMapLayer *> &layers)
Adds the specified layers as individual layers to the configuration with standard configuration...
Class for storing the component parts of a PostgreSQL/RDBMS datasource URI.
bool writeXml(QDomNode &node, QDomDocument &doc) const
Stores state to the given Dom node in the given document.
QgsProjectProperty * findKey_(const QString &scope, const QString &key, QgsProjectPropertyKey &rootProperty)
return the property that matches the given key sequence, if any
void setEvaluateDefaultValues(bool evaluateDefaultValues)
Defines if default values should be evaluated on provider side when requested and not when committed...
Represents a vector layer which manages a vector based data sets.
QList< QgsVectorLayer * > avoidIntersectionsLayers() const
A list of layers with which intersections should be avoided.
bool writeLayerXml(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores state in Dom node.
QgsLayerTree * clone() const override
Create a copy of the node. Returns new instance.
void setName(const QString &name)
The name of the property is used as identifier.
Evaluate default values on provider side when calling QgsVectorDataProvider::defaultValue( int index ...
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QStringList entryList(const QString &scope, const QString &key) const
Return keys with values – do not return keys that contain other keys.
QgsPluginLayer * createLayer(const QString &typeName, const QString &uri=QString())
Returns new layer if corresponding plugin has been found else returns a nullptr.
void removeAll()
Emitted when all layers are removed, before layersWillBeRemoved() and layerWillBeRemoved() signals ar...
void _getProperties(const QDomDocument &doc, QgsProjectPropertyKey &project_properties)
Restore any optional properties found in "doc" to "properties".
bool writeXml(const QString &nodeName, QDomElement &element, QDomDocument &document) override
Writes the property hierarchy to a specified DOM element.
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets project's global labeling engine settings.
void clear()
Clear the project - removes all settings and resets it back to an empty, default state.
static void updateEmbeddedGroupsProjectPath(QgsLayerTreeGroup *group, const QgsProject *project)
Interface for classes that handle missing layer files when reading project file.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
static QgsCoordinateReferenceSystem fromSrsId(long srsId)
Creates a CRS from a specified QGIS SRS ID.
void layerWasAdded(QgsMapLayer *layer)
Emitted when a layer was added to the registry.
Layer tree node points to a map layer.
void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for the node. Properties are stored in a map and saved in project file...
void setReadExtentFromXml(bool readExtentFromXml)
Flag allowing to indicate if the extent has to be read from the XML document when data source has no ...
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns project's global labeling engine settings.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.