67 #include "qgsattributeeditorcontainer.h"
71 #include <QApplication>
75 #include <QTextStream>
76 #include <QTemporaryFile>
79 #include <QStandardPaths>
81 #include <QRegularExpression>
84 #include <sys/utime.h>
93 class ScopedIntIncrementor
97 ScopedIntIncrementor(
int *variable )
98 : mVariable( variable )
103 ScopedIntIncrementor(
const ScopedIntIncrementor &other ) =
delete;
104 ScopedIntIncrementor &operator=(
const ScopedIntIncrementor &other ) =
delete;
114 ~ScopedIntIncrementor()
120 int *mVariable =
nullptr;
135 QStringList keyTokens = QStringList( scope );
136 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
137 keyTokens += key.split(
'/', QString::SkipEmptyParts );
139 keyTokens += key.split(
'/', Qt::SkipEmptyParts );
143 keyTokens.push_front( QStringLiteral(
"properties" ) );
146 for (
int i = 0; i < keyTokens.size(); ++i )
148 QString keyToken = keyTokens.at( i );
152 const thread_local QRegularExpression sInvalidRegexp = QRegularExpression(
"([^:A-Z_a-z\\x{C0}-\\x{D6}\\x{D8}-\\x{F6}\\x{F8}-\\x{2FF}\\x{370}-\\x{37D}\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFFD}\\-\\.0-9\\x{B7}\\x{0300}-\\x{036F}\\x{203F}-\\x{2040}]|^[^:A-Z_a-z\\x{C0}-\\x{D6}\\x{D8}-\\x{F6}\\x{F8}-\\x{2FF}\\x{370}-\\x{37D}\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFFD}])" );
153 if ( keyToken.contains( sInvalidRegexp ) )
155 QString errorString = QObject::tr(
"Entry token invalid : '%1'. The token will not be saved to file." ).arg( keyToken );
183 while ( !keySequence.isEmpty() )
187 if ( keySequence.first() == currentProperty->
name() )
190 keySequence.pop_front();
192 if ( 1 == keySequence.count() )
195 return currentProperty->
find( keySequence.front() );
197 else if ( keySequence.isEmpty() )
202 return currentProperty;
204 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
206 if ( nextProperty->
isKey() )
210 else if ( nextProperty->
isValue() && 1 == keySequence.count() )
216 return currentProperty;
254 const QVariant &value,
255 bool &propertiesModified )
264 propertiesModified =
false;
265 while ( ! keySequence.isEmpty() )
269 if ( keySequence.first() == currentProperty->
name() )
272 keySequence.pop_front();
276 if ( 1 == keySequence.count() )
279 if ( !property || property->value() != value )
281 currentProperty->
setValue( keySequence.front(), value );
282 propertiesModified =
true;
285 return currentProperty;
289 else if ( keySequence.isEmpty() )
291 if ( currentProperty->
value() != value )
294 propertiesModified =
true;
297 return currentProperty;
299 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
303 if ( currentProperty )
314 if ( ( newPropertyKey = currentProperty->
addKey( keySequence.first() ) ) )
316 currentProperty = newPropertyKey;
349 while ( ! keySequence.isEmpty() )
353 if ( keySequence.first() == currentProperty->
name() )
356 keySequence.pop_front();
360 if ( 1 == keySequence.count() )
362 currentProperty->
removeKey( keySequence.front() );
367 else if ( keySequence.isEmpty() )
369 previousQgsPropertyKey->
removeKey( currentProperty->
name() );
371 else if ( ( nextProperty = currentProperty->
find( keySequence.first() ) ) )
373 previousQgsPropertyKey = currentProperty;
376 if ( currentProperty )
402 , mSnappingConfig( this )
415 mProperties.
setName( QStringLiteral(
"properties" ) );
418 mMainAnnotationLayer->setParent(
this );
432 this, [ = ](
const QStringList &
layers ) { mProjectScope.reset(); emit layersWillBeRemoved( layers ); } );
436 this, [ = ](
const QString & layer ) { mProjectScope.reset(); emit layerWillBeRemoved( layer ); } );
438 this, [ = ](
QgsMapLayer * layer ) { mProjectScope.reset(); emit layerWillBeRemoved( layer ); } );
440 [ = ](
const QStringList &
layers ) { mProjectScope.reset(); emit layersRemoved( layers ); } );
442 [ = ](
const QString & layer ) { mProjectScope.reset(); emit layerRemoved( layer ); } );
444 [ = ]() { mProjectScope.reset(); emit removeAll(); } );
446 [ = ](
const QList< QgsMapLayer * > &
layers ) { mProjectScope.reset(); emit layersAdded( layers ); } );
448 [ = ](
QgsMapLayer * layer ) { mProjectScope.reset(); emit layerWasAdded( layer ); } );
456 [ = ](
const QList<QgsMapLayer *> &
layers )
458 for (
const auto &layer :
layers )
465 [ = ](
const QList<QgsMapLayer *> &
layers )
467 for (
const auto &layer :
layers )
482 mIsBeingDeleted =
true;
485 delete mBadLayerHandler;
486 delete mRelationManager;
487 delete mLayerTreeRegistryBridge;
489 if (
this == sProject )
516 mProjectScope.reset();
524 return mMetadata.
title();
534 return mSaveUserFull;
539 return mSaveDateTime;
554 if ( dirty && mDirtyBlockCount > 0 )
557 if ( mDirty == dirty )
566 if ( path == mHomePath )
570 mCachedHomePath.clear();
571 mProjectScope.reset();
580 const QList<QgsAttributeEditorElement *> elements = parent->children();
582 for ( QgsAttributeEditorElement *element : elements )
584 if ( element->type() == QgsAttributeEditorElement::AeTypeContainer )
586 QgsAttributeEditorContainer *container =
dynamic_cast<QgsAttributeEditorContainer *
>( element );
588 translationContext->
registerTranslation( QStringLiteral(
"project:layers:%1:formcontainers" ).arg( layerId ), container->name() );
590 if ( !container->children().empty() )
603 translationContext->
registerTranslation( QStringLiteral(
"project:layers:%1" ).arg( layer->layerId() ), layer->name() );
620 translationContext->
registerTranslation( QStringLiteral(
"project:layers:%1:fieldaliases" ).arg( vlayer->
id() ), fieldName );
635 const QList<QgsLayerTreeGroup *> groupLayers = mRootGroup->
findGroups();
638 translationContext->
registerTranslation( QStringLiteral(
"project:layergroups" ), groupLayer->name() );
642 const QList<QgsRelation> &relations = mRelationManager->
relations().values();
645 translationContext->
registerTranslation( QStringLiteral(
"project:relations" ), relation.name() );
651 mDataDefinedServerProperties = properties;
656 return mDataDefinedServerProperties;
661 if ( name == mFile.fileName() )
666 mFile.setFileName( name );
667 mCachedHomePath.clear();
668 mProjectScope.reset();
673 if ( newHomePath != oldHomePath )
681 return mFile.fileName();
686 mOriginalPath = path;
691 return mOriginalPath;
696 return QFileInfo( mFile );
709 storage->readProjectStorageMetadata( mFile.fileName(),
metadata );
714 return QFileInfo( mFile.fileName() ).lastModified();
723 if ( mFile.fileName().isEmpty() )
726 return QFileInfo( mFile.fileName() ).absolutePath();
734 if ( mFile.fileName().isEmpty() )
737 return QFileInfo( mFile.fileName() ).absoluteFilePath();
745 storage->readProjectStorageMetadata( mFile.fileName(),
metadata );
750 return QFileInfo( mFile.fileName() ).completeBaseName();
764 writeEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectionsEnabled" ),
crs.
isValid() ? 1 : 0 );
765 mProjectScope.reset();
770 if ( adjustEllipsoid )
776 if ( !
crs().isValid() )
779 return readEntry( QStringLiteral(
"Measure" ), QStringLiteral(
"/Ellipsoid" ),
geoNone() );
784 if (
ellipsoid ==
readEntry( QStringLiteral(
"Measure" ), QStringLiteral(
"/Ellipsoid" ) ) )
787 mProjectScope.reset();
794 return mTransformContext;
799 if ( context == mTransformContext )
802 mTransformContext = context;
803 mProjectScope.reset();
806 for (
auto &layer : mLayerStore.get()->mapLayers() )
808 layer->setTransformContext( context );
815 ScopedIntIncrementor snapSingleBlocker( &mBlockSnappingUpdates );
817 mProjectScope.reset();
818 mFile.setFileName( QString() );
821 mSaveUserFull.clear();
822 mSaveDateTime = QDateTime();
825 mCachedHomePath.clear();
826 mAutoTransaction =
false;
827 mEvaluateDefaultValues =
false;
829 mTrustLayerMetadata =
false;
830 mCustomVariables.clear();
833 if ( !mSettings.
value( QStringLiteral(
"projects/anonymize_new_projects" ),
false,
QgsSettings::Core ).toBool() )
844 mEmbeddedLayers.clear();
845 mRelationManager->
clear();
846 mAnnotationManager->clear();
847 mLayoutManager->clear();
848 mBookmarkManager->
clear();
849 mViewSettings->
reset();
850 mTimeSettings->
reset();
851 mDisplaySettings->
reset();
852 mSnappingConfig.
reset();
860 mLabelingEngineSettings->clear();
867 if ( !mIsBeingDeleted )
875 writeEntry( QStringLiteral(
"PositionPrecision" ), QStringLiteral(
"/Automatic" ),
true );
876 writeEntry( QStringLiteral(
"PositionPrecision" ), QStringLiteral(
"/DecimalPlaces" ), 2 );
877 writeEntry( QStringLiteral(
"Paths" ), QStringLiteral(
"/Absolute" ),
false );
880 writeEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/DistanceUnits" ), mSettings.
value( QStringLiteral(
"/qgis/measure/displayunits" ) ).toString() );
881 writeEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/AreaUnits" ), mSettings.
value( QStringLiteral(
"/qgis/measure/areaunits" ) ).toString() );
883 int red = mSettings.
value( QStringLiteral(
"qgis/default_canvas_color_red" ), 255 ).toInt();
884 int green = mSettings.
value( QStringLiteral(
"qgis/default_canvas_color_green" ), 255 ).toInt();
885 int blue = mSettings.
value( QStringLiteral(
"qgis/default_canvas_color_blue" ), 255 ).toInt();
888 red = mSettings.
value( QStringLiteral(
"qgis/default_selection_color_red" ), 255 ).toInt();
889 green = mSettings.
value( QStringLiteral(
"qgis/default_selection_color_green" ), 255 ).toInt();
890 blue = mSettings.
value( QStringLiteral(
"qgis/default_selection_color_blue" ), 0 ).toInt();
891 int alpha = mSettings.
value( QStringLiteral(
"qgis/default_selection_color_alpha" ), 255 ).toInt();
898 if ( mMainAnnotationLayer )
899 mMainAnnotationLayer->
reset();
901 snapSingleBlocker.release();
903 if ( !mBlockSnappingUpdates )
915 topQgsPropertyKey.
dump();
950 QDomElement propertiesElem = doc.documentElement().firstChildElement( QStringLiteral(
"properties" ) );
952 if ( propertiesElem.isNull() )
957 QDomNodeList scopes = propertiesElem.childNodes();
959 if ( propertiesElem.firstChild().isNull() )
961 QgsDebugMsg( QStringLiteral(
"empty ``properties'' XML tag ... bailing" ) );
965 if ( ! project_properties.
readXml( propertiesElem ) )
967 QgsDebugMsg( QStringLiteral(
"Project_properties.readXml() failed" ) );
981 QDomElement ddElem = doc.documentElement().firstChildElement( QStringLiteral(
"dataDefinedServerProperties" ) );
982 if ( !ddElem.isNull() )
984 if ( !ddServerProperties.
readXml( ddElem, dataDefinedServerPropertyDefinitions ) )
986 QgsDebugMsg( QStringLiteral(
"dataDefinedServerProperties.readXml() failed" ) );
989 return ddServerProperties;
996 static void _getTitle(
const QDomDocument &doc, QString &title )
998 QDomElement titleNode = doc.documentElement().firstChildElement( QStringLiteral(
"title" ) );
1002 if ( titleNode.isNull() )
1008 if ( !titleNode.hasChildNodes() )
1014 QDomNode titleTextNode = titleNode.firstChild();
1016 if ( !titleTextNode.isText() )
1022 QDomText titleText = titleTextNode.toText();
1024 title = titleText.data();
1028 static void readProjectFileMetadata(
const QDomDocument &doc, QString &lastUser, QString &lastUserFull, QDateTime &lastSaveDateTime )
1030 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
1038 QDomNode qgisNode = nl.item( 0 );
1040 QDomElement qgisElement = qgisNode.toElement();
1041 lastUser = qgisElement.attribute( QStringLiteral(
"saveUser" ), QString() );
1042 lastUserFull = qgisElement.attribute( QStringLiteral(
"saveUserFull" ), QString() );
1043 lastSaveDateTime = QDateTime::fromString( qgisElement.attribute( QStringLiteral(
"saveDateTime" ), QString() ), Qt::ISODate );
1049 QDomNodeList nl = doc.elementsByTagName( QStringLiteral(
"qgis" ) );
1053 QgsDebugMsg( QStringLiteral(
" unable to find qgis element in project file" ) );
1057 QDomNode qgisNode = nl.item( 0 );
1059 QDomElement qgisElement = qgisNode.toElement();
1060 QgsProjectVersion projectVersion( qgisElement.attribute( QStringLiteral(
"version" ) ) );
1061 return projectVersion;
1067 return mSnappingConfig;
1082 if ( mAvoidIntersectionsMode == mode )
1085 mAvoidIntersectionsMode = mode;
1089 bool QgsProject::_getMapLayers(
const QDomDocument &doc, QList<QDomNode> &brokenNodes, QgsProject::ReadFlags flags )
1094 QDomElement layerElement = doc.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
1098 if ( layerElement.isNull() )
1108 bool returnStatus =
true;
1111 while ( ! layerElement.isNull() )
1114 layerElement = layerElement.nextSiblingElement( QStringLiteral(
"maplayer" ) );
1120 if ( depSorter.hasCycle() )
1124 if ( depSorter.hasMissingDependency() )
1125 returnStatus =
false;
1129 const QVector<QDomNode> sortedLayerNodes = depSorter.sortedLayerNodes();
1130 const int totalLayerCount = sortedLayerNodes.count();
1133 for (
const QDomNode &node : sortedLayerNodes )
1135 const QDomElement element = node.toElement();
1137 const QString name =
translate( QStringLiteral(
"project:layers:%1" ).arg( node.namedItem( QStringLiteral(
"id" ) ).toElement().text() ), node.namedItem( QStringLiteral(
"layername" ) ).toElement().text() );
1138 if ( !name.isNull() )
1139 emit
loadingLayer( tr(
"Loading layer %1" ).arg( name ) );
1141 profile.switchTask( name );
1143 if ( element.attribute( QStringLiteral(
"embedded" ) ) == QLatin1String(
"1" ) )
1145 createEmbeddedLayer( element.attribute( QStringLiteral(
"id" ) ),
readPath( element.attribute( QStringLiteral(
"project" ) ) ), brokenNodes,
true, flags );
1154 if ( !addLayer( element, brokenNodes, context, flags ) )
1156 returnStatus =
false;
1159 if ( !messages.isEmpty() )
1168 return returnStatus;
1171 bool QgsProject::addLayer(
const QDomElement &layerElem, QList<QDomNode> &brokenNodes,
QgsReadWriteContext &context, QgsProject::ReadFlags flags )
1173 QString type = layerElem.attribute( QStringLiteral(
"type" ) );
1175 std::unique_ptr<QgsMapLayer>
mapLayer;
1183 QgsDebugMsg( QStringLiteral(
"Unknown layer type \"%1\"" ).arg( type ) );
1187 switch ( layerType )
1191 mapLayer = qgis::make_unique<QgsVectorLayer>();
1201 mapLayer = qgis::make_unique<QgsRasterLayer>();
1205 mapLayer = qgis::make_unique<QgsMeshLayer>();
1209 mapLayer = qgis::make_unique<QgsVectorTileLayer>();
1213 mapLayer = qgis::make_unique<QgsPointCloudLayer>();
1218 QString
typeName = layerElem.attribute( QStringLiteral(
"name" ) );
1226 mapLayer = qgis::make_unique<QgsAnnotationLayer>( QString(), options );
1233 QgsDebugMsg( QStringLiteral(
"Unable to create layer" ) );
1241 const QString layerId { layerElem.namedItem( QStringLiteral(
"id" ) ).toElement().text() };
1242 Q_ASSERT( ! layerId.isEmpty() );
1246 QgsMapLayer::ReadFlags layerFlags = QgsMapLayer::ReadFlags();
1253 profile.switchTask( tr(
"Load layer source" ) );
1256 profile.switchTask( tr(
"Add layer to project" ) );
1257 QList<QgsMapLayer *> newLayers;
1269 QgsDebugMsg(
"Unable to load " + type +
" layer" );
1270 brokenNodes.push_back( layerElem );
1275 if ( ! layerWasStored )
1280 return layerIsValid;
1285 mFile.setFileName( filename );
1286 mCachedHomePath.clear();
1287 mProjectScope.reset();
1289 return read( flags );
1294 QString filename = mFile.fileName();
1299 QTemporaryFile inDevice;
1300 if ( !inDevice.open() )
1302 setError( tr(
"Unable to open %1" ).arg( inDevice.fileName() ) );
1308 if ( !storage->readProject( filename, &inDevice, context ) )
1310 QString err = tr(
"Unable to open %1" ).arg( filename );
1311 QList<QgsReadWriteContext::ReadWriteMessage> messages = context.
takeMessages();
1312 if ( !messages.isEmpty() )
1313 err += QStringLiteral(
"\n\n" ) + messages.last().message();
1317 returnValue = unzip( inDevice.fileName(), flags );
1323 returnValue = unzip( mFile.fileName(), flags );
1328 returnValue = readProjectFile( mFile.fileName(), flags );
1334 mFile.setFileName( filename );
1335 mCachedHomePath.clear();
1336 mProjectScope.reset();
1341 mTranslator.reset(
nullptr );
1348 bool QgsProject::readProjectFile(
const QString &filename, QgsProject::ReadFlags flags )
1351 ScopedIntIncrementor snapSignalBlock( &mBlockSnappingUpdates );
1353 QFile projectFile( filename );
1359 QString localeFileName = QStringLiteral(
"%1_%2" ).arg( QFileInfo( projectFile.fileName() ).baseName(), mSettings.
value( QStringLiteral(
"locale/userLocale" ), QString() ).toString() );
1361 if ( QFile( QStringLiteral(
"%1/%2.qm" ).arg( QFileInfo( projectFile.fileName() ).absolutePath(), localeFileName ) ).exists() )
1363 mTranslator.reset(
new QTranslator() );
1364 mTranslator->load( localeFileName, QFileInfo( projectFile.fileName() ).absolutePath() );
1367 profile.switchTask( tr(
"Reading project file" ) );
1368 std::unique_ptr<QDomDocument> doc(
new QDomDocument( QStringLiteral(
"qgis" ) ) );
1370 if ( !projectFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
1372 projectFile.close();
1374 setError( tr(
"Unable to open %1" ).arg( projectFile.fileName() ) );
1383 if ( !doc->setContent( &projectFile, &errorMsg, &line, &column ) )
1387 QMessageBox::critical( 0, tr(
"Read Project File" ),
1388 tr(
"%1 at line %2 column %3" ).arg( errorMsg ).arg( line ).arg( column ) );
1391 QString errorString = tr(
"Project file read error in file %1: %2 at line %3 column %4" )
1392 .arg( projectFile.fileName(), errorMsg ).arg( line ).arg( column );
1396 projectFile.close();
1398 setError( tr(
"%1 for file %2" ).arg( errorString, projectFile.fileName() ) );
1403 projectFile.close();
1411 profile.switchTask( tr(
"Updating project file" ) );
1412 if ( thisVersion > fileVersion )
1415 "version of qgis (saved in " + fileVersion.
text() +
1417 "). Problems may occur." );
1424 projectFile.updateRevision( thisVersion );
1428 profile.switchTask( tr(
"Creating auxiliary storage" ) );
1429 QString
fileName = mFile.fileName();
1430 std::unique_ptr<QgsAuxiliaryStorage> aStorage = std::move( mAuxiliaryStorage );
1432 mAuxiliaryStorage = std::move( aStorage );
1434 mCachedHomePath.clear();
1435 mProjectScope.reset();
1436 mSaveVersion = fileVersion;
1439 profile.switchTask( tr(
"Reading properties" ) );
1448 dump_( mProperties );
1453 _getTitle( *doc, oldTitle );
1455 readProjectFileMetadata( *doc, mSaveUser, mSaveUserFull, mSaveDateTime );
1457 QDomNodeList homePathNl = doc->elementsByTagName( QStringLiteral(
"homePath" ) );
1458 if ( homePathNl.count() > 0 )
1460 QDomElement homePathElement = homePathNl.at( 0 ).toElement();
1461 QString
homePath = homePathElement.attribute( QStringLiteral(
"path" ) );
1471 readNumEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/CanvasColorGreenPart" ), 255 ),
1472 readNumEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/CanvasColorBluePart" ), 255 ) );
1475 readNumEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorGreenPart" ), 255 ),
1476 readNumEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorBluePart" ), 255 ),
1477 readNumEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorAlphaPart" ), 255 ) );
1486 if (
readNumEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectionsEnabled" ), 0 ) )
1489 QDomNode srsNode = doc->documentElement().namedItem( QStringLiteral(
"projectCrs" ) );
1490 if ( !srsNode.isNull() )
1492 projectCrs.
readXml( srsNode );
1497 QString projCrsString =
readEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectCRSProj4String" ) );
1498 long currentCRS =
readNumEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectCRSID" ), -1 );
1499 const QString authid =
readEntry( QStringLiteral(
"SpatialRefSys" ), QStringLiteral(
"/ProjectCrs" ) );
1502 bool isUserAuthId = authid.startsWith( QLatin1String(
"USER:" ), Qt::CaseInsensitive );
1503 if ( !authid.isEmpty() && !isUserAuthId )
1507 if ( !projectCrs.
isValid() && currentCRS >= 0 )
1513 if ( !projCrsString.isEmpty() && ( authid.isEmpty() || isUserAuthId ) && ( !projectCrs.
isValid() || projectCrs.
toProj() != projCrsString ) )
1527 QStringList datumErrors;
1528 if ( !mTransformContext.
readXml( doc->documentElement(), context, datumErrors ) && !datumErrors.empty() )
1536 QStringList variableNames =
readListEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableNames" ) );
1537 QStringList variableValues =
readListEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableValues" ) );
1539 mCustomVariables.clear();
1540 if ( variableNames.length() == variableValues.length() )
1542 for (
int i = 0; i < variableNames.length(); ++i )
1544 mCustomVariables.insert( variableNames.at( i ), variableValues.at( i ) );
1549 QgsMessageLog::logMessage( tr(
"Project Variables Invalid" ), tr(
"The project contains invalid variable settings." ) );
1552 QDomElement element = doc->documentElement().firstChildElement( QStringLiteral(
"projectMetadata" ) );
1554 if ( !element.isNull() )
1563 if ( mMetadata.
title().isEmpty() && !oldTitle.isEmpty() )
1570 element = doc->documentElement().firstChildElement( QStringLiteral(
"autotransaction" ) );
1571 if ( ! element.isNull() )
1573 if ( element.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
1574 mAutoTransaction =
true;
1577 element = doc->documentElement().firstChildElement( QStringLiteral(
"evaluateDefaultValues" ) );
1578 if ( !element.isNull() )
1580 if ( element.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
1581 mEvaluateDefaultValues =
true;
1585 element = doc->documentElement().firstChildElement( QStringLiteral(
"trust" ) );
1586 if ( !element.isNull() )
1588 if ( element.attribute( QStringLiteral(
"active" ), QStringLiteral(
"0" ) ).toInt() == 1 )
1589 mTrustLayerMetadata =
true;
1593 profile.switchTask( tr(
"Loading layer tree" ) );
1596 QDomElement layerTreeElem = doc->documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
1597 if ( !layerTreeElem.isNull() )
1609 mLayerTreeRegistryBridge->
setEnabled(
false );
1612 profile.switchTask( tr(
"Reading map layers" ) );
1614 QList<QDomNode> brokenNodes;
1615 bool clean = _getMapLayers( *doc, brokenNodes, flags );
1620 QgsDebugMsg( QStringLiteral(
"Unable to get map layers from project file." ) );
1622 if ( !brokenNodes.isEmpty() )
1624 QgsDebugMsg(
"there are " + QString::number( brokenNodes.size() ) +
" broken layers" );
1632 mMainAnnotationLayer->
readLayerXml( doc->documentElement().firstChildElement( QStringLiteral(
"main-annotation-layer" ) ), context );
1637 profile.switchTask( tr(
"Resolving layer references" ) );
1638 QMap<QString, QgsMapLayer *>
layers = mLayerStore->mapLayers();
1639 for ( QMap<QString, QgsMapLayer *>::iterator it =
layers.begin(); it !=
layers.end(); ++it )
1641 it.value()->resolveReferences(
this );
1644 mLayerTreeRegistryBridge->
setEnabled(
true );
1647 profile.switchTask( tr(
"Loading embedded layers" ) );
1648 loadEmbeddedNodes( mRootGroup, flags );
1651 profile.switchTask( tr(
"Resolving references" ) );
1654 if ( !layerTreeElem.isNull() )
1660 QDomElement layerTreeCanvasElem = doc->documentElement().firstChildElement( QStringLiteral(
"layer-tree-canvas" ) );
1661 if ( !layerTreeCanvasElem.isNull( ) )
1669 const QStringList requiredLayerIds =
readListEntry( QStringLiteral(
"RequiredLayers" ), QStringLiteral(
"Layers" ) );
1670 for (
const QString &layerId : requiredLayerIds )
1677 const QStringList disabledLayerIds =
readListEntry( QStringLiteral(
"Identify" ), QStringLiteral(
"/disabledLayers" ) );
1678 for (
const QString &layerId : disabledLayerIds )
1692 profile.switchTask( tr(
"Storing original layer properties" ) );
1698 profile.switchTask( tr(
"Loading map themes" ) );
1701 mMapThemeCollection->readXml( *doc );
1703 profile.switchTask( tr(
"Loading label settings" ) );
1704 mLabelingEngineSettings->readSettingsFromProject(
this );
1707 profile.switchTask( tr(
"Loading annotations" ) );
1708 mAnnotationManager->readXml( doc->documentElement(), context );
1711 profile.switchTask( tr(
"Loading layouts" ) );
1712 mLayoutManager->readXml( doc->documentElement(), *doc );
1714 profile.switchTask( tr(
"Loading bookmarks" ) );
1715 mBookmarkManager->
readXml( doc->documentElement(), *doc );
1718 QMap<QString, QgsMapLayer *> existingMaps =
mapLayers();
1719 for ( QMap<QString, QgsMapLayer *>::iterator it = existingMaps.begin(); it != existingMaps.end(); ++it )
1721 it.value()->setDependencies( it.value()->dependencies() );
1724 profile.switchTask( tr(
"Loading snapping settings" ) );
1728 profile.switchTask( tr(
"Loading view settings" ) );
1731 const QStringList scales =
readListEntry( QStringLiteral(
"Scales" ), QStringLiteral(
"/ScalesList" ) );
1732 QVector<double> res;
1733 for (
const QString &scale : scales )
1735 const QStringList parts = scale.split(
':' );
1736 if ( parts.size() != 2 )
1740 const double denominator = QLocale().toDouble( parts[1], &ok );
1747 QDomElement viewSettingsElement = doc->documentElement().firstChildElement( QStringLiteral(
"ProjectViewSettings" ) );
1748 if ( !viewSettingsElement.isNull() )
1749 mViewSettings->
readXml( viewSettingsElement, context );
1752 profile.switchTask( tr(
"Loading temporal settings" ) );
1753 QDomElement timeSettingsElement = doc->documentElement().firstChildElement( QStringLiteral(
"ProjectTimeSettings" ) );
1754 if ( !timeSettingsElement.isNull() )
1755 mTimeSettings->
readXml( timeSettingsElement, context );
1757 profile.switchTask( tr(
"Loading display settings" ) );
1758 QDomElement displaySettingsElement = doc->documentElement().firstChildElement( QStringLiteral(
"ProjectDisplaySettings" ) );
1759 if ( !displaySettingsElement.isNull() )
1760 mDisplaySettings->
readXml( displaySettingsElement, context );
1762 profile.switchTask( tr(
"Updating variables" ) );
1764 profile.switchTask( tr(
"Updating CRS" ) );
1769 profile.switchTask( tr(
"Reading external settings" ) );
1773 profile.switchTask( tr(
"Updating interface" ) );
1775 snapSignalBlock.release();
1776 if ( !mBlockSnappingUpdates )
1787 QgsDebugMsgLevel( QString(
"Project save user: %1" ).arg( mSaveUser ), 2 );
1788 QgsDebugMsgLevel( QString(
"Project save user: %1" ).arg( mSaveUserFull ), 2 );
1797 QString newFileName( QStringLiteral(
"%1/%2.qgs" ).arg( QFileInfo( projectFile.fileName() ).absolutePath(), localeFileName ) );
1814 bool QgsProject::loadEmbeddedNodes(
QgsLayerTreeGroup *group, QgsProject::ReadFlags flags )
1817 const auto constChildren = group->
children();
1823 if ( childGroup->
customProperty( QStringLiteral(
"embedded" ) ).toInt() )
1826 QString projectPath =
readPath( childGroup->
customProperty( QStringLiteral(
"embedded_project" ) ).toString() );
1827 childGroup->
setCustomProperty( QStringLiteral(
"embedded_project" ), projectPath );
1831 QList<QgsLayerTreeNode *> clonedChildren;
1832 const auto constChildren = newGroup->
children();
1834 clonedChildren << newGroupChild->clone();
1842 loadEmbeddedNodes( childGroup, flags );
1847 if ( child->customProperty( QStringLiteral(
"embedded" ) ).toInt() )
1849 QList<QDomNode> brokenNodes;
1852 valid = valid &&
false;
1864 return mCustomVariables;
1869 if ( variables == mCustomVariables )
1873 QStringList variableNames;
1874 QStringList variableValues;
1876 QVariantMap::const_iterator it = variables.constBegin();
1877 for ( ; it != variables.constEnd(); ++it )
1879 variableNames << it.key();
1880 variableValues << it.value().toString();
1883 writeEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableNames" ), variableNames );
1884 writeEntry( QStringLiteral(
"Variables" ), QStringLiteral(
"/variableValues" ), variableValues );
1886 mCustomVariables = variables;
1887 mProjectScope.reset();
1894 *mLabelingEngineSettings = settings;
1900 return *mLabelingEngineSettings;
1905 mProjectScope.reset();
1906 return mLayerStore.get();
1911 return mLayerStore.get();
1916 QList<QgsVectorLayer *>
layers;
1917 QStringList layerIds =
readListEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/AvoidIntersectionsList" ), QStringList() );
1918 const auto constLayerIds = layerIds;
1919 for (
const QString &layerId : constLayerIds )
1930 const auto constLayers =
layers;
1932 list << layer->id();
1933 writeEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/AvoidIntersectionsList" ), list );
1950 if ( mProjectScope )
1952 std::unique_ptr< QgsExpressionContextScope > projectScope = qgis::make_unique< QgsExpressionContextScope >( *mProjectScope );
1956 return projectScope.release();
1959 mProjectScope = qgis::make_unique< QgsExpressionContextScope >( QObject::tr(
"Project" ) );
1963 QVariantMap::const_iterator it = vars.constBegin();
1965 for ( ; it != vars.constEnd(); ++it )
1967 mProjectScope->setVariable( it.key(), it.value(),
true );
1971 if ( projectPath.isEmpty() )
1972 projectPath = mOriginalPath;
1973 QString projectFolder = QFileInfo( projectPath ).path();
1974 QString projectFilename = QFileInfo( projectPath ).fileName();
1975 QString projectBasename =
baseName();
2004 QVariantMap keywords;
2006 for (
auto it = metadataKeywords.constBegin(); it != metadataKeywords.constEnd(); ++it )
2008 keywords.insert( it.key(), it.value() );
2013 QVariantList layersIds;
2015 const QMap<QString, QgsMapLayer *> layersInProject = mLayerStore->mapLayers();
2016 layersIds.reserve( layersInProject.count() );
2017 layers.reserve( layersInProject.count() );
2018 for (
auto it = layersInProject.constBegin(); it != layersInProject.constEnd(); ++it )
2020 layersIds << it.value()->id();
2026 mProjectScope->addFunction( QStringLiteral(
"project_color" ),
new GetNamedProjectColor(
this ) );
2031 void QgsProject::onMapLayersAdded(
const QList<QgsMapLayer *> &layers )
2033 QMap<QString, QgsMapLayer *> existingMaps =
mapLayers();
2035 bool tgChanged =
false;
2037 const auto constLayers =
layers;
2040 if ( layer->isValid() )
2042 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
2049 const QString connString = QgsTransaction::connectionString( vlayer->
source() );
2057 mTransactionGroups.insert( qMakePair( key, connString ), tg );
2072 for ( QMap<QString, QgsMapLayer *>::const_iterator it = existingMaps.cbegin(); it != existingMaps.cend(); ++it )
2074 QSet<QgsMapLayerDependency> deps = it.value()->dependencies();
2075 if ( deps.contains( layer->id() ) )
2078 it.value()->setDependencies( deps );
2088 void QgsProject::onMapLayersRemoved(
const QList<QgsMapLayer *> &layers )
2094 void QgsProject::cleanTransactionGroups(
bool force )
2096 bool changed =
false;
2097 for ( QMap< QPair< QString, QString>,
QgsTransactionGroup *>::Iterator tg = mTransactionGroups.begin(); tg != mTransactionGroups.end(); )
2099 if ( tg.value()->
isEmpty() || force )
2102 tg = mTransactionGroups.erase( tg );
2120 QList<QDomNode> brokenNodes;
2121 if ( addLayer( layerNode.toElement(), brokenNodes, context ) )
2125 QVector<QgsVectorLayer *> vectorLayers = layers<QgsVectorLayer *>();
2126 const auto constVectorLayers = vectorLayers;
2130 layer->resolveReferences(
this );
2140 mFile.setFileName( filename );
2141 mCachedHomePath.clear();
2147 mProjectScope.reset();
2153 QString storageFilePath { storage->filePath( mFile.fileName() ) };
2154 if ( storageFilePath.isEmpty() )
2156 writeEntry( QStringLiteral(
"Paths" ), QStringLiteral(
"/Absolute" ),
true );
2160 QString tempPath = QStandardPaths::standardLocations( QStandardPaths::TempLocation ).at( 0 );
2161 QString tmpZipFilename( tempPath + QDir::separator() + QUuid::createUuid().toString() );
2163 if ( !zip( tmpZipFilename ) )
2166 QFile tmpZipFile( tmpZipFilename );
2167 if ( !tmpZipFile.open( QIODevice::ReadOnly ) )
2169 setError( tr(
"Unable to read file %1" ).arg( tmpZipFilename ) );
2174 if ( !storage->writeProject( mFile.fileName(), &tmpZipFile, context ) )
2176 QString err = tr(
"Unable to save project to storage %1" ).arg( mFile.fileName() );
2177 QList<QgsReadWriteContext::ReadWriteMessage> messages = context.
takeMessages();
2178 if ( !messages.isEmpty() )
2179 err += QStringLiteral(
"\n\n" ) + messages.last().message();
2185 QFile::remove( tmpZipFilename );
2192 return zip( mFile.fileName() );
2198 const bool asOk = saveAuxiliaryStorage();
2199 const bool writeOk = writeProjectFile( mFile.fileName() );
2202 if ( !asOk && writeOk )
2204 const QString err = mAuxiliaryStorage->errorString();
2205 setError( tr(
"Unable to save auxiliary storage ('%1')" ).arg( err ) );
2208 return asOk && writeOk;
2212 bool QgsProject::writeProjectFile(
const QString &filename )
2214 QFile projectFile( filename );
2220 QFileInfo myFileInfo( projectFile );
2221 if ( myFileInfo.exists() && !myFileInfo.isWritable() )
2223 setError( tr(
"%1 is not writable. Please adjust permissions (if possible) and try again." )
2224 .arg( projectFile.fileName() ) );
2232 QDomImplementation DomImplementation;
2233 DomImplementation.setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
2235 QDomDocumentType documentType =
2236 DomImplementation.createDocumentType( QStringLiteral(
"qgis" ), QStringLiteral(
"http://mrcc.com/qgis.dtd" ),
2237 QStringLiteral(
"SYSTEM" ) );
2238 std::unique_ptr<QDomDocument> doc(
new QDomDocument( documentType ) );
2240 QDomElement qgisNode = doc->createElement( QStringLiteral(
"qgis" ) );
2241 qgisNode.setAttribute( QStringLiteral(
"projectname" ),
title() );
2242 qgisNode.setAttribute( QStringLiteral(
"version" ),
Qgis::version() );
2244 if ( !mSettings.
value( QStringLiteral(
"projects/anonymize_saved_projects" ),
false,
QgsSettings::Core ).toBool() )
2248 qgisNode.setAttribute( QStringLiteral(
"saveUser" ), newSaveUser );
2249 qgisNode.setAttribute( QStringLiteral(
"saveUserFull" ), newSaveUserFull );
2250 mSaveUser = newSaveUser;
2251 mSaveUserFull = newSaveUserFull;
2252 mSaveDateTime = QDateTime::currentDateTime();
2253 qgisNode.setAttribute( QStringLiteral(
"saveDateTime" ), mSaveDateTime.toString( Qt::ISODate ) );
2258 mSaveUserFull.clear();
2259 mSaveDateTime = QDateTime();
2261 doc->appendChild( qgisNode );
2264 QDomElement homePathNode = doc->createElement( QStringLiteral(
"homePath" ) );
2265 homePathNode.setAttribute( QStringLiteral(
"path" ), mHomePath );
2266 qgisNode.appendChild( homePathNode );
2269 QDomElement titleNode = doc->createElement( QStringLiteral(
"title" ) );
2270 qgisNode.appendChild( titleNode );
2272 QDomElement transactionNode = doc->createElement( QStringLiteral(
"autotransaction" ) );
2273 transactionNode.setAttribute( QStringLiteral(
"active" ), mAutoTransaction ? 1 : 0 );
2274 qgisNode.appendChild( transactionNode );
2276 QDomElement evaluateDefaultValuesNode = doc->createElement( QStringLiteral(
"evaluateDefaultValues" ) );
2277 evaluateDefaultValuesNode.setAttribute( QStringLiteral(
"active" ), mEvaluateDefaultValues ? 1 : 0 );
2278 qgisNode.appendChild( evaluateDefaultValuesNode );
2280 QDomElement trustNode = doc->createElement( QStringLiteral(
"trust" ) );
2281 trustNode.setAttribute( QStringLiteral(
"active" ), mTrustLayerMetadata ? 1 : 0 );
2282 qgisNode.appendChild( trustNode );
2284 QDomText titleText = doc->createTextNode(
title() );
2285 titleNode.appendChild( titleText );
2288 QDomElement srsNode = doc->createElement( QStringLiteral(
"projectCrs" ) );
2290 qgisNode.appendChild( srsNode );
2297 clonedRoot->
writeXml( qgisNode, context );
2301 writeEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/AvoidIntersectionsMode" ),
static_cast<int>( mAvoidIntersectionsMode ) );
2309 QDomElement annotationLayerNode = doc->createElement( QStringLiteral(
"main-annotation-layer" ) );
2310 mMainAnnotationLayer->
writeLayerXml( annotationLayerNode, *doc, context );
2311 qgisNode.appendChild( annotationLayerNode );
2315 QDomElement projectLayersNode = doc->createElement( QStringLiteral(
"projectlayers" ) );
2317 QMap<QString, QgsMapLayer *>::ConstIterator li =
layers.constBegin();
2318 while ( li !=
layers.end() )
2324 QHash< QString, QPair< QString, bool> >::const_iterator emIt = mEmbeddedLayers.constFind( ml->
id() );
2325 if ( emIt == mEmbeddedLayers.constEnd() )
2327 QDomElement maplayerElem;
2333 maplayerElem = doc->createElement( QStringLiteral(
"maplayer" ) );
2338 QDomDocument document;
2341 maplayerElem = document.firstChildElement();
2345 QgsDebugMsg( QStringLiteral(
"Could not restore layer properties for layer %1" ).arg( ml->
id() ) );
2351 projectLayersNode.appendChild( maplayerElem );
2357 if ( emIt.value().second )
2359 QDomElement mapLayerElem = doc->createElement( QStringLiteral(
"maplayer" ) );
2360 mapLayerElem.setAttribute( QStringLiteral(
"embedded" ), 1 );
2361 mapLayerElem.setAttribute( QStringLiteral(
"project" ),
writePath( emIt.value().first ) );
2362 mapLayerElem.setAttribute( QStringLiteral(
"id" ), ml->
id() );
2363 projectLayersNode.appendChild( mapLayerElem );
2370 qgisNode.appendChild( projectLayersNode );
2372 QDomElement layerOrderNode = doc->createElement( QStringLiteral(
"layerorder" ) );
2374 for (
QgsMapLayer *layer : constCustomLayerOrder )
2376 QDomElement mapLayerElem = doc->createElement( QStringLiteral(
"layer" ) );
2377 mapLayerElem.setAttribute( QStringLiteral(
"id" ), layer->id() );
2378 layerOrderNode.appendChild( mapLayerElem );
2380 qgisNode.appendChild( layerOrderNode );
2382 mLabelingEngineSettings->writeSettingsToProject(
this );
2384 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/CanvasColorRedPart" ), mBackgroundColor.red() );
2385 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/CanvasColorGreenPart" ), mBackgroundColor.green() );
2386 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/CanvasColorBluePart" ), mBackgroundColor.blue() );
2388 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorRedPart" ), mSelectionColor.red() );
2389 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorGreenPart" ), mSelectionColor.green() );
2390 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorBluePart" ), mSelectionColor.blue() );
2391 writeEntry( QStringLiteral(
"Gui" ), QStringLiteral(
"/SelectionColorAlphaPart" ), mSelectionColor.alpha() );
2395 dump_( mProperties );
2398 QgsDebugMsgLevel( QStringLiteral(
"there are %1 property scopes" ).arg(
static_cast<int>( mProperties.
count() ) ), 2 );
2403 mProperties.
writeXml( QStringLiteral(
"properties" ), qgisNode, *doc );
2406 QDomElement ddElem = doc->createElement( QStringLiteral(
"dataDefinedServerProperties" ) );
2407 mDataDefinedServerProperties.
writeXml( ddElem, dataDefinedServerPropertyDefinitions() );
2408 qgisNode.appendChild( ddElem );
2410 mMapThemeCollection->writeXml( *doc );
2412 mTransformContext.
writeXml( qgisNode, context );
2414 QDomElement metadataElem = doc->createElement( QStringLiteral(
"projectMetadata" ) );
2416 qgisNode.appendChild( metadataElem );
2418 QDomElement annotationsElem = mAnnotationManager->writeXml( *doc, context );
2419 qgisNode.appendChild( annotationsElem );
2421 QDomElement layoutElem = mLayoutManager->writeXml( *doc );
2422 qgisNode.appendChild( layoutElem );
2424 QDomElement bookmarkElem = mBookmarkManager->
writeXml( *doc );
2425 qgisNode.appendChild( bookmarkElem );
2427 QDomElement viewSettingsElem = mViewSettings->
writeXml( *doc, context );
2428 qgisNode.appendChild( viewSettingsElem );
2430 QDomElement timeSettingsElement = mTimeSettings->
writeXml( *doc, context );
2431 qgisNode.appendChild( timeSettingsElement );
2433 QDomElement displaySettingsElem = mDisplaySettings->
writeXml( *doc, context );
2434 qgisNode.appendChild( displaySettingsElem );
2442 QFile backupFile( QStringLiteral(
"%1~" ).arg( filename ) );
2444 ok &= backupFile.open( QIODevice::WriteOnly | QIODevice::Truncate );
2445 ok &= projectFile.open( QIODevice::ReadOnly );
2448 while ( ok && !projectFile.atEnd() )
2450 ba = projectFile.read( 10240 );
2451 ok &= backupFile.write( ba ) == ba.size();
2454 projectFile.close();
2459 setError( tr(
"Unable to create backup file %1" ).arg( backupFile.fileName() ) );
2464 struct utimbuf tb = {
static_cast<time_t
>( fi.lastRead().toSecsSinceEpoch() ),
static_cast<time_t
>( fi.lastModified().toSecsSinceEpoch() ) };
2465 utime( backupFile.fileName().toUtf8().constData(), &tb );
2468 if ( !projectFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
2470 projectFile.close();
2473 setError( tr(
"Unable to save to file %1" ).arg( projectFile.fileName() ) );
2477 QTemporaryFile tempFile;
2478 bool ok = tempFile.open();
2481 QTextStream projectFileStream( &tempFile );
2482 doc->save( projectFileStream, 2 );
2483 ok &= projectFileStream.pos() > -1;
2485 ok &= tempFile.seek( 0 );
2488 while ( ok && !tempFile.atEnd() )
2490 ba = tempFile.read( 10240 );
2491 ok &= projectFile.write( ba ) == ba.size();
2494 ok &= projectFile.error() == QFile::NoError;
2496 projectFile.close();
2503 setError( tr(
"Unable to save to file %1. Your project "
2504 "may be corrupted on disk. Try clearing some space on the volume and "
2505 "check file permissions before pressing save again." )
2506 .arg( projectFile.fileName() ) );
2518 bool propertiesModified;
2519 bool success =
addKey_( scope, key, &mProperties, value, propertiesModified );
2521 if ( propertiesModified )
2529 bool propertiesModified;
2530 bool success =
addKey_( scope, key, &mProperties, value, propertiesModified );
2532 if ( propertiesModified )
2540 bool propertiesModified;
2541 bool success =
addKey_( scope, key, &mProperties, value, propertiesModified );
2543 if ( propertiesModified )
2551 bool propertiesModified;
2552 bool success =
addKey_( scope, key, &mProperties, value, propertiesModified );
2554 if ( propertiesModified )
2562 bool propertiesModified;
2563 bool success =
addKey_( scope, key, &mProperties, value, propertiesModified );
2565 if ( propertiesModified )
2573 const QStringList &def,
2582 value =
property->value();
2584 bool valid = QVariant::StringList == value.type();
2590 return value.toStringList();
2612 value =
property->value();
2614 bool valid = value.canConvert( QVariant::String );
2619 return value.toString();
2636 value =
property->value();
2639 bool valid = value.canConvert( QVariant::Int );
2648 return value.toInt();
2661 QVariant value =
property->value();
2663 bool valid = value.canConvert( QVariant::Double );
2668 return value.toDouble();
2683 QVariant value =
property->value();
2685 bool valid = value.canConvert( QVariant::Bool );
2690 return value.toBool();
2700 if (
findKey_( scope, key, mProperties ) )
2706 return !
findKey_( scope, key, mProperties );
2714 QStringList entries;
2716 if ( foundProperty )
2731 QStringList entries;
2733 if ( foundProperty )
2746 dump_( mProperties );
2751 bool absolutePaths =
readBoolEntry( QStringLiteral(
"Paths" ), QStringLiteral(
"/Absolute" ),
false );
2753 if ( ! absolutePaths )
2760 filePath = storage->filePath( mFile.fileName() );
2780 void QgsProject::setError(
const QString &errorMessage )
2782 mErrorMessage = errorMessage;
2787 return mErrorMessage;
2790 void QgsProject::clearError()
2792 setError( QString() );
2797 delete mBadLayerHandler;
2798 mBadLayerHandler = handler;
2803 QHash< QString, QPair< QString, bool > >::const_iterator it = mEmbeddedLayers.find(
id );
2804 if ( it == mEmbeddedLayers.constEnd() )
2808 return it.value().first;
2812 bool saveFlag, QgsProject::ReadFlags flags )
2816 static QString sPrevProjectFilePath;
2817 static QDateTime sPrevProjectFileTimestamp;
2818 static QDomDocument sProjectDocument;
2820 QString qgsProjectFile = projectFilePath;
2822 if ( projectFilePath.endsWith( QLatin1String(
".qgz" ), Qt::CaseInsensitive ) )
2824 archive.
unzip( projectFilePath );
2828 QDateTime projectFileTimestamp = QFileInfo( projectFilePath ).lastModified();
2830 if ( projectFilePath != sPrevProjectFilePath || projectFileTimestamp != sPrevProjectFileTimestamp )
2832 sPrevProjectFilePath.clear();
2834 QFile projectFile( qgsProjectFile );
2835 if ( !projectFile.open( QIODevice::ReadOnly ) )
2840 if ( !sProjectDocument.setContent( &projectFile ) )
2845 sPrevProjectFilePath = projectFilePath;
2846 sPrevProjectFileTimestamp = projectFileTimestamp;
2850 bool useAbsolutePaths =
true;
2852 QDomElement propertiesElem = sProjectDocument.documentElement().firstChildElement( QStringLiteral(
"properties" ) );
2853 if ( !propertiesElem.isNull() )
2855 QDomElement absElem = propertiesElem.firstChildElement( QStringLiteral(
"Paths" ) ).firstChildElement( QStringLiteral(
"Absolute" ) );
2856 if ( !absElem.isNull() )
2858 useAbsolutePaths = absElem.text().compare( QLatin1String(
"true" ), Qt::CaseInsensitive ) == 0;
2863 if ( !useAbsolutePaths )
2868 QDomElement projectLayersElem = sProjectDocument.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) );
2869 if ( projectLayersElem.isNull() )
2874 QDomElement mapLayerElem = projectLayersElem.firstChildElement( QStringLiteral(
"maplayer" ) );
2875 while ( ! mapLayerElem.isNull() )
2878 QString
id = mapLayerElem.firstChildElement( QStringLiteral(
"id" ) ).text();
2879 if (
id == layerId )
2882 if ( mapLayerElem.attribute( QStringLiteral(
"embedded" ) ) == QLatin1String(
"1" ) )
2887 mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );
2889 if ( addLayer( mapLayerElem, brokenNodes, embeddedContext, flags ) )
2895 mEmbeddedLayers.remove( layerId );
2899 mapLayerElem = mapLayerElem.nextSiblingElement( QStringLiteral(
"maplayer" ) );
2908 QString qgsProjectFile = projectFilePath;
2910 if ( projectFilePath.endsWith( QLatin1String(
".qgz" ), Qt::CaseInsensitive ) )
2912 archive.
unzip( projectFilePath );
2917 QFile projectFile( qgsProjectFile );
2918 if ( !projectFile.open( QIODevice::ReadOnly ) )
2923 QDomDocument projectDocument;
2924 if ( !projectDocument.setContent( &projectFile ) )
2936 QDomElement layerTreeElem = projectDocument.documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
2937 if ( !layerTreeElem.isNull() )
2947 if ( !group || group->
customProperty( QStringLiteral(
"embedded" ) ).toBool() )
2960 newGroup->
setCustomProperty( QStringLiteral(
"embedded_project" ), projectFilePath );
2963 mLayerTreeRegistryBridge->
setEnabled(
false );
2964 initializeEmbeddedSubtree( projectFilePath, newGroup, flags );
2965 mLayerTreeRegistryBridge->
setEnabled(
true );
2968 const auto constFindLayerIds = newGroup->
findLayerIds();
2969 for (
const QString &layerId : constFindLayerIds )
2982 void QgsProject::initializeEmbeddedSubtree(
const QString &projectFilePath,
QgsLayerTreeGroup *group, QgsProject::ReadFlags flags )
2984 const auto constChildren = group->
children();
2988 child->setCustomProperty( QStringLiteral(
"embedded" ), 1 );
2997 QList<QDomNode> brokenNodes;
3005 return mEvaluateDefaultValues;
3014 QMap<QString, QgsMapLayer *>::const_iterator layerIt =
layers.constBegin();
3015 for ( ; layerIt !=
layers.constEnd(); ++layerIt )
3017 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layerIt.value() );
3029 writeEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/TopologicalEditing" ), ( enabled ? 1 : 0 ) );
3035 return readNumEntry( QStringLiteral(
"Digitizing" ), QStringLiteral(
"/TopologicalEditing" ), 0 );
3040 QString distanceUnitString =
readEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/DistanceUnits" ), QString() );
3041 if ( !distanceUnitString.isEmpty() )
3057 QString areaUnitString =
readEntry( QStringLiteral(
"Measurement" ), QStringLiteral(
"/AreaUnits" ), QString() );
3058 if ( !areaUnitString.isEmpty() )
3074 if ( !mCachedHomePath.isEmpty() )
3075 return mCachedHomePath;
3079 if ( !mHomePath.isEmpty() )
3081 QFileInfo homeInfo( mHomePath );
3082 if ( !homeInfo.isRelative() )
3084 mCachedHomePath = mHomePath;
3090 mCachedHomePath = pfi.path();
3092 return mCachedHomePath;
3095 if ( !pfi.exists() )
3097 mCachedHomePath = mHomePath;
3101 if ( !mHomePath.isEmpty() )
3104 mCachedHomePath = QDir::cleanPath( pfi.path() +
'/' + mHomePath );
3108 mCachedHomePath = pfi.canonicalPath();
3110 return mCachedHomePath;
3120 return mRelationManager;
3125 return mLayoutManager.get();
3130 return mLayoutManager.get();
3135 return mBookmarkManager;
3140 return mBookmarkManager;
3145 return mViewSettings;
3150 return mViewSettings;
3155 return mTimeSettings;
3160 return mTimeSettings;
3165 return mDisplaySettings;
3170 return mDisplaySettings;
3180 return mMapThemeCollection.get();
3185 return mAnnotationManager.get();
3190 return mAnnotationManager.get();
3195 const QMap<QString, QgsMapLayer *> &projectLayers =
mapLayers();
3196 for ( QMap<QString, QgsMapLayer *>::const_iterator it = projectLayers.constBegin(); it != projectLayers.constEnd(); ++it )
3201 if (
layers.contains( it.value() ) )
3216 for (
const QString &layerId : layerIds )
3232 for ( QMap<QString, QgsMapLayer *>::const_iterator it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
3244 return mAutoTransaction;
3254 onMapLayersAdded(
mapLayers().values() );
3256 cleanTransactionGroups(
true );
3262 return mTransactionGroups;
3273 return mLayerStore->count();
3278 return mLayerStore->validCount();
3283 return mLayerStore->mapLayer( layerId );
3288 return mLayerStore->mapLayersByName( layerName );
3293 QList<QgsMapLayer *>
layers;
3294 const auto constMapLayers { mLayerStore->mapLayers() };
3295 for (
const auto &l : constMapLayers )
3297 if ( ! l->shortName().isEmpty() )
3299 if ( l->shortName() == shortName )
3302 else if ( l->name() == shortName )
3310 bool QgsProject::unzip(
const QString &filename, QgsProject::ReadFlags flags )
3316 if ( !archive->unzip( filename ) )
3318 setError( tr(
"Unable to unzip file '%1'" ).arg( filename ) );
3323 if ( archive->projectFile().isEmpty() )
3325 setError( tr(
"Zip archive does not provide a project file" ) );
3330 if ( !archive->auxiliaryStorageFile().isEmpty() )
3334 mAuxiliaryStorage.reset(
new QgsAuxiliaryStorage( archive->auxiliaryStorageFile(),
false ) );
3342 if ( ! readProjectFile( archive->projectFile(), flags ) )
3344 setError( tr(
"Cannot read unzipped qgs project file" ) );
3349 mArchive = std::move( archive );
3350 mArchive->clearProjectFile();
3355 bool QgsProject::zip(
const QString &filename )
3361 const QString
baseName = QFileInfo( filename ).baseName();
3362 const QString qgsFileName = QStringLiteral(
"%1.qgs" ).arg(
baseName );
3363 QFile qgsFile( QDir( archive->dir() ).filePath( qgsFileName ) );
3365 bool writeOk =
false;
3366 if ( qgsFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
3368 writeOk = writeProjectFile( qgsFile.fileName() );
3375 setError( tr(
"Unable to write temporary qgs file" ) );
3380 const QFileInfo info( qgsFile );
3383 if ( ! saveAuxiliaryStorage( asFileName ) )
3385 const QString err = mAuxiliaryStorage->errorString();
3386 setError( tr(
"Unable to save auxiliary storage ('%1')" ).arg( err ) );
3391 archive->addFile( qgsFile.fileName() );
3392 archive->addFile( asFileName );
3395 if ( !archive->zip( filename ) )
3397 setError( tr(
"Unable to perform zip" ) );
3410 const QList<QgsMapLayer *> &layers,
3412 bool takeOwnership )
3414 const QList<QgsMapLayer *> myResultList { mLayerStore->addMapLayers(
layers, takeOwnership ) };
3415 if ( !myResultList.isEmpty() )
3418 for (
auto &l : myResultList )
3428 if ( mAuxiliaryStorage )
3443 mProjectScope.reset();
3445 return myResultList;
3451 bool takeOwnership )
3453 QList<QgsMapLayer *> addedLayers;
3454 addedLayers =
addMapLayers( QList<QgsMapLayer *>() << layer, addToLegend, takeOwnership );
3455 return addedLayers.isEmpty() ? nullptr : addedLayers[0];
3460 mProjectScope.reset();
3461 mLayerStore->removeMapLayers( layerIds );
3466 mProjectScope.reset();
3467 mLayerStore->removeMapLayers(
layers );
3472 mProjectScope.reset();
3473 mLayerStore->removeMapLayer( layerId );
3478 mProjectScope.reset();
3479 mLayerStore->removeMapLayer( layer );
3484 mProjectScope.reset();
3485 return mLayerStore->takeMapLayer( layer );
3490 return mMainAnnotationLayer;
3495 if ( mLayerStore->count() == 0 )
3498 ScopedIntIncrementor snapSingleBlocker( &mBlockSnappingUpdates );
3499 mProjectScope.reset();
3500 mLayerStore->removeAllMapLayers();
3502 snapSingleBlocker.release();
3504 if ( !mBlockSnappingUpdates )
3510 QMap<QString, QgsMapLayer *>
layers = mLayerStore->mapLayers();
3511 QMap<QString, QgsMapLayer *>::const_iterator it =
layers.constBegin();
3512 for ( ; it !=
layers.constEnd(); ++it )
3514 it.value()->reload();
3520 return validOnly ? mLayerStore->validMapLayers() : mLayerStore->mapLayers();
3525 return mTransactionGroups.value( qMakePair( providerKey, connString ) );
3534 if ( mSettings.
value( QStringLiteral(
"/projections/unknownCrsBehavior" ), QStringLiteral(
"NoAction" ),
QgsSettings::App ).toString() == QStringLiteral(
"UseProjectCrs" )
3535 || mSettings.
value( QStringLiteral(
"/projections/unknownCrsBehavior" ), 0,
QgsSettings::App ).toString() == 2 )
3543 QString layerDefaultCrs = mSettings.
value( QStringLiteral(
"/Projections/layerDefaultCrs" ),
geoEpsgCrsAuthId() ).toString();
3552 mTrustLayerMetadata = trust;
3555 for (
auto it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
3557 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( it.value() );
3565 bool QgsProject::saveAuxiliaryStorage(
const QString &filename )
3569 for (
auto it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
3574 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( it.value() );
3582 if ( !mAuxiliaryStorage->exists( *
this ) && filename.isEmpty() && empty )
3586 else if ( !filename.isEmpty() )
3588 return mAuxiliaryStorage->saveAs( filename );
3592 return mAuxiliaryStorage->saveAs( *
this );
3601 QgsProject::DataDefinedServerProperty::WMSOnlineResource,
3605 return sPropertyDefinitions;
3610 return mAuxiliaryStorage.get();
3615 return mAuxiliaryStorage.get();
3629 mProjectScope.reset();
3641 for ( QMap<QString, QgsMapLayer *>::const_iterator it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
3653 const QMap<QString, QgsMapLayer *> &projectLayers =
mapLayers();
3654 for ( QMap<QString, QgsMapLayer *>::const_iterator it = projectLayers.constBegin(); it != projectLayers.constEnd(); ++it )
3659 if (
layers.contains( it.value() ) )
3669 QStringList customColors;
3670 QStringList customColorLabels;
3672 QgsNamedColorList::const_iterator colorIt = colors.constBegin();
3673 for ( ; colorIt != colors.constEnd(); ++colorIt )
3676 QString label = ( *colorIt ).second;
3677 customColors.append( color );
3678 customColorLabels.append( label );
3680 writeEntry( QStringLiteral(
"Palette" ), QStringLiteral(
"/Colors" ), customColors );
3681 writeEntry( QStringLiteral(
"Palette" ), QStringLiteral(
"/Labels" ), customColorLabels );
3682 mProjectScope.reset();
3688 if ( mBackgroundColor == color )
3691 mBackgroundColor = color;
3697 return mBackgroundColor;
3702 if ( mSelectionColor == color )
3705 mSelectionColor = color;
3711 return mSelectionColor;
3745 QString
QgsProject::translate(
const QString &context,
const QString &sourceText,
const char *disambiguation,
int n )
const
3752 QString result = mTranslator->translate( context.toUtf8(), sourceText.toUtf8(), disambiguation, n );
3754 if ( result.isEmpty() )
3766 for (
auto it =
layers.constBegin(); it !=
layers.constEnd(); ++it )
3771 if ( !( ( *it )->accept( visitor ) ) )
3780 if ( !mLayoutManager->accept( visitor ) )
3783 if ( !mAnnotationManager->accept( visitor ) )
3790 GetNamedProjectColor::GetNamedProjectColor(
const QgsProject *project )
3797 QStringList colorStrings = project->
readListEntry( QStringLiteral(
"Palette" ), QStringLiteral(
"/Colors" ) );
3798 QStringList colorLabels = project->
readListEntry( QStringLiteral(
"Palette" ), QStringLiteral(
"/Labels" ) );
3802 for ( QStringList::iterator it = colorStrings.begin();
3803 it != colorStrings.end(); ++it )
3807 if ( colorLabels.length() > colorIndex )
3809 label = colorLabels.at( colorIndex );
3812 mColors.insert( label.toLower(), color );
3817 GetNamedProjectColor::GetNamedProjectColor(
const QHash<QString, QColor> &colors )
3825 QString colorName = values.at( 0 ).toString().toLower();
3826 if ( mColors.contains( colorName ) )
3828 return QStringLiteral(
"%1,%2,%3" ).arg( mColors.value( colorName ).red() ).arg( mColors.value( colorName ).green() ).arg( mColors.value( colorName ).blue() );
3836 return new GetNamedProjectColor( mColors );
static QString version()
Version string.
virtual bool readXml(const QDomElement &collectionElem, const QgsPropertiesDefinition &definitions)
Reads property collection state from an XML element.
virtual bool writeXml(QDomElement &collectionElem, const QgsPropertiesDefinition &definitions) const
Writes the current state of the property collection into an XML element.
Represents a map layer containing a set of georeferenced annotations, e.g.
void setTransformContext(const QgsCoordinateTransformContext &context) override
Sets the coordinate transform context to transformContext.
void reset()
Resets the annotation layer to a default state, and clears all items from it.
Manages storage of a set of QgsAnnotation annotation objects.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
static QgsProjectStorageRegistry * projectStorageRegistry()
Returns registry of available project storage implementations.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
void collectTranslatableObjects(QgsTranslationContext *translationContext)
Emits the signal to collect all the strings of .qgs to be included in ts file.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
void requestForTranslatableObjects(QgsTranslationContext *translationContext)
Emitted when project strings which require translation are being collected for inclusion in a ....
static QString userFullName()
Returns the user's operating system login account full display name.
static QString userLoginName()
Returns the user's operating system login account name.
QgsFields auxiliaryFields() const
Returns a list of all auxiliary fields currently managed by the layer.
bool save()
Commits changes and starts editing then.
Class providing some utility methods to manage auxiliary storage.
static QString extension()
Returns the extension used for auxiliary databases.
Manages storage of a set of bookmarks.
bool readXml(const QDomElement &element, const QDomDocument &doc)
Reads the manager's state from a DOM element, restoring all bookmarks present in the XML document.
void clear()
Removes and deletes all bookmarks from the manager.
QDomElement writeXml(QDomDocument &doc) const
Returns a DOM element representing the state of the manager.
This class represents a coordinate reference system (CRS).
static QgsCoordinateReferenceSystem fromOgcWmsCrs(const QString &ogcCrs)
Creates a CRS from a given OGC WMS-format Coordinate Reference System string.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toProj() const
Returns a Proj string representation of this CRS.
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
QString ellipsoidAcronym() const
Returns the ellipsoid acronym for the ellipsoid used by the CRS.
QString description() const
Returns the descriptive name of the CRS, e.g., "WGS 84" or "GDA 94 / Vicgrid94".
QString projectionAcronym() const
Returns the projection acronym for the projection used by the CRS.
static QgsCoordinateReferenceSystem fromProj(const QString &proj)
Creates a CRS from a proj style formatted string.
QString authid() const
Returns the authority identifier for the CRS.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
bool writeXml(QDomNode &node, QDomDocument &doc) const
Stores state to the given Dom node in the given document.
static QgsCoordinateReferenceSystem fromSrsId(long srsId)
Creates a CRS from a specified QGIS SRS ID.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
Q_GADGET QgsUnitTypes::DistanceUnit mapUnits
Contains information about the context in which a coordinate transform is executed.
void readSettings()
Reads the context's state from application settings.
void writeXml(QDomElement &element, const QgsReadWriteContext &context) const
Writes the context's state to a DOM element.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context, QStringList &missingTransforms)
Reads the context's state from a DOM element.
void setProviderProperty(ProviderProperty property, const QVariant &value)
Allows setting arbitrary properties on the provider.
@ EvaluateDefaultValues
Evaluate default values on provider side when calling QgsVectorDataProvider::defaultValue( int index ...
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
An expression node for expression functions.
Class for parsing and evaluation of expressions (formerly called "search strings").
Encapsulate a field in an attribute table or data source.
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
Container of fields for a vector layer.
bool isEmpty() const
Checks whether the container is empty.
Stores global configuration for labeling engine.
Class used to work with layer dependencies stored in a XML project or layer definition 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.
QgsLayerTreeGroup * findGroup(const QString &name)
Find group node with specified name.
QString name() const override
Returns the group's name.
QStringList findLayerIds() const
Find layer IDs used in all layer nodes.
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.
QgsLayerTreeGroup * clone() const override
Returns a clone of the group.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
QList< QgsLayerTreeGroup * > findGroups() const
Find all group layer nodes.
QgsLayerTreeLayer * findLayer(QgsMapLayer *layer) const
Find layer node representing the map layer.
Layer tree node points to a map layer.
void resolveReferences(const QgsProject *project, bool looseMatching=false) override
Resolves reference to layer from stored layer ID (if it has not been resolved already)
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...
void setCustomProperty(const QString &key, const QVariant &value)
Sets a custom property for the node. Properties are stored in a map and saved in project file.
virtual void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context)=0
Write layer tree to XML.
void removeCustomProperty(const QString &key)
Remove a custom property from layer. Properties are stored in a map and saved in project file.
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.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
void setItemVisibilityChecked(bool checked)
Check or uncheck a node (independently of its ancestors or children)
Listens to the updates in map layer registry and does changes in layer tree.
void setEnabled(bool enabled)
static void replaceChildrenOfEmbeddedGroups(QgsLayerTreeGroup *group)
Remove subtree of embedded groups and replaces it with a custom property embedded-visible-layers.
static void storeOriginalLayersProperties(QgsLayerTreeGroup *group, const QDomDocument *doc)
Stores in a layer's originalXmlProperties the layer properties information.
static void updateEmbeddedGroupsProjectPath(QgsLayerTreeGroup *group, const QgsProject *project)
Updates an embedded group from a project.
static bool readOldLegend(QgsLayerTreeGroup *root, const QDomElement &legendElem)
Try to load layer tree from.
Namespace with helper functions for layer tree operations.
void readLayerOrderFromXml(const QDomElement &doc)
Load the layer order from an XML element.
void clear()
Clear any information from this layer tree.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
QList< QgsMapLayer * > customLayerOrder() const
The order in which layers will be rendered on the canvas.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
QgsLayerTree * clone() const override
Create a copy of the node. Returns new instance.
Manages storage of a set of layouts.
static void warning(const QString &msg)
Goes to qWarning.
static QgsMapLayerType typeFromString(const QString &string, bool &ok)
Returns the map layer type corresponding a string value.
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the store.
void layerWillBeRemoved(const QString &layerId)
Emitted when a layer is about to be removed from the store.
void layersRemoved(const QStringList &layerIds)
Emitted after one or more layers were removed from the store.
void allLayersRemoved()
Emitted when all layers are removed, before layersWillBeRemoved() and layerWillBeRemoved() signals ar...
void layerRemoved(const QString &layerId)
Emitted after a layer was removed from the store.
void layerWasAdded(QgsMapLayer *layer)
Emitted when a layer was added to the store.
QgsMapLayer * mapLayer(const QString &id) const
Retrieve a pointer to a layer by layer id.
void layersAdded(const QList< QgsMapLayer * > &layers)
Emitted when one or more layers were added to the store.
Base class for all map layer types.
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
void configChanged()
Emitted whenever the configuration is changed.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
QString originalXmlProperties() const
Returns the XML properties of the original layer as they were when the layer was first read from the ...
bool writeLayerXml(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores state in DOM node.
void dataSourceChanged()
Emitted whenever the layer's data source has been changed.
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags=QgsMapLayer::ReadFlags())
Sets state from DOM document.
@ Identifiable
If the layer is identifiable using the identify map tool and as a WMS layer.
@ Removable
If the layer can be removed from the project. The layer will not be removable from the legend menu en...
@ FlagTrustLayerMetadata
Trust layer metadata. Improves layer load time by skipping expensive checks like primary key unicity,...
@ FlagDontResolveLayers
Don't resolve layer paths or create data providers for layers.
Container class that allows storage of map themes consisting of visible map layers and layer styles.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Resolves relative paths into absolute paths and vice versa.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
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.
Interface for classes that handle missing layer files when reading project file.
virtual void handleBadLayers(const QList< QDomNode > &layers)
This method will be called whenever the project tries to load layers which cannot be accessed.
Contains settings and properties relating to how a QgsProject should display values such as map coord...
void reset()
Resets the settings to a default state.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads the settings's state from a DOM element.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Returns a DOM element representing the settings.
Project property key node.
QString name() const
The name of the property is used as identifier.
QgsProjectPropertyKey * addKey(const QString &keyName)
Adds the specified property key as a sub-key.
void removeKey(const QString &keyName)
Removes the specified key.
void dump(int tabs=0) const override
Dumps out the keys and values.
bool isEmpty() const
Returns true if this property contains no sub-keys.
virtual void clearKeys()
Deletes any sub-nodes from the property.
bool writeXml(const QString &nodeName, QDomElement &element, QDomDocument &document) override
Writes the property hierarchy to a specified DOM element.
void subkeyList(QStringList &entries) const
Returns any sub-keys contained by this property which themselves contain other keys.
QgsProjectProperty * find(const QString &propertyName) const
Attempts to find a property with a matching sub-key name.
void setName(const QString &name)
The name of the property is used as identifier.
QVariant value() const override
If this key has a value, it will be stored by its name in its properties.
void entryList(QStringList &entries) const
Returns any sub-keys contained by this property that do not contain other keys.
int count() const
Returns the number of sub-keys contained by this property.
QgsProjectPropertyValue * setValue(const QString &name, const QVariant &value)
Sets the value associated with this key.
bool readXml(const QDomNode &keyNode) override
Restores the property hierarchy from a specified DOM node.
An Abstract Base Class for QGIS project property hierarchys.
virtual bool isKey() const =0
Returns true if the property is a QgsProjectPropertyKey.
virtual bool isValue() const =0
Returns true if the property is a QgsProjectPropertyValue.
QgsProjectStorage * projectStorageFromUri(const QString &uri)
Returns storage implementation if the URI matches one. Returns nullptr otherwise (it is a normal file...
Abstract interface for project storage - to be implemented by various backends and registered in QgsP...
Contains temporal settings and properties for the project, this may be used when animating maps or sh...
bool readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads the settings's state from a DOM element.
void reset()
Resets the settings to a default state.
QDomElement writeXml(QDomDocument &document, const QgsReadWriteContext &context) const
Returns a DOM element representing the settings.
A class to describe the version of a project.
QString text() const
Returns a string representation of the version.
Contains settings and properties relating to how a QgsProject should be displayed inside map canvas,...
bool useProjectScales() const
Returns true if project mapScales() are enabled.
void reset()
Resets the settings to a default state.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads the settings's state from a DOM element.
void setMapScales(const QVector< double > &scales)
Sets the list of custom project map scales.
void setUseProjectScales(bool enabled)
Sets whether project mapScales() are enabled.
QVector< double > mapScales() const
Returns the list of custom project map scales.
void mapScalesChanged()
Emitted when the list of custom project map scales changes.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Returns a DOM element representing the settings.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
bool isZipped() const
Returns true if the project comes from a zip archive, false otherwise.
QgsProject(QObject *parent=nullptr)
Create a new QgsProject.
void setAvoidIntersectionsMode(const AvoidIntersectionsMode mode)
Sets the avoid intersections mode.
QgsRelationManager * relationManager
bool write()
Writes the project to its current associated file (see fileName() ).
void removeMapLayer(const QString &layerId)
Remove a layer from the registry by layer ID.
bool evaluateDefaultValues() const
Should default values be evaluated on provider side when requested and not when committed.
void setAreaUnits(QgsUnitTypes::AreaUnit unit)
Sets the default area measurement units for the project.
void layersRemoved(const QStringList &layerIds)
Emitted after one or more layers were removed from the registry.
void clear()
Clears the project, removing all settings and resetting it back to an empty, default state.
QString error() const
Returns error message from previous read/write.
Q_DECL_DEPRECATED void setUseProjectScales(bool enabled)
Sets whether project mapScales() are enabled.
int readNumEntry(const QString &scope, const QString &key, int def=0, bool *ok=nullptr) const
Reads an integer from the specified scope and key.
Q_DECL_DEPRECATED void setNonIdentifiableLayers(const QList< QgsMapLayer * > &layers)
Set a list of layers which should not be taken into account on map identification.
QList< QgsMapLayer * > addMapLayers(const QList< QgsMapLayer * > &mapLayers, bool addToLegend=true, bool takeOwnership=true)
Add a list of layers to the map of loaded layers.
Q_DECL_DEPRECATED QFileInfo fileInfo() const
Returns QFileInfo object for the project's associated file.
QString presetHomePath() const
Returns any manual project home path setting, or an empty string if not set.
void setBackgroundColor(const QColor &color)
Sets the default background color used by default map canvases.
void setCrs(const QgsCoordinateReferenceSystem &crs, bool adjustEllipsoid=false)
Sets the project's native coordinate reference system.
QString title() const
Returns the project's title.
void mapThemeCollectionChanged()
Emitted when the map theme collection changes.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_DECL_DEPRECATED void mapScalesChanged()
Emitted when the list of custom project map scales changes.
void fileNameChanged()
Emitted when the file name of the project changes.
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
void writeMapLayer(QgsMapLayer *mapLayer, QDomElement &layerElem, QDomDocument &doc)
Emitted when a layer is being saved.
void setSnappingConfig(const QgsSnappingConfig &snappingConfig)
The snapping configuration for this project.
void setDistanceUnits(QgsUnitTypes::DistanceUnit unit)
Sets the default distance measurement units for the project.
QgsPropertyCollection dataDefinedServerProperties() const
Returns the data defined properties used for overrides in user defined server parameters.
Q_DECL_DEPRECATED void nonIdentifiableLayersChanged(QStringList nonIdentifiableLayers)
Emitted when the list of layer which are excluded from map identification changes.
void layersWillBeRemoved(const QStringList &layerIds)
Emitted when one or more layers are about to be removed from the registry.
void setSelectionColor(const QColor &color)
Sets the color used to highlight selected features.
void snappingConfigChanged(const QgsSnappingConfig &config)
Emitted whenever the configuration for snapping has changed.
QgsPathResolver pathResolver() const
Returns path resolver object with considering whether the project uses absolute or relative paths and...
void setBadLayerHandler(QgsProjectBadLayerHandler *handler)
Change handler for missing layers.
void setEvaluateDefaultValues(bool evaluateDefaultValues)
Defines if default values should be evaluated on provider side when requested and not when committed.
void crsChanged()
Emitted when the CRS of the project has changed.
QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const override
Translates the project with QTranslator and qm file.
QgsSnappingConfig snappingConfig
void setFileName(const QString &name)
Sets the file name associated with the project.
QgsUnitTypes::AreaUnit areaUnits() const
Convenience function to query default area measurement units for project.
void avoidIntersectionsLayersChanged()
Emitted whenever avoidIntersectionsLayers has changed.
void setDataDefinedServerProperties(const QgsPropertyCollection &properties)
Sets the data defined properties used for overrides in user defined server parameters to properties.
void registerTranslatableObjects(QgsTranslationContext *translationContext)
Registers the objects that require translation into the translationContext.
QgsAnnotationLayer * mainAnnotationLayer()
Returns the main annotation layer associated with the project.
const QgsBookmarkManager * bookmarkManager() const
Returns the project's bookmark manager, which manages bookmarks within the project.
void readMapLayer(QgsMapLayer *mapLayer, const QDomElement &layerNode)
Emitted after the basic initialization of a layer from the project file is done.
void setAutoTransaction(bool autoTransaction)
Transactional editing means that on supported datasources (postgres databases) the edit state of all ...
void setTrustLayerMetadata(bool trust)
Sets the trust option allowing to indicate if the extent has to be read from the XML document when da...
void cleared()
Emitted when the project is cleared (and additionally when an open project is cleared just before a n...
void setLabelingEngineSettings(const QgsLabelingEngineSettings &settings)
Sets project's global labeling engine settings.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
void metadataChanged()
Emitted when the project's metadata is changed.
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
QString absolutePath() const
Returns full absolute path to the project folder if the project is stored in a file system - derived ...
void removeMapLayers(const QStringList &layerIds)
Remove a set of layers from the registry by layer ID.
Q_DECL_DEPRECATED void setRequiredLayers(const QSet< QgsMapLayer * > &layers)
Configures a set of map layers that are required in the project and therefore they should not get rem...
QList< QgsVectorLayer * > avoidIntersectionsLayers
QString readEntry(const QString &scope, const QString &key, const QString &def=QString(), bool *ok=nullptr) const
Reads a string from the specified scope and key.
AvoidIntersectionsMode
Flags which control how intersections of pre-existing feature are handled when digitizing new feature...
@ AvoidIntersectionsLayers
Overlap with features from a specified list of layers when digitizing new features not allowed.
@ AllowIntersections
Overlap with any feature allowed when digitizing new features.
QgsExpressionContextScope * createExpressionContextScope() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QString baseName() const
Returns the base name of the project file without the path and without extension - derived from fileN...
void ellipsoidChanged(const QString &ellipsoid)
Emitted when the project ellipsoid is changed.
QgsMapThemeCollection * mapThemeCollection
void generateTsFile(const QString &locale)
Triggers the collection strings of .qgs to be included in ts file and calls writeTsFile()
QStringList entryList(const QString &scope, const QString &key) const
Returns a list of child keys with values which exist within the the specified scope and key.
QgsAnnotationManager * annotationManager()
Returns pointer to the project's annotation manager.
QgsProjectMetadata metadata
void projectColorsChanged()
Emitted whenever the project's color scheme has been changed.
QgsUnitTypes::DistanceUnit distanceUnits() const
Convenience function to query default distance measurement units for project.
QString saveUser() const
Returns the user name that did the last save.
void setProjectColors(const QgsNamedColorList &colors)
Sets the colors for the project's color scheme (see QgsProjectColorScheme).
QgsCoordinateTransformContext transformContext
void labelingEngineSettingsChanged()
Emitted when global configuration of the labeling engine changes.
void customVariablesChanged()
Emitted whenever the expression variables stored in the project have been changed.
QgsLayerTree * layerTreeRoot() const
Returns pointer to the root (invisible) node of the project's layer tree.
bool readBoolEntry(const QString &scope, const QString &key, bool def=false, bool *ok=nullptr) const
Reads a boolean from the specified scope and key.
QgsMapLayerStore * layerStore()
Returns a pointer to the project's internal layer store.
void readProject(const QDomDocument &)
Emitted when a project is being read.
QString originalPath() const
Returns the original path associated with the project.
void setOriginalPath(const QString &path)
Sets the original path associated with the project.
void dumpProperties() const
Dump out current project properties to stderr.
static void setInstance(QgsProject *project)
Set the current project singleton instance to project.
int validCount() const
Returns the number of registered valid layers.
const QgsLayoutManager * layoutManager() const
Returns the project's layout manager, which manages print layouts, atlases and reports within the pro...
QList< QgsMapLayer * > mapLayersByName(const QString &layerName) const
Retrieve a list of matching registered layers by layer name.
bool autoTransaction() const
Transactional editing means that on supported datasources (postgres databases) the edit state of all ...
bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified style entity visitor, causing it to visit all style entities associated with th...
void setMetadata(const QgsProjectMetadata &metadata)
Sets the project's metadata store.
void missingDatumTransforms(const QStringList &missingTransforms)
Emitted when datum transforms stored in the project are not available locally.
QgsTransactionGroup * transactionGroup(const QString &providerKey, const QString &connString)
Returns the matching transaction group from a provider key and connection string.
QgsCoordinateReferenceSystem crs
void readProjectWithContext(const QDomDocument &, QgsReadWriteContext &context)
Emitted when a project is being read.
QgsMapLayer * addMapLayer(QgsMapLayer *mapLayer, bool addToLegend=true, bool takeOwnership=true)
Add a layer to the map of loaded layers.
QStringList nonIdentifiableLayers
void transactionGroupsChanged()
Emitted whenever a new transaction group has been created or a transaction group has been removed.
const QgsAuxiliaryStorage * auxiliaryStorage() const
Returns the current const auxiliary storage.
void reloadAllLayers()
Reload all registered layer's provider data caches, synchronising the layer with any changes in the d...
int count() const
Returns the number of registered layers.
void loadingLayerMessageReceived(const QString &layerName, const QList< QgsReadWriteContext::ReadWriteMessage > &messages)
Emitted when loading layers has produced some messages.
void setTitle(const QString &title)
Sets the project's title.
QMap< QPair< QString, QString >, QgsTransactionGroup * > transactionGroups()
Map of transaction groups.
void writeProject(QDomDocument &)
Emitted when the project is being written.
QDateTime lastModified() const
Returns last modified time of the project file as returned by the file system (or other project stora...
bool readLayer(const QDomNode &layerNode)
Reads the layer described in the associated DOM node.
double readDoubleEntry(const QString &scope, const QString &key, double def=0, bool *ok=nullptr) const
Reads a double from the specified scope and key.
bool writeEntry(const QString &scope, const QString &key, bool value)
Write a boolean value to the project file.
QgsLayerTreeGroup * createEmbeddedGroup(const QString &groupName, const QString &projectFilePath, const QStringList &invisibleLayers, QgsProject::ReadFlags flags=QgsProject::ReadFlags())
Create layer group instance defined in an arbitrary project file.
QString absoluteFilePath() const
Returns full absolute path to the project file if the project is stored in a file system - derived fr...
QDateTime lastSaveDateTime() const
Returns the date and time when the project was last saved.
void projectSaved()
Emitted when the project file has been written and closed.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
void setEllipsoid(const QString &ellipsoid)
Sets the project's ellipsoid from a proj string representation, e.g., "WGS84".
bool read(const QString &filename, QgsProject::ReadFlags flags=QgsProject::ReadFlags())
Reads given project file from the given file.
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the project's coordinate transform context, which stores various information regarding which dat...
void layerLoaded(int i, int n)
Emitted when a layer from a projects was read.
QStringList subkeyList(const QString &scope, const QString &key) const
Returns a list of child keys which contain other keys that exist within the the specified scope and k...
QStringList readListEntry(const QString &scope, const QString &key, const QStringList &def=QStringList(), bool *ok=nullptr) const
Reads a string list from the specified scope and key.
void selectionColorChanged()
Emitted whenever the project's selection color has been changed.
bool createEmbeddedLayer(const QString &layerId, const QString &projectFilePath, QList< QDomNode > &brokenNodes, bool saveFlag=true, QgsProject::ReadFlags flags=QgsProject::ReadFlags())
Creates a maplayer instance defined in an arbitrary project file.
const QgsLabelingEngineSettings & labelingEngineSettings() const
Returns project's global labeling engine settings.
void removeAllMapLayers()
Removes all registered layers.
Q_DECL_DEPRECATED QVector< double > mapScales() const
Returns the list of custom project map scales.
void setDirty(bool b=true)
Flag the project as dirty (modified).
void backgroundColorChanged()
Emitted whenever the project's canvas background color has been changed.
@ FlagTrustLayerMetadata
Trust layer metadata. Improves project read time. Do not use it if layers' extent is not fixed during...
@ FlagDontStoreOriginalStyles
Skip the initial XML style storage for layers. Useful for minimising project load times in non-intera...
@ FlagDontLoadLayouts
Don't load print layouts. Improves project read time if layouts are not required, and allows projects...
@ FlagDontResolveLayers
Don't resolve layer paths (i.e. don't load any layer content). Dramatically improves project read tim...
const QgsProjectViewSettings * viewSettings() const
Returns the project's view settings, which contains settings and properties relating to how a QgsProj...
QString readPath(const QString &filename) const
Transforms a filename read from the project file to an absolute path.
void registerTranslatableContainers(QgsTranslationContext *translationContext, QgsAttributeEditorContainer *parent, const QString &layerId)
Registers the containers that require translation into the translationContext.
void oldProjectVersionWarning(const QString &)
Emitted when an old project file is read.
Q_DECL_DEPRECATED QSet< QgsMapLayer * > requiredLayers() const
Returns a set of map layers that are required in the project and therefore they should not get remove...
void transformContextChanged()
Emitted when the project transformContext() is changed.
void setTopologicalEditing(bool enabled)
Convenience function to set topological editing.
void legendLayersAdded(const QList< QgsMapLayer * > &layers)
Emitted, when a layer was added to the registry and the legend.
QVariantMap customVariables() const
A map of custom project variables.
void setAvoidIntersectionsLayers(const QList< QgsVectorLayer * > &layers)
Sets the list of layers with which intersections should be avoided.
void homePathChanged()
Emitted when the home path of the project changes.
void setCustomVariables(const QVariantMap &customVariables)
A map of custom project variables.
QgsCoordinateReferenceSystem defaultCrsForNewLayers() const
Returns the default CRS for new layers based on the settings and the current project CRS.
const QgsProjectDisplaySettings * displaySettings() const
Returns the project's display settings, which settings and properties relating to how a QgsProject sh...
QString saveUserFullName() const
Returns the full user name that did the last save.
void layersAdded(const QList< QgsMapLayer * > &layers)
Emitted when one or more layers were added to the registry.
QMap< QString, QgsMapLayer * > mapLayers(const bool validOnly=false) const
Returns a map of all registered layers by layer ID.
bool isDirty() const
Returns true if the project has been modified since the last write()
QgsMapLayer * takeMapLayer(QgsMapLayer *layer)
Takes a layer from the registry.
void isDirtyChanged(bool dirty)
Emitted when the project dirty status changes.
Q_DECL_DEPRECATED bool useProjectScales() const
Returns true if project mapScales() are enabled.
Q_DECL_DEPRECATED void setMapScales(const QVector< double > &scales)
Sets the list of custom project map scales.
void setPresetHomePath(const QString &path)
Sets the project's home path.
QList< QgsMapLayer * > mapLayersByShortName(const QString &shortName) const
Retrieves a list of matching registered layers by layer shortName.
QgsProjectStorage * projectStorage() const
Returns pointer to project storage implementation that handles read/write of the project file.
QString layerIsEmbedded(const QString &id) const
Returns the source project file path if the layer with matching id is embedded from other project fil...
const QgsProjectTimeSettings * timeSettings() const
Returns the project's time settings, which contains the project's temporal range and other time based...
void topologicalEditingChanged()
Emitted when the topological editing flag has changed.
bool removeEntry(const QString &scope, const QString &key)
Remove the given key from the specified scope.
QgsProjectVersion lastSaveVersion() const
Returns the QGIS version which the project was last saved using.
void avoidIntersectionsModeChanged()
Emitted whenever the avoid intersections mode has changed.
void loadingLayer(const QString &layerName)
Emitted when a layer is loaded.
A grouped map of multiple QgsProperty objects, each referenced by a integer key value.
Definition for a property.
@ String
Any string value.
The class is used as a container of context for various read/write operations on other objects.
void setTransformContext(const QgsCoordinateTransformContext &transformContext)
Sets data coordinate transform context to transformContext.
QList< QgsReadWriteContext::ReadWriteMessage > takeMessages()
Returns the stored messages and remove them.
void setProjectTranslator(QgsProjectTranslator *projectTranslator)
Sets the project translator.
void setPathResolver(const QgsPathResolver &resolver)
Sets up path resolver for conversion between relative and absolute paths.
This class manages a set of relations between layers.
void clear()
Remove any relation managed by this class.
void updateRelationsStatus()
Updates relations status.
QMap< QString, QgsRelation > relations() const
Gets access to the relations managed by this class.
void clear(const QString &group="startup")
clear Clear all profile data.
Expression function for use within a QgsExpressionContextScope.
Scoped object for logging of the runtime for a single operation or group of operations.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
This is a container for configuration of the snapping of the project.
bool addLayers(const QList< QgsMapLayer * > &layers)
Adds the specified layers as individual layers to the configuration with standard configuration.
void readProject(const QDomDocument &doc)
Reads the configuration from the specified QGIS project document.
void reset()
reset to default values
void writeProject(QDomDocument &doc)
Writes the configuration to the specified QGIS project document.
void clearIndividualLayerSettings()
Removes all individual layer snapping settings.
bool removeLayers(const QList< QgsMapLayer * > &layers)
Removes the specified layers from the individual layer configuration.
An interface for classes which can visit style entity (e.g.
virtual bool visitExit(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor stops visiting a node.
virtual bool visitEnter(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor starts visiting a node.
static QColor decodeColor(const QString &str)
static QString encodeColor(const QColor &color)
bool isEmpty() const
Returns true if there are no layers in this transaction group.
bool addLayer(QgsVectorLayer *layer)
Add a layer to this transaction group.
static bool supportsTransaction(const QgsVectorLayer *layer)
Checks if the provider of a given layer supports transactions.
Used for the collecting of strings from projects for translation and creation of ts files.
void registerTranslation(const QString &context, const QString &source)
Registers the source to be translated.
void writeTsFile(const QString &locale)
Writes the Ts-file.
void setFileName(const QString &fileName)
Sets the fileName of the TS file.
void setProject(QgsProject *project)
Sets the project being translated.
DistanceUnit
Units of distance.
static Q_INVOKABLE QString encodeUnit(QgsUnitTypes::DistanceUnit unit)
Encodes a distance unit to a string.
static Q_INVOKABLE QgsUnitTypes::DistanceUnit decodeDistanceUnit(const QString &string, bool *ok=nullptr)
Decodes a distance unit from a string.
static Q_INVOKABLE QString toString(QgsUnitTypes::DistanceUnit unit)
Returns a translated string representing a distance unit.
static Q_INVOKABLE QgsUnitTypes::AreaUnit decodeAreaUnit(const QString &string, bool *ok=nullptr)
Decodes an areal unit from a string.
@ AreaSquareMeters
Square meters.
Represents a vector layer which manages a vector based data sets.
bool loadAuxiliaryLayer(const QgsAuxiliaryStorage &storage, const QString &key=QString())
Loads the auxiliary layer for this vector layer.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
void setReadExtentFromXml(bool readExtentFromXml)
Flag allowing to indicate if the extent has to be read from the XML document when data source has no ...
QgsEditFormConfig editFormConfig
QList< QPair< QColor, QString > > QgsNamedColorList
List of colors paired with a friendly display name identifying the color.
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.
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.
CONSTLATIN1STRING geoNone()
Constant that holds the string representation for "No ellips/No CRS".
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
CONSTLATIN1STRING geoEpsgCrsAuthId()
Geographic coord sys from EPSG authority.
#define QgsDebugMsgLevel(str, level)
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
void _getProperties(const QDomDocument &doc, QgsProjectPropertyKey &project_properties)
Restore any optional properties found in "doc" to "properties".
QgsPropertyCollection getDataDefinedServerProperties(const QDomDocument &doc, const QgsPropertiesDefinition &dataDefinedServerPropertyDefinitions)
Returns the data defined server properties collection found in "doc" to "dataDefinedServerProperties"...
QgsProjectProperty * findKey_(const QString &scope, const QString &key, QgsProjectPropertyKey &rootProperty)
return the property that matches the given key sequence, if any
void removeKey_(const QString &scope, const QString &key, QgsProjectPropertyKey &rootProperty)
Remove a given key.
QgsProjectProperty * addKey_(const QString &scope, const QString &key, QgsProjectPropertyKey *rootProperty, const QVariant &value, bool &propertiesModified)
Add the given key and value.
QgsProjectVersion getVersion(const QDomDocument &doc)
Returns the version string found in the given DOM document.
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...
void dump_(const QgsProjectPropertyKey &topQgsPropertyKey)
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.
const QgsCoordinateReferenceSystem & crs
Setting options for loading annotation layers.
Single variable definition for use within a QgsExpressionContextScope.
Contains information relating to a node (i.e.