QGIS API Documentation 4.1.0-Master (3b8ef1f72a3)
Loading...
Searching...
No Matches
qgsmaplayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmaplayer.cpp - description
3 -------------------
4 begin : Fri Jun 28 2002
5 copyright : (C) 2002 by Gary E.Sherman
6 email : sherman at mrcc.com
7***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18
19#include "qgsmaplayer.h"
20
21#include <sqlite3.h>
22
25#include "qgsapplication.h"
26#include "qgsauthmanager.h"
29#include "qgsdatasourceuri.h"
30#include "qgsdatums.h"
31#include "qgsfileutils.h"
32#include "qgslayernotesutils.h"
33#include "qgslogger.h"
35#include "qgsmaplayerlegend.h"
38#include "qgsmessagelog.h"
39#include "qgsobjectvisitor.h"
40#include "qgspathresolver.h"
41#include "qgsproject.h"
43#include "qgsprojoperation.h"
44#include "qgsprovidermetadata.h"
45#include "qgsproviderregistry.h"
46#include "qgsrasterlayer.h"
47#include "qgsreadwritecontext.h"
48#include "qgsrectangle.h"
49#include "qgsscaleutils.h"
50#include "qgssldexportcontext.h"
51#include "qgssqliteutils.h"
52#include "qgsstringutils.h"
53#include "qgsthreadingutils.h"
54#include "qgsunittypes.h"
55#include "qgsvectorlayer.h"
56#include "qgsxmlutils.h"
57
58#include <QDir>
59#include <QDomDocument>
60#include <QDomElement>
61#include <QDomImplementation>
62#include <QDomNode>
63#include <QFile>
64#include <QFileInfo>
65#include <QLocale>
66#include <QRegularExpression>
67#include <QStandardPaths>
68#include <QString>
69#include <QTextStream>
70#include <QTimer>
71#include <QUrl>
72#include <QUuid>
73#include <QXmlStreamReader>
74
75#include "moc_qgsmaplayer.cpp"
76
77using namespace Qt::StringLiterals;
78
80{
81 switch ( type )
82 {
83 case Metadata:
84 return u".qmd"_s;
85
86 case Style:
87 return u".qml"_s;
88 }
89 return QString();
90}
91
92QgsMapLayer::QgsMapLayer( Qgis::LayerType type, const QString &lyrname, const QString &source )
94 , mLayerName( lyrname )
95 , mLayerType( type )
96 , mServerProperties( std::make_unique<QgsMapLayerServerProperties>( this ) )
97 , mUndoStack( new QUndoStack( this ) )
98 , mUndoStackStyles( new QUndoStack( this ) )
99 , mStyleManager( std::make_unique<QgsMapLayerStyleManager>( this ) )
100 , mRefreshTimer( new QTimer( this ) )
101{
102 mID = generateId( lyrname );
103 connect( this, &QgsMapLayer::crsChanged, this, &QgsMapLayer::configChanged );
105 connect( mRefreshTimer, &QTimer::timeout, this, [this] {
106 switch ( mAutoRefreshMode )
107 {
109 break;
111 triggerRepaint( true );
112 break;
114 reload();
115 break;
116 }
117 } );
118}
119
121{
122 if ( project() && project()->pathResolver().writePath( mDataSource ).startsWith( "attachment:" ) )
123 {
125 }
126}
127
128void QgsMapLayer::clone( QgsMapLayer *layer ) const
129{
131
132 QgsDebugMsgLevel( u"Cloning layer '%1'"_s.arg( name() ), 3 );
133 layer->setBlendMode( blendMode() );
134
135 const auto constStyles = styleManager()->styles();
136 for ( const QString &s : constStyles )
137 {
138 layer->styleManager()->addStyle( s, styleManager()->style( s ) );
139 }
140
141 layer->setName( name() );
142
143 if ( layer->dataProvider() && layer->dataProvider()->elevationProperties() )
144 {
146 layer->mExtent3D = mExtent3D;
147 else
148 layer->mExtent2D = mExtent2D;
149 }
150
151 layer->setMaximumScale( maximumScale() );
152 layer->setMinimumScale( minimumScale() );
154 layer->setDependencies( dependencies() );
156 layer->setCrs( crs() );
157 layer->setCustomProperties( mCustomProperties );
158 layer->setOpacity( mLayerOpacity );
159 layer->setMetadata( mMetadata );
160 layer->serverProperties()->copyTo( mServerProperties.get() );
161}
162
164{
165 // because QgsVirtualLayerProvider is not anywhere NEAR thread safe:
167
168 return mLayerType;
169}
170
177
179{
181
182 if ( flags == mFlags )
183 return;
184
185 mFlags = flags;
186 emit flagsChanged();
187}
188
195
196QString QgsMapLayer::id() const
197{
198 // because QgsVirtualLayerProvider is not anywhere NEAR thread safe:
200
201 return mID;
202}
203
204bool QgsMapLayer::setId( const QString &id )
205{
207 if ( qobject_cast< QgsMapLayerStore * >( parent() ) )
208 {
209 // layer is already registered, cannot change id
210 return false;
211 }
212
213 if ( id == mID )
214 return false;
215
216 mID = id;
217 emit idChanged( id );
218 return true;
219}
220
221void QgsMapLayer::setName( const QString &name )
222{
224
225 if ( name == mLayerName )
226 return;
227
229
230 emit nameChanged();
231}
232
233QString QgsMapLayer::name() const
234{
235 // because QgsVirtualLayerProvider is not anywhere NEAR thread safe:
237
238 QgsDebugMsgLevel( "returning name '" + mLayerName + '\'', 4 );
239 return mLayerName;
240}
241
248
250{
252
253 return nullptr;
254}
255
260
262{
264
265 mServerProperties->setShortName( shortName );
266}
267
269{
271
272 return mServerProperties->shortName();
273}
274
275void QgsMapLayer::setTitle( const QString &title )
276{
278
279 mServerProperties->setTitle( title );
280}
281
282QString QgsMapLayer::title() const
283{
285
286 return mServerProperties->title();
287}
288
289void QgsMapLayer::setAbstract( const QString &abstract )
290{
292
293 mServerProperties->setAbstract( abstract );
294}
295
297{
299
300 return mServerProperties->abstract();
301}
302
303void QgsMapLayer::setKeywordList( const QString &keywords )
304{
306
307 mServerProperties->setKeywordList( keywords );
308}
309
311{
313
314 return mServerProperties->keywordList();
315}
316
317void QgsMapLayer::setDataUrl( const QString &dataUrl )
318{
320
321 mServerProperties->setDataUrl( dataUrl );
322}
323
324QString QgsMapLayer::dataUrl() const
325{
327
328 return mServerProperties->dataUrl();
329}
330
332{
334
335 mServerProperties->setDataUrlFormat( dataUrlFormat );
336}
337
339{
341
342 return mServerProperties->dataUrlFormat();
343}
344
345void QgsMapLayer::setAttribution( const QString &attrib )
346{
348
349 mServerProperties->setAttribution( attrib );
350}
351
353{
355
356 return mServerProperties->attribution();
357}
358
359void QgsMapLayer::setAttributionUrl( const QString &attribUrl )
360{
362
363 mServerProperties->setAttributionUrl( attribUrl );
364}
365
367{
369
370 return mServerProperties->attributionUrl();
371}
372
374{
376
377 mServerProperties->setLegendUrl( legendUrl );
378}
379
381{
383
384 return mServerProperties->legendUrl();
385}
386
388{
390
391 mServerProperties->setLegendUrlFormat( legendUrlFormat );
392}
393
395{
397
398 return mServerProperties->legendUrlFormat();
399}
400
401void QgsMapLayer::setMetadataUrl( const QString &metaUrl )
402{
404
405 QList<QgsMapLayerServerProperties::MetadataUrl> urls = serverProperties()->metadataUrls();
406 if ( urls.isEmpty() )
407 {
408 const QgsMapLayerServerProperties::MetadataUrl newItem = QgsMapLayerServerProperties::MetadataUrl( metaUrl, QLatin1String(), QLatin1String() );
409 urls.prepend( newItem );
410 }
411 else
412 {
413 const QgsMapLayerServerProperties::MetadataUrl old = urls.takeFirst();
414 const QgsMapLayerServerProperties::MetadataUrl newItem( metaUrl, old.type, old.format );
415 urls.prepend( newItem );
416 }
418}
419
421{
423
424 if ( mServerProperties->metadataUrls().isEmpty() )
425 {
426 return QLatin1String();
427 }
428 else
429 {
430 return mServerProperties->metadataUrls().first().url;
431 }
432}
433
434void QgsMapLayer::setMetadataUrlType( const QString &metaUrlType )
435{
437
438 QList<QgsMapLayerServerProperties::MetadataUrl> urls = mServerProperties->metadataUrls();
439 if ( urls.isEmpty() )
440 {
441 const QgsMapLayerServerProperties::MetadataUrl newItem( QLatin1String(), metaUrlType, QLatin1String() );
442 urls.prepend( newItem );
443 }
444 else
445 {
446 const QgsMapLayerServerProperties::MetadataUrl old = urls.takeFirst();
447 const QgsMapLayerServerProperties::MetadataUrl newItem( old.url, metaUrlType, old.format );
448 urls.prepend( newItem );
449 }
450 mServerProperties->setMetadataUrls( urls );
451}
452
454{
456
457 if ( mServerProperties->metadataUrls().isEmpty() )
458 {
459 return QLatin1String();
460 }
461 else
462 {
463 return mServerProperties->metadataUrls().first().type;
464 }
465}
466
467void QgsMapLayer::setMetadataUrlFormat( const QString &metaUrlFormat )
468{
470
471 QList<QgsMapLayerServerProperties::MetadataUrl> urls = mServerProperties->metadataUrls();
472 if ( urls.isEmpty() )
473 {
474 const QgsMapLayerServerProperties::MetadataUrl newItem( QLatin1String(), QLatin1String(), metaUrlFormat );
475 urls.prepend( newItem );
476 }
477 else
478 {
479 const QgsMapLayerServerProperties::MetadataUrl old = urls.takeFirst();
480 const QgsMapLayerServerProperties::MetadataUrl newItem( old.url, old.type, metaUrlFormat );
481 urls.prepend( newItem );
482 }
483 mServerProperties->setMetadataUrls( urls );
484}
485
487{
489
490 if ( mServerProperties->metadataUrls().isEmpty() )
491 {
492 return QString();
493 }
494 else
495 {
496 return mServerProperties->metadataUrls().first().format;
497 }
498}
499
500QString QgsMapLayer::publicSource( bool redactCredentials ) const
501{
503
504 // Redo this every time we're asked for it, as we don't know if
505 // dataSource has changed.
507 {
509 }
510 else
511 {
512 return QgsDataSourceUri::removePassword( mDataSource, redactCredentials );
513 }
514}
515
516QString QgsMapLayer::source() const
517{
519
520 return mDataSource;
521}
522
524{
526
527 return mExtent2D.isNull() ? mExtent3D.toRectangle() : mExtent2D;
528}
529
531{
533
534 return mExtent3D;
535}
536
537void QgsMapLayer::setBlendMode( const QPainter::CompositionMode blendMode )
538{
540
541 if ( mBlendMode == blendMode )
542 return;
543
544 mBlendMode = blendMode;
547}
548
549QPainter::CompositionMode QgsMapLayer::blendMode() const
550{
551 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
553
554 return mBlendMode;
555}
556
567
569{
570 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
572
573 return mLayerOpacity;
574}
575
576bool QgsMapLayer::readLayerXml( const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags, QgsDataProvider *preloadedProvider )
577{
579
580 mPreloadedProvider.reset( preloadedProvider );
581 if ( mPreloadedProvider )
582 {
584 }
585
586 bool layerError;
588
589 QDomNode mnl;
590 QDomElement mne;
591
592 // read provider
593 QString provider;
594 mnl = layerElement.namedItem( u"provider"_s );
595 mne = mnl.toElement();
596 provider = mne.text();
597
598 // set data source
599 mnl = layerElement.namedItem( u"datasource"_s );
600 mne = mnl.toElement();
601 const QString dataSourceRaw = mne.text();
602
603 // if the layer needs authentication, ensure the master password is set
604 const thread_local QRegularExpression rx( "authcfg=([a-z]|[A-Z]|[0-9]){7}" );
605 if ( rx.match( dataSourceRaw ).hasMatch() && !QgsApplication::authManager()->setMasterPassword( true ) )
606 {
607 return false;
608 }
609
610 mDataSource = decodedSource( dataSourceRaw, provider, context );
611
612 // Set the CRS from project file, asking the user if necessary.
613 // Make it the saved CRS to have WMS layer projected correctly.
614 // We will still overwrite whatever GDAL etc picks up anyway
615 // further down this function.
616 mnl = layerElement.namedItem( u"layername"_s );
617 mne = mnl.toElement();
618
620 CUSTOM_CRS_VALIDATION savedValidation;
621
622 const QDomNode srsNode = layerElement.namedItem( u"srs"_s );
623 mCRS.readXml( srsNode );
624 mCRS.setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
626 mCRS.validate();
627 savedCRS = mCRS;
628
629 // Do not validate any projections in children, they will be overwritten anyway.
630 // No need to ask the user for a projections when it is overwritten, is there?
633
634 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "Layer" ), mne.text() );
635
636 // the internal name is just the data source basename
637 //QFileInfo dataSourceFileInfo( mDataSource );
638 //internalName = dataSourceFileInfo.baseName();
639
640 // set ID
641 mnl = layerElement.namedItem( u"id"_s );
642 if ( !mnl.isNull() )
643 {
644 mne = mnl.toElement();
645 if ( !mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
646 {
647 const QString newId = mne.text();
648 if ( newId != mID )
649 {
650 mID = mne.text();
651 emit idChanged( mID );
652 }
653 }
654 }
655
656 // set name
657 mnl = layerElement.namedItem( u"layername"_s );
658 mne = mnl.toElement();
659
660 //name can be translated
661 setName( context.projectTranslator()->translate( u"project:layers:%1"_s.arg( layerElement.namedItem( u"id"_s ).toElement().text() ), mne.text() ) );
662
663 // now let the children grab what they need from the Dom node.
664 layerError = !readXml( layerElement, context );
665
666 const QgsCoordinateReferenceSystem oldVerticalCrs = verticalCrs();
667 const QgsCoordinateReferenceSystem oldCrs3D = mCrs3D;
668
669 // overwrite CRS with what we read from project file before the raster/vector
670 // file reading functions changed it. They will if projections is specified in the file.
671 // FIXME: is this necessary? Yes, it is (autumn 2019)
673 mCRS = savedCRS;
674
675 //vertical CRS
676 {
678 const QDomNode verticalCrsNode = layerElement.firstChildElement( u"verticalCrs"_s );
679 if ( !verticalCrsNode.isNull() )
680 {
681 verticalCrs.readXml( verticalCrsNode );
682 }
683 mVerticalCrs = verticalCrs;
684 }
685 rebuildCrs3D();
686
687 serverProperties()->readXml( layerElement );
688
689 // mMetadata.readFromLayer( this );
690 const QDomElement metadataElem = layerElement.firstChildElement( u"resourceMetadata"_s );
691 mMetadata.readMetadataXml( metadataElem, context );
692
693 setAutoRefreshInterval( layerElement.attribute( u"autoRefreshTime"_s, u"0"_s ).toInt() );
694 if ( layerElement.hasAttribute( u"autoRefreshMode"_s ) )
695 {
696 setAutoRefreshMode( qgsEnumKeyToValue( layerElement.attribute( u"autoRefreshMode"_s ), Qgis::AutoRefreshMode::Disabled ) );
697 }
698 else
699 {
700 setAutoRefreshMode( layerElement.attribute( u"autoRefreshEnabled"_s, u"0"_s ).toInt() ? Qgis::AutoRefreshMode::RedrawOnly : Qgis::AutoRefreshMode::Disabled );
701 }
702 setRefreshOnNofifyMessage( layerElement.attribute( u"refreshOnNotifyMessage"_s, QString() ) );
703 setRefreshOnNotifyEnabled( layerElement.attribute( u"refreshOnNotifyEnabled"_s, u"0"_s ).toInt() );
704
705 // geographic extent is read only if necessary
707 {
708 const QDomNode wgs84ExtentNode = layerElement.namedItem( u"wgs84extent"_s );
709 if ( !wgs84ExtentNode.isNull() )
710 mWgs84Extent = QgsXmlUtils::readRectangle( wgs84ExtentNode.toElement() );
711 }
712
713 mLegendPlaceholderImage = layerElement.attribute( u"legendPlaceholderImage"_s );
714
715 if ( verticalCrs() != oldVerticalCrs )
716 emit verticalCrsChanged();
717 if ( mCrs3D != oldCrs3D )
718 emit crs3DChanged();
719
720 return !layerError;
721} // bool QgsMapLayer::readLayerXML
722
723
724bool QgsMapLayer::readXml( const QDomNode &layer_node, QgsReadWriteContext &context )
725{
727
728 Q_UNUSED( layer_node )
729 Q_UNUSED( context )
730 // NOP by default; children will over-ride with behavior specific to them
731
732 // read Extent
734 {
735 const QDomNode extent3DNode = layer_node.namedItem( u"extent3D"_s );
736 if ( extent3DNode.isNull() )
737 {
738 const QDomNode extentNode = layer_node.namedItem( u"extent"_s );
739 if ( !extentNode.isNull() )
740 {
741 mExtent2D = QgsXmlUtils::readRectangle( extentNode.toElement() );
742 }
743 }
744 else
745 {
746 mExtent3D = QgsXmlUtils::readBox3D( extent3DNode.toElement() );
747 }
748 }
749
750 return true;
751} // void QgsMapLayer::readXml
752
753
754bool QgsMapLayer::writeLayerXml( QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context ) const
755{
757
758 if ( !mExtent3D.isNull() && dataProvider() && dataProvider()->elevationProperties() && dataProvider()->elevationProperties()->containsElevationData() )
759 layerElement.appendChild( QgsXmlUtils::writeBox3D( mExtent3D, document ) );
760 else
761 {
762 // Extent might be null because lazily set
763 const QgsRectangle extent2D { mExtent2D.isNull() ? extent() : mExtent2D };
764 if ( !extent2D.isNull() )
765 {
766 layerElement.appendChild( QgsXmlUtils::writeRectangle( extent2D, document ) );
767 }
768 }
769
770 if ( const QgsRectangle lWgs84Extent = wgs84Extent( true ); !lWgs84Extent.isNull() )
771 {
772 layerElement.appendChild( QgsXmlUtils::writeRectangle( lWgs84Extent, document, u"wgs84extent"_s ) );
773 }
774
775 layerElement.setAttribute( u"autoRefreshTime"_s, QString::number( mRefreshTimer->interval() ) );
776 layerElement.setAttribute( u"autoRefreshMode"_s, qgsEnumValueToKey( mAutoRefreshMode ) );
777 layerElement.setAttribute( u"refreshOnNotifyEnabled"_s, mIsRefreshOnNofifyEnabled ? 1 : 0 );
778 layerElement.setAttribute( u"refreshOnNotifyMessage"_s, mRefreshOnNofifyMessage );
779
780 // ID
781 QDomElement layerId = document.createElement( u"id"_s );
782 const QDomText layerIdText = document.createTextNode( id() );
783 layerId.appendChild( layerIdText );
784
785 layerElement.appendChild( layerId );
786
787 if ( mVerticalCrs.isValid() )
788 {
789 QDomElement verticalSrsNode = document.createElement( u"verticalCrs"_s );
790 mVerticalCrs.writeXml( verticalSrsNode, document );
791 layerElement.appendChild( verticalSrsNode );
792 }
793
794 // data source
795 QDomElement dataSource = document.createElement( u"datasource"_s );
796 const QString src = encodedSource( source(), context );
797 const QDomText dataSourceText = document.createTextNode( src );
798 dataSource.appendChild( dataSourceText );
799 layerElement.appendChild( dataSource );
800
801 // layer name
802 QDomElement layerName = document.createElement( u"layername"_s );
803 const QDomText layerNameText = document.createTextNode( name() );
804 layerName.appendChild( layerNameText );
805 layerElement.appendChild( layerName );
806
807 // timestamp if supported
808 if ( timestamp() > QDateTime() )
809 {
810 QDomElement stamp = document.createElement( u"timestamp"_s );
811 const QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
812 stamp.appendChild( stampText );
813 layerElement.appendChild( stamp );
814 }
815
816 layerElement.appendChild( layerName );
817
818 // zorder
819 // This is no longer stored in the project file. It is superfluous since the layers
820 // are written and read in the proper order.
821
822 // spatial reference system id
823 QDomElement mySrsElement = document.createElement( u"srs"_s );
824 mCRS.writeXml( mySrsElement, document );
825 layerElement.appendChild( mySrsElement );
826
827 // layer metadata
828 QDomElement myMetadataElem = document.createElement( u"resourceMetadata"_s );
829 mMetadata.writeMetadataXml( myMetadataElem, document );
830 layerElement.appendChild( myMetadataElem );
831
832 layerElement.setAttribute( u"legendPlaceholderImage"_s, mLegendPlaceholderImage );
833
834 serverProperties()->writeXml( layerElement, document );
835
836 // now append layer node to map layer node
837 return writeXml( layerElement, document, context );
838}
839
840void QgsMapLayer::writeCommonStyle( QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories ) const
841{
843
844 // save categories
845 const QMetaEnum metaEnum = QMetaEnum::fromType<QgsMapLayer::StyleCategories>();
846 const QString categoriesKeys( metaEnum.valueToKeys( static_cast<int>( categories ) ) );
847 layerElement.setAttribute( u"styleCategories"_s, categoriesKeys );
848
849 // Store layer type
850 layerElement.setAttribute( u"layerType"_s, qgsEnumValueToKey( type() ) );
851
852 if ( categories.testFlag( Rendering ) )
853 {
854 // use scale dependent visibility flag
855 layerElement.setAttribute( u"hasScaleBasedVisibilityFlag"_s, hasScaleBasedVisibility() ? 1 : 0 );
856 layerElement.setAttribute( u"maxScale"_s, QString::number( maximumScale() ) );
857 layerElement.setAttribute( u"minScale"_s, QString::number( minimumScale() ) );
858 layerElement.setAttribute( u"autoRefreshMode"_s, qgsEnumValueToKey( mAutoRefreshMode ) );
859 layerElement.setAttribute( u"autoRefreshTime"_s, QString::number( autoRefreshInterval() ) );
860 }
861
862 if ( categories.testFlag( Symbology3D ) )
863 {
864 if ( m3DRenderer )
865 {
866 QDomElement renderer3DElem = document.createElement( u"renderer-3d"_s );
867 renderer3DElem.setAttribute( u"type"_s, m3DRenderer->type() );
868 m3DRenderer->writeXml( renderer3DElem, context );
869 layerElement.appendChild( renderer3DElem );
870 }
871 }
872
873 if ( categories.testFlag( LayerConfiguration ) )
874 {
875 // flags
876 // this code is saving automatically all the flags entries
877 QDomElement layerFlagsElem = document.createElement( u"flags"_s );
878 const auto enumMap = qgsEnumMap<QgsMapLayer::LayerFlag>();
879 for ( auto it = enumMap.constBegin(); it != enumMap.constEnd(); ++it )
880 {
881 const bool flagValue = mFlags.testFlag( it.key() );
882 QDomElement flagElem = document.createElement( it.value() );
883 flagElem.appendChild( document.createTextNode( QString::number( flagValue ) ) );
884 layerFlagsElem.appendChild( flagElem );
885 }
886 layerElement.appendChild( layerFlagsElem );
887 }
888
889 if ( categories.testFlag( Temporal ) )
890 {
891 if ( QgsMapLayerTemporalProperties *properties = const_cast< QgsMapLayer * >( this )->temporalProperties() )
892 properties->writeXml( layerElement, document, context );
893 }
894
895 if ( categories.testFlag( Elevation ) )
896 {
897 if ( QgsMapLayerElevationProperties *properties = const_cast< QgsMapLayer * >( this )->elevationProperties() )
898 properties->writeXml( layerElement, document, context );
899 }
900
901 if ( categories.testFlag( Notes ) && QgsLayerNotesUtils::layerHasNotes( this ) )
902 {
903 QDomElement notesElem = document.createElement( u"userNotes"_s );
904 notesElem.setAttribute( u"value"_s, QgsLayerNotesUtils::layerNotes( this ) );
905 layerElement.appendChild( notesElem );
906 }
907
908 // custom properties
909 if ( categories.testFlag( CustomProperties ) )
910 {
911 writeCustomProperties( layerElement, document );
912 }
913}
914
915
916bool QgsMapLayer::writeXml( QDomNode &layer_node, QDomDocument &document, const QgsReadWriteContext &context ) const
917{
919
920 Q_UNUSED( layer_node )
921 Q_UNUSED( document )
922 Q_UNUSED( context )
923 // NOP by default; children will over-ride with behavior specific to them
924
925 return true;
926}
927
928QString QgsMapLayer::encodedSource( const QString &source, const QgsReadWriteContext &context ) const
929{
931
932 Q_UNUSED( context )
933 return source;
934}
935
936QString QgsMapLayer::decodedSource( const QString &source, const QString &dataProvider, const QgsReadWriteContext &context ) const
937{
939
940 Q_UNUSED( context )
941 Q_UNUSED( dataProvider )
942 return source;
943}
944
946{
948
950 if ( m3DRenderer )
951 m3DRenderer->resolveReferences( *project );
952}
953
954
955void QgsMapLayer::readCustomProperties( const QDomNode &layerNode, const QString &keyStartsWith )
956{
958
959 const QgsObjectCustomProperties oldKeys = mCustomProperties;
960
961 mCustomProperties.readXml( layerNode, keyStartsWith );
962
963 for ( const QString &key : mCustomProperties.keys() )
964 {
965 if ( !oldKeys.contains( key ) || mCustomProperties.value( key ) != oldKeys.value( key ) )
966 {
967 emit customPropertyChanged( key );
968 }
969 }
970}
971
972void QgsMapLayer::writeCustomProperties( QDomNode &layerNode, QDomDocument &doc ) const
973{
975
976 mCustomProperties.writeXml( layerNode, doc );
977}
978
979void QgsMapLayer::readStyleManager( const QDomNode &layerNode )
980{
982
983 const QDomElement styleMgrElem = layerNode.firstChildElement( u"map-layer-style-manager"_s );
984 if ( !styleMgrElem.isNull() )
985 mStyleManager->readXml( styleMgrElem );
986 else
987 mStyleManager->reset();
988}
989
990void QgsMapLayer::writeStyleManager( QDomNode &layerNode, QDomDocument &doc ) const
991{
993
994 if ( mStyleManager )
995 {
996 QDomElement styleMgrElem = doc.createElement( u"map-layer-style-manager"_s );
997 mStyleManager->writeXml( styleMgrElem );
998 layerNode.appendChild( styleMgrElem );
999 }
1000}
1001
1003{
1005
1006 return mMapTipTemplate;
1007}
1008
1009void QgsMapLayer::setMapTipTemplate( const QString &mapTip )
1010{
1012
1013 if ( mMapTipTemplate == mapTip )
1014 return;
1015
1016 mMapTipTemplate = mapTip;
1017 emit mapTipTemplateChanged();
1018}
1019
1021{
1023
1024 if ( mMapTipsEnabled == enabled )
1025 return;
1026
1027 mMapTipsEnabled = enabled;
1028 emit mapTipsEnabledChanged();
1029}
1030
1032{
1034
1035 return mMapTipsEnabled;
1036}
1037
1039{
1041 if ( layerReadFlags & QgsMapLayer::FlagTrustLayerMetadata )
1042 {
1044 }
1045 if ( layerReadFlags & QgsMapLayer::FlagForceReadOnly )
1046 {
1048 }
1049
1050 if ( layerReadFlags & QgsMapLayer::FlagReadExtentFromXml )
1051 {
1052 const QDomNode extent3DNode = layerNode.namedItem( u"extent3D"_s );
1053 if ( extent3DNode.isNull() )
1054 {
1055 const QDomNode extentNode = layerNode.namedItem( u"extent"_s );
1056 if ( !extentNode.isNull() )
1057 {
1059 }
1060 }
1061 else
1062 {
1064 }
1065 }
1066
1067 return flags;
1068}
1069
1071{
1072 // because QgsVirtualLayerProvider is not anywhere NEAR thread safe:
1074
1075 return mValid;
1076}
1077
1078#if 0
1079void QgsMapLayer::connectNotify( const char *signal )
1080{
1081 Q_UNUSED( signal )
1082 QgsDebugMsgLevel( "QgsMapLayer connected to " + QString( signal ), 3 );
1083} // QgsMapLayer::connectNotify
1084#endif
1085
1086bool QgsMapLayer::isInScaleRange( double scale ) const
1087{
1088 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
1090
1091 // mMinScale (denominator!) is inclusive ( >= --> In range )
1092 // mMaxScale (denominator!) is exclusive ( < --> In range )
1093 return !mScaleBasedVisibility
1094 || ( ( mMinScale == 0 || !QgsScaleUtils::lessThanMaximumScale( scale, mMinScale ) ) && ( mMaxScale == 0 || !QgsScaleUtils::equalToOrGreaterThanMinimumScale( scale, mMaxScale ) ) );
1095}
1096
1098{
1099 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
1101
1102 return mScaleBasedVisibility;
1103}
1104
1106{
1108
1109 return mAutoRefreshMode != Qgis::AutoRefreshMode::Disabled;
1110 ;
1111}
1112
1114{
1116
1117 return mAutoRefreshMode;
1118}
1119
1121{
1123
1124 return mRefreshTimer->interval();
1125}
1126
1128{
1130
1131 if ( interval <= 0 )
1132 {
1133 mRefreshTimer->stop();
1134 mRefreshTimer->setInterval( 0 );
1136 }
1137 else
1138 {
1139 mRefreshTimer->setInterval( interval );
1140 }
1141 emit autoRefreshIntervalChanged( mRefreshTimer->isActive() ? mRefreshTimer->interval() : 0 );
1142}
1143
1150
1152{
1154
1155 if ( mode == mAutoRefreshMode )
1156 return;
1157
1158 mAutoRefreshMode = mode;
1159 switch ( mAutoRefreshMode )
1160 {
1162 mRefreshTimer->stop();
1163 break;
1164
1167 if ( mRefreshTimer->interval() > 0 )
1168 mRefreshTimer->start();
1169 break;
1170 }
1171
1172 emit autoRefreshIntervalChanged( mRefreshTimer->isActive() ? mRefreshTimer->interval() : 0 );
1173}
1174
1176{
1178
1179 return mMetadata;
1180}
1181
1183{
1185
1186 mMinScale = scale;
1187}
1188
1190{
1192
1193 return mMinScale;
1194}
1195
1197{
1199
1200 mMaxScale = scale;
1201}
1202
1204{
1206
1207 mScaleBasedVisibility = enabled;
1208}
1209
1211{
1213
1214 return mMaxScale;
1215}
1216
1217QStringList QgsMapLayer::subLayers() const
1218{
1220
1221 return QStringList();
1222}
1223
1224void QgsMapLayer::setLayerOrder( const QStringList &layers )
1225{
1227
1228 Q_UNUSED( layers )
1229}
1230
1231void QgsMapLayer::setSubLayerVisibility( const QString &name, bool vis )
1232{
1234
1235 Q_UNUSED( name )
1236 Q_UNUSED( vis )
1237}
1238
1240{
1242
1243 return false;
1244}
1245
1247{
1248 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
1250
1251 return mCRS;
1252}
1253
1255{
1256 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
1258
1259 switch ( mCRS.type() )
1260 {
1261 case Qgis::CrsType::Vertical: // would hope this never happens!
1262 QgsDebugError( u"Layer has a vertical CRS set as the horizontal CRS!"_s );
1263 return mCRS;
1264
1266 return mCRS.verticalCrs();
1267
1279 break;
1280 }
1281 return mVerticalCrs;
1282}
1283
1285{
1287
1288 return mCrs3D.isValid() ? mCrs3D : mCRS;
1289}
1290
1291void QgsMapLayer::setCrs( const QgsCoordinateReferenceSystem &srs, bool emitSignal )
1292{
1294 const bool needToValidateCrs = mShouldValidateCrs && isSpatial() && !srs.isValid() && type() != Qgis::LayerType::Annotation;
1295
1296 if ( mCRS == srs && !needToValidateCrs )
1297 return;
1298
1299 const QgsCoordinateReferenceSystem oldVerticalCrs = verticalCrs();
1300 const QgsCoordinateReferenceSystem oldCrs3D = mCrs3D;
1301 const QgsCoordinateReferenceSystem oldCrs = mCRS;
1302
1303 mCRS = srs;
1304
1305 if ( needToValidateCrs )
1306 {
1307 mCRS.setValidationHint( tr( "Specify CRS for layer %1" ).arg( name() ) );
1308 mCRS.validate();
1309 }
1310
1311 rebuildCrs3D();
1312
1313 if ( emitSignal && mCRS != oldCrs )
1314 emit crsChanged();
1315
1316 // Did vertical crs also change as a result of this? If so, emit signal
1317 if ( oldVerticalCrs != verticalCrs() )
1318 emit verticalCrsChanged();
1319 if ( oldCrs3D != mCrs3D )
1320 emit crs3DChanged();
1321}
1322
1324{
1326 bool res = true;
1327 if ( crs.isValid() )
1328 {
1329 // validate that passed crs is a vertical crs
1330 switch ( crs.type() )
1331 {
1333 break;
1334
1347 if ( errorMessage )
1348 *errorMessage = QObject::tr( "Specified CRS is a %1 CRS, not a Vertical CRS" ).arg( qgsEnumValueToKey( crs.type() ) );
1349 return false;
1350 }
1351 }
1352
1353 if ( crs != mVerticalCrs )
1354 {
1355 const QgsCoordinateReferenceSystem oldVerticalCrs = verticalCrs();
1356 const QgsCoordinateReferenceSystem oldCrs3D = mCrs3D;
1357
1358 switch ( mCRS.type() )
1359 {
1361 if ( crs != oldVerticalCrs )
1362 {
1363 if ( errorMessage )
1364 *errorMessage = QObject::tr( "Layer CRS is a Compound CRS, specified Vertical CRS will be ignored" );
1365 return false;
1366 }
1367 break;
1368
1370 if ( crs != oldVerticalCrs )
1371 {
1372 if ( errorMessage )
1373 *errorMessage = QObject::tr( "Layer CRS is a Geographic 3D CRS, specified Vertical CRS will be ignored" );
1374 return false;
1375 }
1376 break;
1377
1379 if ( crs != oldVerticalCrs )
1380 {
1381 if ( errorMessage )
1382 *errorMessage = QObject::tr( "Layer CRS is a Geocentric CRS, specified Vertical CRS will be ignored" );
1383 return false;
1384 }
1385 break;
1386
1388 if ( mCRS.hasVerticalAxis() && crs != oldVerticalCrs )
1389 {
1390 if ( errorMessage )
1391 *errorMessage = QObject::tr( "Layer CRS is a Projected 3D CRS, specified Vertical CRS will be ignored" );
1392 return false;
1393 }
1394 break;
1395
1405 break;
1406 }
1407
1408 mVerticalCrs = crs;
1409 res = rebuildCrs3D( errorMessage );
1410
1411 // only emit signal if vertical crs was actually changed, so eg if mCrs is compound
1412 // then we haven't actually changed the vertical crs by this call!
1413 if ( verticalCrs() != oldVerticalCrs )
1414 emit verticalCrsChanged();
1415 if ( mCrs3D != oldCrs3D )
1416 emit crs3DChanged();
1417 }
1418 return res;
1419}
1420
1422{
1424
1425 const QgsDataProvider *lDataProvider = dataProvider();
1426 return lDataProvider ? lDataProvider->transformContext() : QgsCoordinateTransformContext();
1427}
1428
1429QString QgsMapLayer::formatLayerName( const QString &name )
1430{
1431 QString layerName( name );
1432 layerName.replace( '_', ' ' );
1434 return layerName;
1435}
1436
1437QString QgsMapLayer::baseURI( PropertyType type ) const
1438{
1440
1441 QString myURI = publicSource();
1442
1443 // first get base path for delimited text, spatialite and OGR layers,
1444 // as in these cases URI may contain layer name and/or additional
1445 // information. This also strips prefix in case if VSIFILE mechanism
1446 // is used
1447 if ( providerType() == "ogr"_L1 || providerType() == "delimitedtext"_L1 || providerType() == "gdal"_L1 || providerType() == "spatialite"_L1 )
1448 {
1449 QVariantMap components = QgsProviderRegistry::instance()->decodeUri( providerType(), myURI );
1450 myURI = components["path"].toString();
1451 }
1452
1453 QFileInfo myFileInfo( myURI );
1454 QString key;
1455
1456 if ( myFileInfo.exists() )
1457 {
1458 // if file is using the /vsizip/ or /vsigzip/ mechanism, cleanup the name
1459 if ( myURI.endsWith( ".gz"_L1, Qt::CaseInsensitive ) )
1460 myURI.chop( 3 );
1461 else if ( myURI.endsWith( ".zip"_L1, Qt::CaseInsensitive ) )
1462 myURI.chop( 4 );
1463 else if ( myURI.endsWith( ".tar"_L1, Qt::CaseInsensitive ) )
1464 myURI.chop( 4 );
1465 else if ( myURI.endsWith( ".tar.gz"_L1, Qt::CaseInsensitive ) )
1466 myURI.chop( 7 );
1467 else if ( myURI.endsWith( ".tgz"_L1, Qt::CaseInsensitive ) )
1468 myURI.chop( 4 );
1469 myFileInfo.setFile( myURI );
1470 // get the file name for our .qml style file
1471 key = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + QgsMapLayer::extensionPropertyType( type );
1472 }
1473 else
1474 {
1475 key = publicSource();
1476 }
1477
1478 return key;
1479}
1480
1482{
1484
1485 return baseURI( PropertyType::Metadata );
1486}
1487
1488QString QgsMapLayer::saveDefaultMetadata( bool &resultFlag )
1489{
1491
1493 {
1494 if ( metadata->providerCapabilities() & QgsProviderMetadata::SaveLayerMetadata )
1495 {
1496 try
1497 {
1498 QString errorMessage;
1499 resultFlag = QgsProviderRegistry::instance()->saveLayerMetadata( providerType(), mDataSource, mMetadata, errorMessage );
1500 if ( resultFlag )
1501 return tr( "Successfully saved default layer metadata" );
1502 else
1503 return errorMessage;
1504 }
1505 catch ( QgsNotSupportedException &e )
1506 {
1507 resultFlag = false;
1508 return e.what();
1509 }
1510 }
1511 }
1512
1513 // fallback default metadata saving method, for providers which don't support (or implement) saveLayerMetadata
1514 return saveNamedMetadata( metadataUri(), resultFlag );
1515}
1516
1517QString QgsMapLayer::loadDefaultMetadata( bool &resultFlag )
1518{
1520
1521 return loadNamedMetadata( metadataUri(), resultFlag );
1522}
1523
1525{
1527
1528 return baseURI( PropertyType::Style );
1529}
1530
1537
1538bool QgsMapLayer::loadNamedMetadataFromDatabase( const QString &db, const QString &uri, QString &qmd )
1539{
1541
1542 return loadNamedPropertyFromDatabase( db, uri, qmd, PropertyType::Metadata );
1543}
1544
1545bool QgsMapLayer::loadNamedStyleFromDatabase( const QString &db, const QString &uri, QString &qml )
1546{
1548
1549 return loadNamedPropertyFromDatabase( db, uri, qml, PropertyType::Style );
1550}
1551
1552bool QgsMapLayer::loadNamedPropertyFromDatabase( const QString &db, const QString &uri, QString &xml, QgsMapLayer::PropertyType type )
1553{
1555
1556 QgsDebugMsgLevel( u"db = %1 uri = %2"_s.arg( db, uri ), 4 );
1557
1558 bool resultFlag = false;
1559
1560 // read from database
1563
1564 int myResult;
1565
1566 QgsDebugMsgLevel( u"Trying to load style or metadata for \"%1\" from \"%2\""_s.arg( uri, db ), 4 );
1567
1568 if ( db.isEmpty() || !QFile( db ).exists() )
1569 return false;
1570
1571 myResult = database.open_v2( db, SQLITE_OPEN_READONLY, nullptr );
1572 if ( myResult != SQLITE_OK )
1573 {
1574 return false;
1575 }
1576
1577 QString mySql;
1578 switch ( type )
1579 {
1580 case Metadata:
1581 mySql = u"select qmd from tbl_metadata where metadata=?"_s;
1582 break;
1583
1584 case Style:
1585 mySql = u"select qml from tbl_styles where style=?"_s;
1586 break;
1587 }
1588
1589 statement = database.prepare( mySql, myResult );
1590 if ( myResult == SQLITE_OK )
1591 {
1592 QByteArray param = uri.toUtf8();
1593
1594 if ( sqlite3_bind_text( statement.get(), 1, param.data(), param.length(), SQLITE_STATIC ) == SQLITE_OK && sqlite3_step( statement.get() ) == SQLITE_ROW )
1595 {
1596 xml = QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( statement.get(), 0 ) ) );
1597 resultFlag = true;
1598 }
1599 }
1600 return resultFlag;
1601}
1602
1603
1604QString QgsMapLayer::loadNamedStyle( const QString &uri, bool &resultFlag, QgsMapLayer::StyleCategories categories, Qgis::LoadStyleFlags flags )
1605{
1607
1608 return loadNamedStyle( uri, resultFlag, false, categories, flags );
1609}
1610
1611QString QgsMapLayer::loadNamedProperty( const QString &uri, QgsMapLayer::PropertyType type, bool &namedPropertyExists, bool &propertySuccessfullyLoaded, StyleCategories categories, Qgis::LoadStyleFlags flags )
1612{
1614
1615 QgsDebugMsgLevel( u"uri = %1 myURI = %2"_s.arg( uri, publicSource() ), 4 );
1616
1617 namedPropertyExists = false;
1618 propertySuccessfullyLoaded = false;
1619 if ( uri.isEmpty() )
1620 return QString();
1621
1622 QDomDocument myDocument( u"qgis"_s );
1623
1624 // location of problem associated with errorMsg
1625 int line, column;
1626 QString myErrorMessage;
1627
1628 QFile myFile( uri );
1629 if ( myFile.open( QFile::ReadOnly ) )
1630 {
1631 QgsDebugMsgLevel( u"file found %1"_s.arg( uri ), 2 );
1632 namedPropertyExists = true;
1633
1634 // read file
1635 propertySuccessfullyLoaded = myDocument.setContent( &myFile, &myErrorMessage, &line, &column );
1636 if ( !propertySuccessfullyLoaded )
1637 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
1638 myFile.close();
1639 }
1640 else
1641 {
1642 const QFileInfo project( QgsProject::instance()->fileName() ); // skip-keyword-check
1643 QgsDebugMsgLevel( u"project fileName: %1"_s.arg( project.absoluteFilePath() ), 4 );
1644
1645 QString xml;
1646 switch ( type )
1647 {
1648 case QgsMapLayer::Style:
1649 {
1650 if ( loadNamedStyleFromDatabase( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ), uri, xml )
1651 || ( project.exists() && loadNamedStyleFromDatabase( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), uri, xml ) )
1652 || loadNamedStyleFromDatabase( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( u"resources/qgis.qmldb"_s ), uri, xml ) )
1653 {
1654 namedPropertyExists = true;
1655 propertySuccessfullyLoaded = myDocument.setContent( xml, &myErrorMessage, &line, &column );
1656 if ( !propertySuccessfullyLoaded )
1657 {
1658 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
1659 }
1660 }
1661 else
1662 {
1664 {
1665 myErrorMessage = tr( "Style not found in database" );
1666 }
1667 }
1668 break;
1669 }
1671 {
1672 if ( loadNamedMetadataFromDatabase( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ), uri, xml )
1673 || ( project.exists() && loadNamedMetadataFromDatabase( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), uri, xml ) )
1674 || loadNamedMetadataFromDatabase( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( u"resources/qgis.qmldb"_s ), uri, xml ) )
1675 {
1676 namedPropertyExists = true;
1677 propertySuccessfullyLoaded = myDocument.setContent( xml, &myErrorMessage, &line, &column );
1678 if ( !propertySuccessfullyLoaded )
1679 {
1680 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
1681 }
1682 }
1683 else
1684 {
1685 myErrorMessage = tr( "Metadata not found in database" );
1686 }
1687 break;
1688 }
1689 }
1690 }
1691
1692 if ( !propertySuccessfullyLoaded )
1693 {
1694 return myErrorMessage;
1695 }
1696
1697 switch ( type )
1698 {
1699 case QgsMapLayer::Style:
1700 propertySuccessfullyLoaded = importNamedStyle( myDocument, myErrorMessage, categories );
1701 if ( !propertySuccessfullyLoaded )
1702 myErrorMessage = tr( "Loading style file %1 failed because:\n%2" ).arg( uri, myErrorMessage );
1703 break;
1705 propertySuccessfullyLoaded = importNamedMetadata( myDocument, myErrorMessage );
1706 if ( !propertySuccessfullyLoaded )
1707 myErrorMessage = tr( "Loading metadata file %1 failed because:\n%2" ).arg( uri, myErrorMessage );
1708 break;
1709 }
1710 return myErrorMessage;
1711}
1712
1713bool QgsMapLayer::importNamedMetadata( QDomDocument &document, QString &errorMessage )
1714{
1716
1717 const QDomElement myRoot = document.firstChildElement( u"qgis"_s );
1718 if ( myRoot.isNull() )
1719 {
1720 errorMessage = tr( "Root <qgis> element could not be found" );
1721 return false;
1722 }
1723
1724 return mMetadata.readMetadataXml( myRoot );
1725}
1726
1727bool QgsMapLayer::importNamedStyle( QDomDocument &myDocument, QString &myErrorMessage, QgsMapLayer::StyleCategories categories )
1728{
1730
1731 const QDomElement myRoot = myDocument.firstChildElement( u"qgis"_s );
1732 if ( myRoot.isNull() )
1733 {
1734 myErrorMessage = tr( "Root <qgis> element could not be found" );
1735 return false;
1736 }
1737
1738 // get style file version string, if any
1739 const QgsProjectVersion fileVersion( myRoot.attribute( u"version"_s ) );
1740 const QgsProjectVersion thisVersion( Qgis::version() );
1741
1742 if ( thisVersion > fileVersion )
1743 {
1744 QgsProjectFileTransform styleFile( myDocument, fileVersion );
1745 styleFile.updateRevision( thisVersion );
1746 }
1747
1748 // Get source categories
1749 const QgsMapLayer::StyleCategories sourceCategories = QgsXmlUtils::readFlagAttribute( myRoot, u"styleCategories"_s, QgsMapLayer::AllStyleCategories );
1750
1751 //Test for matching geometry type on vector layers when applying, if geometry type is given in the style
1752 if ( ( sourceCategories.testFlag( QgsMapLayer::Symbology ) || sourceCategories.testFlag( QgsMapLayer::Symbology3D ) )
1753 && ( categories.testFlag( QgsMapLayer::Symbology ) || categories.testFlag( QgsMapLayer::Symbology3D ) ) )
1754 {
1755 if ( type() == Qgis::LayerType::Vector && !myRoot.firstChildElement( u"layerGeometryType"_s ).isNull() )
1756 {
1757 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( this );
1758 const Qgis::GeometryType importLayerGeometryType = static_cast<Qgis::GeometryType>( myRoot.firstChildElement( u"layerGeometryType"_s ).text().toInt() );
1759 if ( importLayerGeometryType != Qgis::GeometryType::Unknown && vl->geometryType() != importLayerGeometryType )
1760 {
1761 myErrorMessage = tr( "Cannot apply style with symbology to layer with a different geometry type" );
1762 return false;
1763 }
1764 }
1765 }
1766
1767 // Pass the intersection between the desired categories and those that are really in the document
1769 return readSymbology( myRoot, myErrorMessage, context, categories & sourceCategories ); // TODO: support relative paths in QML?
1770}
1771
1772void QgsMapLayer::exportNamedMetadata( QDomDocument &doc, QString &errorMsg ) const
1773{
1775
1776 QDomImplementation DomImplementation;
1777 const QDomDocumentType documentType = DomImplementation.createDocumentType( u"qgis"_s, u"http://mrcc.com/qgis.dtd"_s, u"SYSTEM"_s );
1778 QDomDocument myDocument( documentType );
1779
1780 QDomElement myRootNode = myDocument.createElement( u"qgis"_s );
1781 myRootNode.setAttribute( u"version"_s, Qgis::version() );
1782 myDocument.appendChild( myRootNode );
1783
1784 if ( !mMetadata.writeMetadataXml( myRootNode, myDocument ) )
1785 {
1786 errorMsg = QObject::tr( "Could not save metadata" );
1787 return;
1788 }
1789
1790 doc = myDocument;
1791}
1792
1793void QgsMapLayer::exportNamedStyle( QDomDocument &doc, QString &errorMsg, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories ) const
1794{
1796
1797 QDomImplementation DomImplementation;
1798 const QDomDocumentType documentType = DomImplementation.createDocumentType( u"qgis"_s, u"http://mrcc.com/qgis.dtd"_s, u"SYSTEM"_s );
1799 QDomDocument myDocument( documentType );
1800
1801 QDomElement myRootNode = myDocument.createElement( u"qgis"_s );
1802 myRootNode.setAttribute( u"version"_s, Qgis::version() );
1803 myDocument.appendChild( myRootNode );
1804
1805 if ( !writeSymbology( myRootNode, myDocument, errorMsg, context, categories ) ) // TODO: support relative paths in QML?
1806 {
1807 errorMsg = QObject::tr( "Could not save symbology because:\n%1" ).arg( errorMsg );
1808 return;
1809 }
1810
1811 /*
1812 * Check to see if the layer is vector - in which case we should also export its geometryType
1813 * to avoid eventually pasting to a layer with a different geometry
1814 */
1815 if ( type() == Qgis::LayerType::Vector )
1816 {
1817 //Getting the selectionLayer geometry
1818 const QgsVectorLayer *vl = qobject_cast<const QgsVectorLayer *>( this );
1819 const QString geoType = QString::number( static_cast<int>( vl->geometryType() ) );
1820
1821 //Adding geometryinformation
1822 QDomElement layerGeometryType = myDocument.createElement( u"layerGeometryType"_s );
1823 const QDomText type = myDocument.createTextNode( geoType );
1824
1825 layerGeometryType.appendChild( type );
1826 myRootNode.appendChild( layerGeometryType );
1827 }
1828
1829 doc = myDocument;
1830}
1831
1832QString QgsMapLayer::saveDefaultStyle( bool &resultFlag )
1833{
1835
1836 return saveDefaultStyle( resultFlag, AllStyleCategories );
1837}
1838
1839QString QgsMapLayer::saveDefaultStyle( bool &resultFlag, StyleCategories categories )
1840{
1842
1843 return saveNamedStyle( styleURI(), resultFlag, categories );
1844}
1845
1846QString QgsMapLayer::saveNamedMetadata( const QString &uri, bool &resultFlag )
1847{
1849
1850 return saveNamedProperty( uri, QgsMapLayer::Metadata, resultFlag );
1851}
1852
1853QString QgsMapLayer::loadNamedMetadata( const QString &uri, bool &resultFlag )
1854{
1856
1857 bool metadataExists = false;
1858 bool metadataSuccessfullyLoaded = false;
1859 const QString message = loadNamedProperty( uri, QgsMapLayer::Metadata, metadataExists, metadataSuccessfullyLoaded );
1860
1861 // TODO QGIS 5.0 -- fix API for loadNamedMetadata so we can return metadataExists too
1862 ( void ) metadataExists;
1863 resultFlag = metadataSuccessfullyLoaded;
1864 return message;
1865}
1866
1867QString QgsMapLayer::saveNamedProperty( const QString &uri, QgsMapLayer::PropertyType type, bool &resultFlag, StyleCategories categories )
1868{
1870
1871 // check if the uri is a file or ends with .qml/.qmd,
1872 // which indicates that it should become one
1873 // everything else goes to the database
1874 QString filename;
1875
1876 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
1877 if ( vlayer && vlayer->providerType() == "ogr"_L1 )
1878 {
1879 QStringList theURIParts = uri.split( '|' );
1880 filename = theURIParts[0];
1881 }
1882 else if ( vlayer && vlayer->providerType() == "gpx"_L1 )
1883 {
1884 QStringList theURIParts = uri.split( '?' );
1885 filename = theURIParts[0];
1886 }
1887 else if ( vlayer && vlayer->providerType() == "delimitedtext"_L1 )
1888 {
1889 filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile();
1890 // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml"
1891 if ( filename.isEmpty() )
1892 filename = uri;
1893 }
1894 else
1895 {
1896 filename = uri;
1897 }
1898
1899 QString myErrorMessage;
1900 QDomDocument myDocument;
1901 switch ( type )
1902 {
1903 case Metadata:
1904 exportNamedMetadata( myDocument, myErrorMessage );
1905 break;
1906
1907 case Style:
1908 const QgsReadWriteContext context;
1909 exportNamedStyle( myDocument, myErrorMessage, context, categories );
1910 break;
1911 }
1912
1913 const QFileInfo myFileInfo( filename );
1914 if ( myFileInfo.exists() || filename.endsWith( QgsMapLayer::extensionPropertyType( type ), Qt::CaseInsensitive ) )
1915 {
1916 const QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name
1917 if ( !myDirInfo.isWritable() )
1918 {
1919 resultFlag = false;
1920 return tr( "The directory containing your dataset needs to be writable!" );
1921 }
1922
1923 // now construct the file name for our .qml or .qmd file
1924 const QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + QgsMapLayer::extensionPropertyType( type );
1925
1926 QFile myFile( myFileName );
1927 if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
1928 {
1929 QTextStream myFileStream( &myFile );
1930 // save as utf-8 with 2 spaces for indents
1931 myDocument.save( myFileStream, 2 );
1932 myFile.close();
1933 resultFlag = true;
1934 switch ( type )
1935 {
1936 case Metadata:
1937 return tr( "Created default metadata file as %1" ).arg( myFileName );
1938
1939 case Style:
1940 return tr( "Created default style file as %1" ).arg( myFileName );
1941 }
1942 }
1943 else
1944 {
1945 resultFlag = false;
1946 switch ( type )
1947 {
1948 case Metadata:
1949 return tr( "ERROR: Failed to created default metadata file as %1. Check file permissions and retry." ).arg( myFileName );
1950
1951 case Style:
1952 return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
1953 }
1954 }
1955 }
1956 else
1957 {
1958 const QString qml = myDocument.toString();
1959
1960 // read from database
1961 sqlite3_database_unique_ptr database;
1962 sqlite3_statement_unique_ptr statement;
1963
1964 int myResult = database.open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ) );
1965 if ( myResult != SQLITE_OK )
1966 {
1967 return tr( "User database could not be opened." );
1968 }
1969
1970 QByteArray param0 = uri.toUtf8();
1971 QByteArray param1 = qml.toUtf8();
1972
1973 QString mySql;
1974 switch ( type )
1975 {
1976 case Metadata:
1977 mySql = u"create table if not exists tbl_metadata(metadata varchar primary key,qmd varchar)"_s;
1978 break;
1979
1980 case Style:
1981 mySql = u"create table if not exists tbl_styles(style varchar primary key,qml varchar)"_s;
1982 break;
1983 }
1984
1985 statement = database.prepare( mySql, myResult );
1986 if ( myResult == SQLITE_OK )
1987 {
1988 if ( sqlite3_step( statement.get() ) != SQLITE_DONE )
1989 {
1990 resultFlag = false;
1991 switch ( type )
1992 {
1993 case Metadata:
1994 return tr( "The metadata table could not be created." );
1995
1996 case Style:
1997 return tr( "The style table could not be created." );
1998 }
1999 }
2000 }
2001
2002 switch ( type )
2003 {
2004 case Metadata:
2005 mySql = u"insert into tbl_metadata(metadata,qmd) values (?,?)"_s;
2006 break;
2007
2008 case Style:
2009 mySql = u"insert into tbl_styles(style,qml) values (?,?)"_s;
2010 break;
2011 }
2012 statement = database.prepare( mySql, myResult );
2013 if ( myResult == SQLITE_OK )
2014 {
2015 if ( sqlite3_bind_text( statement.get(), 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK
2016 && sqlite3_bind_text( statement.get(), 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK
2017 && sqlite3_step( statement.get() ) == SQLITE_DONE )
2018 {
2019 resultFlag = true;
2020 switch ( type )
2021 {
2022 case Metadata:
2023 myErrorMessage = tr( "The metadata %1 was saved to database" ).arg( uri );
2024 break;
2025
2026 case Style:
2027 myErrorMessage = tr( "The style %1 was saved to database" ).arg( uri );
2028 break;
2029 }
2030 }
2031 }
2032
2033 if ( !resultFlag )
2034 {
2035 QString mySql;
2036 switch ( type )
2037 {
2038 case Metadata:
2039 mySql = u"update tbl_metadata set qmd=? where metadata=?"_s;
2040 break;
2041
2042 case Style:
2043 mySql = u"update tbl_styles set qml=? where style=?"_s;
2044 break;
2045 }
2046 statement = database.prepare( mySql, myResult );
2047 if ( myResult == SQLITE_OK )
2048 {
2049 if ( sqlite3_bind_text( statement.get(), 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK
2050 && sqlite3_bind_text( statement.get(), 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK
2051 && sqlite3_step( statement.get() ) == SQLITE_DONE )
2052 {
2053 resultFlag = true;
2054 switch ( type )
2055 {
2056 case Metadata:
2057 myErrorMessage = tr( "The metadata %1 was updated in the database." ).arg( uri );
2058 break;
2059
2060 case Style:
2061 myErrorMessage = tr( "The style %1 was updated in the database." ).arg( uri );
2062 break;
2063 }
2064 }
2065 else
2066 {
2067 resultFlag = false;
2068 switch ( type )
2069 {
2070 case Metadata:
2071 myErrorMessage = tr( "The metadata %1 could not be updated in the database." ).arg( uri );
2072 break;
2073
2074 case Style:
2075 myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( uri );
2076 break;
2077 }
2078 }
2079 }
2080 else
2081 {
2082 resultFlag = false;
2083 switch ( type )
2084 {
2085 case Metadata:
2086 myErrorMessage = tr( "The metadata %1 could not be inserted into database." ).arg( uri );
2087 break;
2088
2089 case Style:
2090 myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( uri );
2091 break;
2092 }
2093 }
2094 }
2095 }
2096
2097 return myErrorMessage;
2098}
2099
2100QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag, StyleCategories categories )
2101{
2103
2104 return saveNamedProperty( uri, QgsMapLayer::Style, resultFlag, categories );
2105}
2106
2107void QgsMapLayer::exportSldStyle( QDomDocument &doc, QString &errorMsg ) const
2108{
2109 QgsSldExportContext exportContext;
2110 doc = exportSldStyleV3( exportContext );
2111 if ( !exportContext.errors().empty() )
2112 errorMsg = exportContext.errors().join( "\n" );
2113}
2114
2115void QgsMapLayer::exportSldStyleV2( QDomDocument &doc, QString &errorMsg, QgsSldExportContext &exportContext ) const
2116{
2118 doc = exportSldStyleV3( exportContext );
2119 if ( !exportContext.errors().empty() )
2120 errorMsg = exportContext.errors().join( "\n" );
2121}
2122
2123QDomDocument QgsMapLayer::exportSldStyleV3( QgsSldExportContext &exportContext ) const
2124{
2126
2127 QDomDocument myDocument = QDomDocument();
2128
2129 const QDomNode header = myDocument.createProcessingInstruction( u"xml"_s, u"version=\"1.0\" encoding=\"UTF-8\""_s );
2130 myDocument.appendChild( header );
2131
2132 const QgsVectorLayer *vlayer = qobject_cast<const QgsVectorLayer *>( this );
2133 const QgsRasterLayer *rlayer = qobject_cast<const QgsRasterLayer *>( this );
2134 if ( !vlayer && !rlayer )
2135 {
2136 exportContext.pushError( tr( "Could not save symbology because:\n%1" ).arg( tr( "Only vector and raster layers are supported" ) ) );
2137 return myDocument;
2138 }
2139
2140 // Create the root element
2141 QDomElement root = myDocument.createElementNS( u"http://www.opengis.net/sld"_s, u"StyledLayerDescriptor"_s );
2142 QDomElement layerNode;
2143 if ( vlayer )
2144 {
2145 root.setAttribute( u"version"_s, u"1.1.0"_s );
2146 root.setAttribute( u"xsi:schemaLocation"_s, u"http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd"_s );
2147 root.setAttribute( u"xmlns:ogc"_s, u"http://www.opengis.net/ogc"_s );
2148 root.setAttribute( u"xmlns:se"_s, u"http://www.opengis.net/se"_s );
2149 root.setAttribute( u"xmlns:xlink"_s, u"http://www.w3.org/1999/xlink"_s );
2150 root.setAttribute( u"xmlns:xsi"_s, u"http://www.w3.org/2001/XMLSchema-instance"_s );
2151 myDocument.appendChild( root );
2152
2153 // Create the NamedLayer element
2154 layerNode = myDocument.createElement( u"NamedLayer"_s );
2155 root.appendChild( layerNode );
2156 }
2157
2158 // note: Only SLD 1.0 version is generated because seems none is using SE1.1.0 at least for rasters
2159 if ( rlayer )
2160 {
2161 // Create the root element
2162 root.setAttribute( u"version"_s, u"1.0.0"_s );
2163 root.setAttribute( u"xmlns:gml"_s, u"http://www.opengis.net/gml"_s );
2164 root.setAttribute( u"xmlns:ogc"_s, u"http://www.opengis.net/ogc"_s );
2165 root.setAttribute( u"xmlns:sld"_s, u"http://www.opengis.net/sld"_s );
2166 myDocument.appendChild( root );
2167
2168 // Create the NamedLayer element
2169 layerNode = myDocument.createElement( u"UserLayer"_s );
2170 root.appendChild( layerNode );
2171 }
2172
2173 QVariantMap props = exportContext.extraProperties();
2174
2175 QVariant context;
2176 context.setValue( exportContext );
2177
2178 // TODO -- move this to proper members of QgsSldExportContext
2179 props[u"SldExportContext"_s] = context;
2180
2182 {
2183 props[u"scaleMinDenom"_s] = QString::number( mMinScale );
2184 props[u"scaleMaxDenom"_s] = QString::number( mMaxScale );
2185 }
2186 exportContext.setExtraProperties( props );
2187
2188 if ( vlayer )
2189 {
2190 if ( !vlayer->writeSld( layerNode, myDocument, exportContext ) )
2191 {
2192 return myDocument;
2193 }
2194 }
2195 else if ( rlayer )
2196 {
2197 if ( !rlayer->writeSld( layerNode, myDocument, exportContext ) )
2198 {
2199 return myDocument;
2200 }
2201 }
2202
2203 return myDocument;
2204}
2205
2206QString QgsMapLayer::saveSldStyle( const QString &uri, bool &resultFlag ) const
2207{
2208 QgsSldExportContext context;
2209 context.setExportFilePath( uri );
2210 return saveSldStyleV2( resultFlag, context );
2211}
2212
2213QString QgsMapLayer::saveSldStyleV2( bool &resultFlag, QgsSldExportContext &exportContext ) const
2214{
2216
2217 const QgsMapLayer *mlayer = qobject_cast<const QgsMapLayer *>( this );
2218
2219 const QString uri { exportContext.exportFilePath() };
2220
2221 // check if the uri is a file or ends with .sld,
2222 // which indicates that it should become one
2223 QString filename;
2224 if ( mlayer->providerType() == "ogr"_L1 )
2225 {
2226 QStringList theURIParts = uri.split( '|' );
2227 filename = theURIParts[0];
2228 }
2229 else if ( mlayer->providerType() == "gpx"_L1 )
2230 {
2231 QStringList theURIParts = uri.split( '?' );
2232 filename = theURIParts[0];
2233 }
2234 else if ( mlayer->providerType() == "delimitedtext"_L1 )
2235 {
2236 filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile();
2237 // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml"
2238 if ( filename.isEmpty() )
2239 filename = uri;
2240 }
2241 else
2242 {
2243 filename = uri;
2244 }
2245
2246 const QFileInfo myFileInfo( filename );
2247 if ( myFileInfo.exists() || filename.endsWith( ".sld"_L1, Qt::CaseInsensitive ) )
2248 {
2249 const QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name
2250 if ( !myDirInfo.isWritable() )
2251 {
2252 resultFlag = false;
2253 return tr( "The directory containing your dataset needs to be writable!" );
2254 }
2255
2256 // now construct the file name for our .sld style file
2257 const QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".sld";
2258
2259 QgsSldExportContext context { exportContext };
2260 context.setExportFilePath( myFileName );
2261
2262 QDomDocument myDocument = mlayer->exportSldStyleV3( context );
2263
2264 if ( !context.errors().empty() )
2265 {
2266 resultFlag = false;
2267 return context.errors().join( '\n' );
2268 }
2269
2270 QFile myFile( myFileName );
2271 if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
2272 {
2273 QTextStream myFileStream( &myFile );
2274 // save as utf-8 with 2 spaces for indents
2275 myDocument.save( myFileStream, 2 );
2276 myFile.close();
2277 resultFlag = true;
2278 return tr( "Created default style file as %1" ).arg( myFileName );
2279 }
2280 }
2281
2282 resultFlag = false;
2283 return tr( "ERROR: Failed to created SLD style file as %1. Check file permissions and retry." ).arg( filename );
2284}
2285
2286QString QgsMapLayer::loadSldStyle( const QString &uri, bool &resultFlag )
2287{
2289
2290 resultFlag = false;
2291
2292 QDomDocument myDocument;
2293
2294 // location of problem associated with errorMsg
2295 int line = 0, column = 0;
2296 QString myErrorMessage;
2297
2298 QFile myFile( uri );
2299 if ( myFile.open( QFile::ReadOnly ) )
2300 {
2301 // read file
2302 QXmlStreamReader xmlReader( &myFile );
2303 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"sld"_s, u"http://www.opengis.net/sld"_s ) );
2304 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"fes"_s, u"http://www.opengis.net/fes/2.0"_s ) );
2305 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"ogc"_s, u"http://www.opengis.net/ogc"_s ) );
2306 const QDomDocument::ParseResult result = myDocument.setContent( &xmlReader, QDomDocument::ParseOption::UseNamespaceProcessing );
2307 if ( result )
2308 {
2309 resultFlag = true;
2310 }
2311 else
2312 {
2313 myErrorMessage = result.errorMessage;
2314 line = result.errorLine;
2315 column = result.errorColumn;
2316 }
2317 if ( !resultFlag )
2318 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
2319 myFile.close();
2320 }
2321 else
2322 {
2323 myErrorMessage = tr( "Unable to open file %1" ).arg( uri );
2324 }
2325
2326 if ( !resultFlag )
2327 {
2328 return myErrorMessage;
2329 }
2330
2331 // check for root SLD element
2332 const QDomElement myRoot = myDocument.firstChildElement( u"StyledLayerDescriptor"_s );
2333 if ( myRoot.isNull() )
2334 {
2335 myErrorMessage = u"Error: StyledLayerDescriptor element not found in %1"_s.arg( uri );
2336 resultFlag = false;
2337 return myErrorMessage;
2338 }
2339
2340 // now get the style node out and pass it over to the layer
2341 // to deserialise...
2342 const QDomElement namedLayerElem = myRoot.firstChildElement( u"NamedLayer"_s );
2343 if ( namedLayerElem.isNull() )
2344 {
2345 myErrorMessage = u"Info: NamedLayer element not found."_s;
2346 resultFlag = false;
2347 return myErrorMessage;
2348 }
2349
2350 QString errorMsg;
2351 resultFlag = readSld( namedLayerElem, errorMsg );
2352 if ( !resultFlag )
2353 {
2354 myErrorMessage = tr( "Loading style file %1 failed because:\n%2" ).arg( uri, errorMsg );
2355 return myErrorMessage;
2356 }
2357
2358 return QString();
2359}
2360
2361bool QgsMapLayer::readStyle( const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories )
2362{
2364
2365 Q_UNUSED( node )
2366 Q_UNUSED( errorMessage )
2367 Q_UNUSED( context )
2368 Q_UNUSED( categories )
2369 return false;
2370}
2371
2372bool QgsMapLayer::writeStyle( QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories ) const
2373{
2375
2376 Q_UNUSED( node )
2377 Q_UNUSED( doc )
2378 Q_UNUSED( errorMessage )
2379 Q_UNUSED( context )
2380 Q_UNUSED( categories )
2381 return false;
2382}
2383
2384
2385void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, bool loadDefaultStyleFlag )
2386{
2388
2390
2392 if ( loadDefaultStyleFlag )
2393 {
2395 }
2396
2398 {
2400 }
2401 setDataSource( dataSource, baseName.isEmpty() ? mLayerName : baseName, provider.isEmpty() ? mProviderKey : provider, options, flags );
2402}
2403
2404void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, bool loadDefaultStyleFlag )
2405{
2407
2409 if ( loadDefaultStyleFlag )
2410 {
2412 }
2413
2415 {
2417 }
2418 setDataSource( dataSource, baseName, provider, options, flags );
2419}
2420
2421void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
2422{
2424
2426 {
2428 }
2429 setDataSourcePrivate( dataSource, baseName, provider, options, flags );
2430 emit dataSourceChanged();
2431 emit dataChanged();
2433}
2434
2435
2436void QgsMapLayer::setDataSourcePrivate( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
2437{
2439
2440 Q_UNUSED( dataSource )
2441 Q_UNUSED( baseName )
2442 Q_UNUSED( provider )
2443 Q_UNUSED( options )
2444 Q_UNUSED( flags )
2445}
2446
2447
2449{
2451
2452 return mProviderKey;
2453}
2454
2455void QgsMapLayer::readCommonStyle( const QDomElement &layerElement, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories )
2456{
2458
2459 if ( categories.testFlag( Symbology3D ) )
2460 {
2461 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "3D Symbology" ) );
2462
2463 QgsAbstract3DRenderer *r3D = nullptr;
2464 QDomElement renderer3DElem = layerElement.firstChildElement( u"renderer-3d"_s );
2465 if ( !renderer3DElem.isNull() )
2466 {
2467 const QString type3D = renderer3DElem.attribute( u"type"_s );
2469 if ( meta3D )
2470 {
2471 r3D = meta3D->createRenderer( renderer3DElem, context );
2472 }
2473 }
2474 setRenderer3D( r3D );
2475 }
2476
2477 if ( categories.testFlag( CustomProperties ) )
2478 {
2479 // read custom properties before passing reading further to a subclass, so that
2480 // the subclass can also read custom properties
2481 readCustomProperties( layerElement );
2482 }
2483
2484 // use scale dependent visibility flag
2485 if ( categories.testFlag( Rendering ) )
2486 {
2487 setScaleBasedVisibility( layerElement.attribute( u"hasScaleBasedVisibilityFlag"_s ).toInt() == 1 );
2488 if ( layerElement.hasAttribute( u"minimumScale"_s ) )
2489 {
2490 // older element, when scales were reversed
2491 setMaximumScale( layerElement.attribute( u"minimumScale"_s ).toDouble() );
2492 setMinimumScale( layerElement.attribute( u"maximumScale"_s ).toDouble() );
2493 }
2494 else
2495 {
2496 setMaximumScale( layerElement.attribute( u"maxScale"_s ).toDouble() );
2497 setMinimumScale( layerElement.attribute( u"minScale"_s ).toDouble() );
2498 }
2499 if ( layerElement.hasAttribute( u"autoRefreshMode"_s ) )
2500 {
2501 setAutoRefreshInterval( layerElement.attribute( u"autoRefreshTime"_s ).toInt() );
2502 setAutoRefreshMode( qgsEnumKeyToValue( layerElement.attribute( u"autoRefreshMode"_s ), Qgis::AutoRefreshMode::Disabled ) );
2503 }
2504 }
2505
2506 if ( categories.testFlag( LayerConfiguration ) )
2507 {
2508 // flags
2509 const QDomElement flagsElem = layerElement.firstChildElement( u"flags"_s );
2510 LayerFlags flags = mFlags;
2511 const auto enumMap = qgsEnumMap<QgsMapLayer::LayerFlag>();
2512 for ( auto it = enumMap.constBegin(); it != enumMap.constEnd(); ++it )
2513 {
2514 const QDomNode flagNode = flagsElem.namedItem( it.value() );
2515 if ( flagNode.isNull() )
2516 continue;
2517 const bool flagValue = flagNode.toElement().text() == "1" ? true : false;
2518 if ( flags.testFlag( it.key() ) && !flagValue )
2519 flags &= ~it.key();
2520 else if ( !flags.testFlag( it.key() ) && flagValue )
2521 flags |= it.key();
2522 }
2523 setFlags( flags );
2524 }
2525
2526 if ( categories.testFlag( Temporal ) )
2527 {
2528 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "Temporal" ) );
2529
2531 properties->readXml( layerElement.toElement(), context );
2532 }
2533
2534 if ( categories.testFlag( Elevation ) )
2535 {
2536 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "Elevation" ) );
2537
2539 properties->readXml( layerElement.toElement(), context );
2540 }
2541
2542 if ( categories.testFlag( Notes ) )
2543 {
2544 const QDomElement notesElem = layerElement.firstChildElement( u"userNotes"_s );
2545 if ( !notesElem.isNull() )
2546 {
2547 const QString notes = notesElem.attribute( u"value"_s );
2548 QgsLayerNotesUtils::setLayerNotes( this, notes );
2549 }
2550 }
2551}
2552
2554{
2556
2557 return mUndoStack;
2558}
2559
2561{
2563
2564 return mUndoStackStyles;
2565}
2566
2568{
2570
2571 return mCustomProperties.keys();
2572}
2573
2574void QgsMapLayer::setCustomProperty( const QString &key, const QVariant &value )
2575{
2577
2578 if ( !mCustomProperties.contains( key ) || mCustomProperties.value( key ) != value )
2579 {
2580 mCustomProperties.setValue( key, value );
2581 emit customPropertyChanged( key );
2582 }
2583}
2584
2586{
2588
2589 mCustomProperties = properties;
2590 for ( const QString &key : mCustomProperties.keys() )
2591 {
2592 emit customPropertyChanged( key );
2593 }
2594}
2595
2597{
2599
2600 return mCustomProperties;
2601}
2602
2603QVariant QgsMapLayer::customProperty( const QString &value, const QVariant &defaultValue ) const
2604{
2605 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
2607
2608 return mCustomProperties.value( value, defaultValue );
2609}
2610
2611void QgsMapLayer::removeCustomProperty( const QString &key )
2612{
2614
2615 if ( mCustomProperties.contains( key ) )
2616 {
2617 mCustomProperties.remove( key );
2618 emit customPropertyChanged( key );
2619 }
2620}
2621
2622int QgsMapLayer::listStylesInDatabase( QStringList &ids, QStringList &names, QStringList &descriptions, QString &msgError )
2623{
2625
2626 return QgsProviderRegistry::instance()->listStyles( mProviderKey, mDataSource, ids, names, descriptions, msgError );
2627}
2628
2629QString QgsMapLayer::getStyleFromDatabase( const QString &styleId, QString &msgError )
2630{
2632
2633 return QgsProviderRegistry::instance()->getStyleById( mProviderKey, mDataSource, styleId, msgError );
2634}
2635
2636bool QgsMapLayer::deleteStyleFromDatabase( const QString &styleId, QString &msgError )
2637{
2639
2641}
2642
2643void QgsMapLayer::saveStyleToDatabase( const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories )
2644{
2645 saveStyleToDatabaseV2( name, description, useAsDefault, uiFileContent, msgError, categories );
2646}
2647
2649 const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories
2650)
2651{
2653
2655
2656 QString sldStyle, qmlStyle;
2657 QDomDocument qmlDocument;
2658 QgsReadWriteContext context;
2659 exportNamedStyle( qmlDocument, msgError, context, categories );
2660 if ( !msgError.isEmpty() )
2661 {
2663 }
2664 else
2665 {
2666 qmlStyle = qmlDocument.toString();
2667 }
2668
2669 QgsSldExportContext sldContext;
2670 QDomDocument sldDocument = this->exportSldStyleV3( sldContext );
2671 if ( !sldContext.errors().empty() )
2672 {
2674 }
2675 else
2676 {
2677 sldStyle = sldDocument.toString();
2678 }
2679
2680 if ( !QgsProviderRegistry::instance()->saveStyle( mProviderKey, mDataSource, qmlStyle, sldStyle, name, description, uiFileContent, useAsDefault, msgError ) )
2681 {
2683 }
2684 return results;
2685}
2686
2687QString QgsMapLayer::loadNamedStyle( const QString &theURI, bool &resultFlag, bool loadFromLocalDB, QgsMapLayer::StyleCategories categories, Qgis::LoadStyleFlags flags )
2688{
2690
2691 QString returnMessage;
2692 QString qml, errorMsg;
2693 QString styleName;
2694 if ( !loadFromLocalDB && dataProvider() && dataProvider()->styleStorageCapabilities().testFlag( Qgis::ProviderStyleStorageCapability::LoadFromDatabase ) )
2695 {
2697 }
2698
2699 // Style was successfully loaded from provider storage
2700 if ( !qml.isEmpty() )
2701 {
2702 QDomDocument myDocument( u"qgis"_s );
2703 myDocument.setContent( qml );
2704 resultFlag = importNamedStyle( myDocument, errorMsg );
2705 returnMessage = QObject::tr( "Loaded from Provider" );
2706 }
2707 else
2708 {
2710
2711 bool styleExists = false;
2712 bool styleSuccessfullyLoaded = false;
2713
2714 returnMessage = loadNamedProperty( theURI, PropertyType::Style, styleExists, styleSuccessfullyLoaded, categories, flags );
2715
2716 // TODO QGIS 5.0 -- fix API for loadNamedStyle so we can return styleExists too
2717 ( void ) styleExists;
2718 resultFlag = styleSuccessfullyLoaded;
2719 }
2720
2721 if ( !styleName.isEmpty() )
2722 {
2723 styleManager()->renameStyle( styleManager()->currentStyle(), styleName );
2724 }
2725
2726 if ( resultFlag )
2727 emit styleLoaded( categories );
2728
2729 return returnMessage;
2730}
2731
2738
2740{
2742
2743 return false;
2744}
2745
2747{
2749
2750 return false;
2751}
2752
2754{
2756
2757 return true;
2758}
2759
2761{
2763
2764 // invalid layers are temporary? -- who knows?!
2765 if ( !isValid() )
2766 return false;
2767
2768 if ( mProviderKey == "memory"_L1 )
2769 return true;
2770
2771 const QVariantMap sourceParts = QgsProviderRegistry::instance()->decodeUri( mProviderKey, mDataSource );
2772 const QString path = sourceParts.value( u"path"_s ).toString();
2773 if ( path.isEmpty() )
2774 return false;
2775
2776 // check if layer path is inside one of the standard temporary file locations for this platform
2777 const QStringList tempPaths = QStandardPaths::standardLocations( QStandardPaths::TempLocation );
2778 for ( const QString &tempPath : tempPaths )
2779 {
2780 if ( path.startsWith( tempPath ) )
2781 return true;
2782 }
2783
2784 return false;
2785}
2786
2787void QgsMapLayer::setValid( bool valid )
2788{
2790
2791 if ( mValid == valid )
2792 return;
2793
2794 mValid = valid;
2795 emit isValidChanged();
2796}
2797
2799{
2801
2802 if ( legend == mLegend.get() )
2803 return;
2804
2805 mLegend.reset( legend );
2806
2807
2808 if ( mLegend )
2809 {
2810 mLegend->setParent( this );
2811 connect( mLegend.get(), &QgsMapLayerLegend::itemsChanged, this, &QgsMapLayer::legendChanged, Qt::UniqueConnection );
2812 }
2813
2814 emit legendChanged();
2815}
2816
2818{
2820
2821 return mLegend.get();
2822}
2823
2825{
2827
2828 return mStyleManager.get();
2829}
2830
2832{
2834
2835 if ( renderer == m3DRenderer.get() )
2836 return;
2837
2838 m3DRenderer.reset( renderer );
2839
2840 emit renderer3DChanged();
2841 emit repaintRequested();
2843}
2844
2846{
2848
2849 return m3DRenderer.get();
2850}
2851
2852void QgsMapLayer::triggerRepaint( bool deferredUpdate )
2853{
2855
2856 if ( mRepaintRequestedFired )
2857 return;
2858 mRepaintRequestedFired = true;
2859 emit repaintRequested( deferredUpdate );
2860 mRepaintRequestedFired = false;
2861}
2862
2869
2871{
2873
2874 mMetadata = metadata;
2875 // mMetadata.saveToLayer( this );
2876 emit metadataChanged();
2877}
2878
2880{
2882
2883 return QString();
2884}
2885
2886QDateTime QgsMapLayer::timestamp() const
2887{
2889
2890 return QDateTime();
2891}
2892
2900
2902{
2903 updateExtent( extent );
2904}
2905
2907{
2909
2910 updateExtent( extent );
2911}
2912
2913bool QgsMapLayer::isReadOnly() const
2914{
2916
2917 return true;
2918}
2919
2921{
2923
2924 return mOriginalXmlProperties;
2925}
2926
2928{
2930
2931 mOriginalXmlProperties = originalXmlProperties;
2932}
2933
2934QString QgsMapLayer::generateId( const QString &layerName )
2935{
2936 // Generate the unique ID of this layer
2937 const QString uuid = QUuid::createUuid().toString();
2938 // trim { } from uuid
2939 QString id = layerName + '_' + uuid.mid( 1, uuid.length() - 2 );
2940 // Tidy the ID up to avoid characters that may cause problems
2941 // elsewhere (e.g in some parts of XML). Replaces every non-word
2942 // character (word characters are the alphabet, numbers and
2943 // underscore) with an underscore.
2944 // Note that the first backslash in the regular expression is
2945 // there for the compiler, so the pattern is actually \W
2946 const thread_local QRegularExpression idRx( u"[\\W]"_s );
2947 id.replace( idRx, u"_"_s );
2948 return id;
2949}
2950
2952{
2954
2955 return true;
2956}
2957
2964
2966{
2968
2969 return mapTipsEnabled() && !mMapTipTemplate.isEmpty();
2970}
2971
2978
2979QSet<QgsMapLayerDependency> QgsMapLayer::dependencies() const
2980{
2982
2983 return mDependencies;
2984}
2985
2986bool QgsMapLayer::setDependencies( const QSet<QgsMapLayerDependency> &oDeps )
2987{
2989
2990 QSet<QgsMapLayerDependency> deps;
2991 const auto constODeps = oDeps;
2992 for ( const QgsMapLayerDependency &dep : constODeps )
2993 {
2994 if ( dep.origin() == QgsMapLayerDependency::FromUser )
2995 deps << dep;
2996 }
2997
2998 mDependencies = deps;
2999 emit dependenciesChanged();
3000 return true;
3001}
3002
3004{
3006
3007 QgsDataProvider *lDataProvider = dataProvider();
3008
3009 if ( !lDataProvider )
3010 return;
3011
3012 if ( enabled && !isRefreshOnNotifyEnabled() )
3013 {
3014 lDataProvider->setListening( enabled );
3015 connect( lDataProvider, &QgsDataProvider::notify, this, &QgsMapLayer::onNotified );
3016 }
3017 else if ( !enabled && isRefreshOnNotifyEnabled() )
3018 {
3019 // we don't want to disable provider listening because someone else could need it (e.g. actions)
3020 disconnect( lDataProvider, &QgsDataProvider::notify, this, &QgsMapLayer::onNotified );
3021 }
3022 mIsRefreshOnNofifyEnabled = enabled;
3023}
3024
3026{
3027 // aggregate based tests aren't thread safe
3029
3030 if ( QgsMapLayerStore *store = qobject_cast<QgsMapLayerStore *>( parent() ) )
3031 {
3032 return qobject_cast<QgsProject *>( store->parent() );
3033 }
3034 return nullptr;
3035}
3036
3037void QgsMapLayer::onNotified( const QString &message )
3038{
3040
3041 if ( refreshOnNotifyMessage().isEmpty() || refreshOnNotifyMessage() == message )
3042 {
3044 emit dataChanged();
3045 }
3046}
3047
3048QgsRectangle QgsMapLayer::wgs84Extent( bool forceRecalculate ) const
3049{
3051
3052 if ( !crs().isEarthCrs() )
3053 {
3054 return QgsRectangle();
3055 }
3056
3057 // if this function is called without previous call to extent() it will return empty rectangle as both mExtent2D and mExtent3D are null
3058 // to avoid this call extent here to force extent calculation
3059 ( void ) extent();
3060
3062
3063 if ( !forceRecalculate && !mWgs84Extent.isNull() )
3064 {
3065 wgs84Extent = mWgs84Extent;
3066 }
3067 else if ( !mExtent2D.isNull() || !mExtent3D.isNull() )
3068 {
3069 QgsCoordinateTransform transformer { crs(), QgsCoordinateReferenceSystem( u"EPSG:4326"_s ), transformContext() };
3070 transformer.setBallparkTransformsAreAppropriate( true );
3071 try
3072 {
3073 if ( mExtent2D.isNull() )
3074 wgs84Extent = transformer.transformBoundingBox( mExtent3D.toRectangle() );
3075 else
3076 wgs84Extent = transformer.transformBoundingBox( mExtent2D );
3077 }
3078 catch ( const QgsCsException &cse )
3079 {
3080 QgsMessageLog::logMessage( tr( "Error transforming extent: %1" ).arg( cse.what() ) );
3082 }
3083 }
3084 return wgs84Extent;
3085}
3086
3087void QgsMapLayer::updateExtent( const QgsRectangle &extent ) const
3088{
3090
3091 if ( extent == mExtent2D )
3092 return;
3093
3094 mExtent2D = extent;
3095
3096 // do not update the wgs84 extent if we trust layer metadata
3098 return;
3099
3100 mWgs84Extent = wgs84Extent( true );
3101}
3102
3103void QgsMapLayer::updateExtent( const QgsBox3D &extent ) const
3104{
3106
3107 if ( extent == mExtent3D )
3108 return;
3109
3110 if ( extent.isNull() )
3111 {
3112 if ( !extent.toRectangle().isNull() )
3113 {
3114 // bad 3D extent param but valid in 2d --> update 2D extent
3115 updateExtent( extent.toRectangle() );
3116 }
3117 else
3118 {
3119 QgsDebugMsgLevel( u"Unable to update extent with empty parameter"_s, 1 );
3120 }
3121 }
3122 else
3123 {
3124 mExtent3D = extent;
3125
3126 // do not update the wgs84 extent if we trust layer metadata
3128 return;
3129
3130 mWgs84Extent = wgs84Extent( true );
3131 }
3132}
3133
3134bool QgsMapLayer::rebuildCrs3D( QString *error )
3135{
3136 bool res = true;
3137 if ( !mCRS.isValid() )
3138 {
3139 mCrs3D = QgsCoordinateReferenceSystem();
3140 }
3141 else if ( !mVerticalCrs.isValid() )
3142 {
3143 mCrs3D = mCRS;
3144 }
3145 else
3146 {
3147 switch ( mCRS.type() )
3148 {
3152 mCrs3D = mCRS;
3153 break;
3154
3156 {
3157 QString tempError;
3158 mCrs3D = mCRS.hasVerticalAxis() ? mCRS : QgsCoordinateReferenceSystem::createCompoundCrs( mCRS, mVerticalCrs, error ? *error : tempError );
3159 res = mCrs3D.isValid();
3160 break;
3161 }
3162
3164 // nonsense situation
3165 mCrs3D = QgsCoordinateReferenceSystem();
3166 res = false;
3167 break;
3168
3177 {
3178 QString tempError;
3179 mCrs3D = QgsCoordinateReferenceSystem::createCompoundCrs( mCRS, mVerticalCrs, error ? *error : tempError );
3180 res = mCrs3D.isValid();
3181 break;
3182 }
3183 }
3184 }
3185 return res;
3186}
3187
3189{
3191
3192 // do not update the wgs84 extent if we trust layer metadata
3194 return;
3195
3196 mWgs84Extent = QgsRectangle();
3197}
3198
3200{
3202
3203 QString metadata = u"<h1>"_s + tr( "General" ) + u"</h1>\n<hr>\n"_s + u"<table class=\"list-view\">\n"_s;
3204
3205 // name
3206 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Name" ) + u"</td><td>"_s + name() + u"</td></tr>\n"_s;
3207
3208 const QString lPublicSource = publicSource();
3209
3210 QString path;
3211 bool isLocalPath = false;
3212 if ( dataProvider() )
3213 {
3214 // local path
3215 QVariantMap uriComponents = QgsProviderRegistry::instance()->decodeUri( dataProvider()->name(), lPublicSource );
3216 if ( uriComponents.contains( u"path"_s ) )
3217 {
3218 path = uriComponents[u"path"_s].toString();
3219 QFileInfo fi( path );
3220 if ( fi.exists() )
3221 {
3222 isLocalPath = true;
3223 metadata += u"<tr><td class=\"highlight\">"_s
3224 + tr( "Path" )
3225 + u"</td><td>%1"_s.arg( u"<a href=\"%1\">%2</a>"_s.arg( QUrl::fromLocalFile( path ).toString(), QDir::toNativeSeparators( path ) ) )
3226 + u"</td></tr>\n"_s;
3227
3228 QDateTime lastModified = fi.lastModified();
3229 QString lastModifiedFileName;
3230 QSet<QString> sidecarFiles = QgsFileUtils::sidecarFilesForPath( path );
3231 if ( fi.isFile() )
3232 {
3233 qint64 fileSize = fi.size();
3234 if ( !sidecarFiles.isEmpty() )
3235 {
3236 lastModifiedFileName = fi.fileName();
3237 QStringList sidecarFileNames;
3238 for ( const QString &sidecarFile : sidecarFiles )
3239 {
3240 QFileInfo sidecarFi( sidecarFile );
3241 fileSize += sidecarFi.size();
3242 if ( sidecarFi.lastModified() > lastModified )
3243 {
3244 lastModified = sidecarFi.lastModified();
3245 lastModifiedFileName = sidecarFi.fileName();
3246 }
3247 sidecarFileNames << sidecarFi.fileName();
3248 }
3249 metadata += u"<tr><td class=\"highlight\">"_s
3250 + ( sidecarFiles.size() > 1 ? tr( "Sidecar files" ) : tr( "Sidecar file" ) )
3251 + u"</td><td>%1"_s.arg( sidecarFileNames.join( ", "_L1 ) )
3252 + u"</td></tr>\n"_s;
3253 }
3254 metadata += u"<tr><td class=\"highlight\">"_s
3255 + ( !sidecarFiles.isEmpty() ? tr( "Total size" ) : tr( "Size" ) )
3256 + u"</td><td>%1"_s.arg( QgsFileUtils::representFileSize( fileSize ) )
3257 + u"</td></tr>\n"_s;
3258 }
3259 metadata += u"<tr><td class=\"highlight\">"_s
3260 + tr( "Last modified" )
3261 + u"</td><td>%1"_s.arg( QLocale().toString( fi.lastModified() ) )
3262 + ( !lastModifiedFileName.isEmpty() ? u" (%1)"_s.arg( lastModifiedFileName ) : QString() )
3263 + u"</td></tr>\n"_s;
3264 }
3265 }
3266 if ( uriComponents.contains( u"url"_s ) )
3267 {
3268 QUrl decodedUri = QUrl::fromPercentEncoding( uriComponents[u"url"_s].toString().toLocal8Bit() );
3269 const QString url = decodedUri.toString();
3270 metadata += u"<tr><td class=\"highlight\">"_s + tr( "URL" ) + u"</td><td>%1"_s.arg( u"<a href=\"%1\">%2</a>"_s.arg( url, url ) ) + u"</td></tr>\n"_s;
3271 }
3272 }
3273
3274 // data source
3275 if ( lPublicSource != path || !isLocalPath )
3276 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Source" ) + u"</td><td>%1"_s.arg( lPublicSource != path ? lPublicSource : path ) + u"</td></tr>\n"_s;
3277
3278 // provider
3279 if ( dataProvider() )
3280 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Provider" ) + u"</td><td>%1"_s.arg( dataProvider()->name() ) + u"</td></tr>\n"_s;
3281
3282 // Layer ID
3283 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Layer ID" ) + u"</td><td>%1"_s.arg( id() ) + u"</td></tr>\n"_s;
3284
3285 metadata += "</table>\n<br><br>"_L1;
3286
3287 return metadata;
3288}
3289
3291{
3292 QString metadata;
3293 // custom properties
3294 if ( const auto keys = customPropertyKeys(); !keys.isEmpty() )
3295 {
3296 metadata += u"<h1>"_s + tr( "Custom properties" ) + u"</h1>\n<hr>\n"_s;
3297 metadata += "<table class=\"list-view\">\n<tbody>"_L1;
3298 for ( const QString &key : keys )
3299 {
3300 // keys prefaced with _ are considered private/internal details
3301 if ( key.startsWith( '_' ) )
3302 continue;
3303
3304 const QVariant propValue = customProperty( key );
3305 QString stringValue;
3306 if ( propValue.type() == QVariant::List || propValue.type() == QVariant::StringList )
3307 {
3308 for ( const QString &s : propValue.toStringList() )
3309 {
3310 stringValue += "<p style=\"margin: 0;\">" + s.toHtmlEscaped() + "</p>";
3311 }
3312 }
3313 else
3314 {
3315 stringValue = propValue.toString().toHtmlEscaped();
3316
3317 //if the result string is empty but propValue is not, the conversion has failed
3318 if ( stringValue.isEmpty() && !QgsVariantUtils::isNull( propValue ) )
3319 stringValue = tr( "<i>value cannot be displayed</i>" );
3320 }
3321
3322 metadata += u"<tr><td class=\"highlight\">%1</td><td>%2</td></tr>"_s.arg( key.toHtmlEscaped(), stringValue );
3323 }
3324 metadata += "</tbody></table>\n"_L1;
3325 metadata += "<br><br>\n"_L1;
3326 }
3327 return metadata;
3328}
3329
3331{
3333 QString metadata;
3334
3335 auto addCrsInfo = [&metadata]( const QgsCoordinateReferenceSystem &c, bool includeType, bool includeOperation, bool includeCelestialBody ) {
3336 if ( !c.isValid() )
3337 metadata += u"<tr><td colspan=\"2\" class=\"highlight\">"_s + tr( "Unknown" ) + u"</td></tr>\n"_s;
3338 else
3339 {
3340 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Name" ) + u"</td><td>"_s + c.userFriendlyIdentifier( Qgis::CrsIdentifierType::FullString ) + u"</td></tr>\n"_s;
3341
3342 // map units
3343 metadata += u"<tr><td class=\"highlight\">"_s
3344 + tr( "Units" )
3345 + u"</td><td>"_s
3346 + ( c.isGeographic() ? tr( "Geographic (uses latitude and longitude for coordinates)" ) : QgsUnitTypes::toString( c.mapUnits() ) )
3347 + u"</td></tr>\n"_s;
3348
3349 if ( includeType )
3350 {
3351 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Type" ) + u"</td><td>"_s + QgsCoordinateReferenceSystemUtils::crsTypeToString( c.type() ) + u"</td></tr>\n"_s;
3352 }
3353
3354 if ( includeOperation )
3355 {
3356 // operation
3357 const QgsProjOperation operation = c.operation();
3358 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Method" ) + u"</td><td>"_s + operation.description() + u"</td></tr>\n"_s;
3359 }
3360
3361 if ( includeCelestialBody )
3362 {
3363 // celestial body
3364 try
3365 {
3366 const QString celestialBody = c.celestialBodyName();
3367 if ( !celestialBody.isEmpty() )
3368 {
3369 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Celestial Body" ) + u"</td><td>"_s + celestialBody + u"</td></tr>\n"_s;
3370 }
3371 }
3372 catch ( QgsNotSupportedException & )
3373 {}
3374 }
3375
3376 QString accuracyString;
3377 // dynamic crs with no epoch?
3378 if ( c.isDynamic() && std::isnan( c.coordinateEpoch() ) )
3379 {
3380 accuracyString = tr( "Based on a dynamic CRS, but no coordinate epoch is set. Coordinates are ambiguous and of limited accuracy." );
3381 }
3382
3383 // based on datum ensemble?
3384 try
3385 {
3386 const QgsDatumEnsemble ensemble = c.datumEnsemble();
3387 if ( ensemble.isValid() )
3388 {
3389 QString id;
3390 if ( !ensemble.code().isEmpty() )
3391 id = u"<i>%1</i> (%2:%3)"_s.arg( ensemble.name(), ensemble.authority(), ensemble.code() );
3392 else
3393 id = u"<i>%1</i>”"_s.arg( ensemble.name() );
3394
3395 if ( ensemble.accuracy() > 0 )
3396 {
3397 accuracyString = tr( "Based on %1, which has a limited accuracy of <b>at best %2 meters</b>." ).arg( id ).arg( ensemble.accuracy() );
3398 }
3399 else
3400 {
3401 accuracyString = tr( "Based on %1, which has a limited accuracy." ).arg( id );
3402 }
3403 }
3404 }
3405 catch ( QgsNotSupportedException & )
3406 {}
3407
3408 if ( !accuracyString.isEmpty() )
3409 {
3410 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Accuracy" ) + u"</td><td>"_s + accuracyString + u"</td></tr>\n"_s;
3411 }
3412
3413 // static/dynamic
3414 metadata += u"<tr><td class=\"highlight\">"_s
3415 + tr( "Reference" )
3416 + u"</td><td>%1</td></tr>\n"_s.arg( c.isDynamic() ? tr( "Dynamic (relies on a datum which is not plate-fixed)" ) : tr( "Static (relies on a datum which is plate-fixed)" ) );
3417
3418 // coordinate epoch
3419 if ( !std::isnan( c.coordinateEpoch() ) )
3420 {
3421 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Coordinate Epoch" ) + u"</td><td>%1</td></tr>\n"_s.arg( qgsDoubleToString( c.coordinateEpoch(), 3 ) );
3422 }
3423 }
3424 };
3425
3426 metadata += u"<h1>"_s + tr( "Coordinate Reference System (CRS)" ) + u"</h1>\n<hr>\n"_s;
3427 metadata += "<table class=\"list-view\">\n"_L1;
3428 addCrsInfo( crs().horizontalCrs(), true, true, true );
3429 metadata += "</table>\n<br><br>\n"_L1;
3430
3431 if ( verticalCrs().isValid() )
3432 {
3433 metadata += u"<h1>"_s + tr( "Vertical Coordinate Reference System (CRS)" ) + u"</h1>\n<hr>\n"_s;
3434 metadata += "<table class=\"list-view\">\n"_L1;
3435 addCrsInfo( verticalCrs(), false, false, false );
3436 metadata += "</table>\n<br><br>\n"_L1;
3437 }
3438
3439 return metadata;
3440}
static QString version()
Version string.
Definition qgis.cpp:682
@ FullString
Full definition – possibly a very lengthy string, e.g. with no truncation of custom WKT definitions.
Definition qgis.h:2554
@ Vertical
Vertical CRS.
Definition qgis.h:2467
@ Temporal
Temporal CRS.
Definition qgis.h:2470
@ Compound
Compound (horizontal + vertical) CRS.
Definition qgis.h:2469
@ Projected
Projected CRS.
Definition qgis.h:2468
@ Other
Other type.
Definition qgis.h:2473
@ Bound
Bound CRS.
Definition qgis.h:2472
@ DerivedProjected
Derived projected CRS.
Definition qgis.h:2474
@ Unknown
Unknown type.
Definition qgis.h:2462
@ Engineering
Engineering CRS.
Definition qgis.h:2471
@ Geographic3d
3D geopraphic CRS
Definition qgis.h:2466
@ Geodetic
Geodetic CRS.
Definition qgis.h:2463
@ Geographic2d
2D geographic CRS
Definition qgis.h:2465
@ Geocentric
Geocentric CRS.
Definition qgis.h:2464
@ RemoveCredentials
Completely remove credentials (eg passwords) from the URI. This flag is not compatible with the Redac...
Definition qgis.h:1477
@ RedactCredentials
Replace the value of credentials (eg passwords) with 'xxxxxxxx'. This flag is not compatible with the...
Definition qgis.h:1478
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
Definition qgis.h:3559
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:379
@ Unknown
Unknown types.
Definition qgis.h:383
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:512
LayerType
Types of layers that can be added to a map.
Definition qgis.h:206
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:212
@ Vector
Vector layer.
Definition qgis.h:207
QFlags< MapLayerProperty > MapLayerProperties
Map layer properties.
Definition qgis.h:2419
QFlags< LoadStyleFlag > LoadStyleFlags
Flags for loading layer styles.
Definition qgis.h:263
@ LoadDefaultStyle
Reset the layer's style to the default for the datasource.
Definition qgis.h:495
@ ForceReadOnly
Open layer in a read-only mode.
Definition qgis.h:498
@ SkipGetExtent
Skip the extent from provider.
Definition qgis.h:496
@ TrustDataSource
Trust datasource config (primary key unicity, geometry type and srid, etc). Improves provider load ti...
Definition qgis.h:492
@ IgnoreMissingStyleErrors
If the style is missing, then don't flag it as an error. This flag can be used when the caller is not...
Definition qgis.h:253
AutoRefreshMode
Map layer automatic refresh modes.
Definition qgis.h:2429
@ RedrawOnly
Redraw current data only.
Definition qgis.h:2432
@ ReloadData
Reload data (and draw the new data).
Definition qgis.h:2431
@ Disabled
Automatic refreshing is disabled.
Definition qgis.h:2430
Base metadata class for 3D renderers.
virtual QgsAbstract3DRenderer * createRenderer(QDomElement &elem, const QgsReadWriteContext &context)=0
Returns new instance of the renderer given the DOM element.
Qgs3DRendererAbstractMetadata * rendererMetadata(const QString &type) const
Returns metadata for a 3D renderer type (may be used to create a new instance of the type).
Base class for all renderers that participate in 3D views.
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QString qgisSettingsDirPath()
Returns the path to the settings directory in user's home dir.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static Qgs3DRendererRegistry * renderer3DRegistry()
Returns registry of available 3D renderers.
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:45
static QString crsTypeToString(Qgis::CrsType type)
Returns a translated string representing a CRS type.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static CUSTOM_CRS_VALIDATION customCrsValidation()
Gets custom function.
static QgsCoordinateReferenceSystem createCompoundCrs(const QgsCoordinateReferenceSystem &horizontalCrs, const QgsCoordinateReferenceSystem &verticalCrs, QString &error)
Given a horizontal and vertical CRS, attempts to create a compound CRS from them.
static void setCustomCrsValidation(CUSTOM_CRS_VALIDATION f)
Sets custom function to force valid CRS.
Contains information about the context in which a coordinate transform is executed.
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
virtual bool containsElevationData() const
Returns true if the data provider definitely contains elevation related data.
Abstract base class for spatial data provider implementations.
void notify(const QString &msg)
Emitted when the datasource issues a notification.
virtual QgsDataProviderElevationProperties * elevationProperties()
Returns the provider's elevation properties.
static QString removePassword(const QString &aUri, bool hide=false)
Removes the password element from a URI.
Contains information about a datum ensemble.
Definition qgsdatums.h:100
QString code() const
Identification code, e.g.
Definition qgsdatums.h:126
QString authority() const
Authority name, e.g.
Definition qgsdatums.h:121
bool isValid() const
Returns true if the datum ensemble is a valid object, or false if it is a null/invalid object.
Definition qgsdatums.h:106
QString name() const
Display name of datum ensemble.
Definition qgsdatums.h:111
double accuracy() const
Positional accuracy (in meters).
Definition qgsdatums.h:116
A container for error messages.
Definition qgserror.h:83
QString what() const
static QSet< QString > sidecarFilesForPath(const QString &path)
Returns a list of the sidecar files which exist for the dataset a the specified path.
static QString representFileSize(qint64 bytes)
Returns the human size from bytes.
A structured metadata store for a map layer.
static void setLayerNotes(QgsMapLayer *layer, const QString &notes)
Sets the notes for the specified layer, where notes is a HTML formatted string.
static bool layerHasNotes(const QgsMapLayer *layer)
Returns true if the specified layer has notes available.
static QString layerNotes(const QgsMapLayer *layer)
Returns the notes for the specified layer.
Models dependencies with or between map layers.
Base class for storage of map layer elevation properties.
An abstract interface for implementations of legends for one map layer.
void itemsChanged()
Emitted when existing items/nodes got invalid and should be replaced by new ones.
Manages QGIS Server properties for a map layer.
void readXml(const QDomNode &layer_node)
Reads server properties from project file.
void copyTo(QgsMapLayerServerProperties *properties) const
Copy properties to another instance.
void writeXml(QDomNode &layer_node, QDomDocument &document) const
Saves server properties to xml under the layer node.
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
Management of styles for use with one map layer.
bool addStyle(const QString &name, const QgsMapLayerStyle &style)
Add a style with given name and data.
QStringList styles() const
Returns list of all defined style names.
bool renameStyle(const QString &name, const QString &newName)
Rename a stored style to a different name.
Base class for storage of map layer temporal properties.
void crs3DChanged()
Emitted when the crs3D() of the layer has changed.
Q_DECL_DEPRECATED void setShortName(const QString &shortName)
Sets the short name of the layer used by QGIS Server to identify the layer.
virtual bool deleteStyleFromDatabase(const QString &styleId, QString &msgError)
Deletes a style from the database.
bool importNamedMetadata(QDomDocument &document, QString &errorMessage)
Import the metadata of this layer from a QDomDocument.
QString name
Definition qgsmaplayer.h:87
void readStyleManager(const QDomNode &layerNode)
Read style manager's configuration (if any). To be called by subclasses.
virtual bool writeSymbology(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const =0
Write the style for the layer into the document provided.
Q_DECL_DEPRECATED QString legendUrlFormat() const
Returns the format for a URL based layer legend.
Q_INVOKABLE QgsRectangle wgs84Extent(bool forceRecalculate=false) const
Returns the WGS84 extent (EPSG:4326) of the layer according to ReadFlag::FlagTrustLayerMetadata.
void setRefreshOnNotifyEnabled(bool enabled)
Set whether provider notification is connected to triggerRepaint.
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
virtual bool isTemporary() const
Returns true if the layer is considered a temporary layer.
virtual Q_DECL_DEPRECATED void exportSldStyleV2(QDomDocument &doc, QString &errorMsg, QgsSldExportContext &exportContext) const
Export the properties of this layer as SLD style in a QDomDocument.
virtual void exportNamedStyle(QDomDocument &doc, QString &errorMsg, const QgsReadWriteContext &context=QgsReadWriteContext(), QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const
Export the properties of this layer as named style in a QDomDocument.
bool setId(const QString &id)
Sets the layer's id.
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all symbols associated with the layer.
void dependenciesChanged()
Emitted when dependencies are changed.
virtual bool hasMapTips() const
Returns true if the layer contains map tips.
bool isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
void legendChanged()
Signal emitted when legend of the layer has changed.
void writeStyleManager(QDomNode &layerNode, QDomDocument &doc) const
Write style manager's configuration (if exists). To be called by subclasses.
QgsMapLayerLegend * legend() const
Can be nullptr.
QFlags< ReadFlag > ReadFlags
QFlags< LayerFlag > LayerFlags
virtual bool importNamedStyle(QDomDocument &doc, QString &errorMsg, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Import the properties of this layer from a QDomDocument.
Q_DECL_DEPRECATED void setAbstract(const QString &abstract)
Sets the abstract of the layer used by QGIS Server in GetCapabilities request.
void metadataChanged()
Emitted when the layer's metadata is changed.
virtual Q_INVOKABLE QgsRectangle extent() const
Returns the extent of the layer.
virtual QString saveSldStyle(const QString &uri, bool &resultFlag) const
Saves the properties of this layer to an SLD format file.
QString source() const
Returns the source for the layer.
Q_DECL_DEPRECATED void setLegendUrl(const QString &legendUrl)
Sets the URL for the layer's legend.
virtual bool setDependencies(const QSet< QgsMapLayerDependency > &layers)
Sets the list of dependencies.
void request3DUpdate()
Signal emitted when a layer requires an update in any 3D maps.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
QgsError mError
Error.
int mBlockStyleChangedSignal
If non-zero, the styleChanged signal should not be emitted.
@ SldGenerationFailed
Generation of the SLD failed, and was not written to the database.
@ DatabaseWriteFailed
An error occurred when attempting to write to the database.
@ QmlGenerationFailed
Generation of the QML failed, and was not written to the database.
QString providerType() const
Returns the provider type (provider key) for this layer.
virtual void setExtent3D(const QgsBox3D &box)
Sets the extent.
void removeCustomProperty(const QString &key)
Remove a custom property from layer.
Qgis::AutoRefreshMode autoRefreshMode() const
Returns the layer's automatic refresh mode.
void setBlendMode(QPainter::CompositionMode blendMode)
Set the blending mode used for rendering a layer.
void configChanged()
Emitted whenever the configuration is changed.
void trigger3DUpdate()
Will advise any 3D maps that this layer requires to be updated in the scene.
void autoRefreshIntervalChanged(int interval)
Emitted when the auto refresh interval changes.
void setMinimumScale(double scale)
Sets the minimum map scale (i.e.
virtual QSet< QgsMapLayerDependency > dependencies() const
Gets the list of dependencies.
void setCustomProperties(const QgsObjectCustomProperties &properties)
Set custom properties for layer.
static Qgis::DataProviderReadFlags providerReadFlags(const QDomNode &layerNode, QgsMapLayer::ReadFlags layerReadFlags)
Returns provider read flag deduced from layer read flags layerReadFlags and a dom node layerNode that...
virtual QString loadNamedStyle(const QString &theURI, bool &resultFlag, bool loadFromLocalDb, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories, Qgis::LoadStyleFlags flags=Qgis::LoadStyleFlags())
Loads a named style from file/local db/datasource db.
virtual QString encodedSource(const QString &source, const QgsReadWriteContext &context) const
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to proje...
QgsCoordinateReferenceSystem crs3D
Definition qgsmaplayer.h:92
virtual void setSubLayerVisibility(const QString &name, bool visible)
Set the visibility of the given sublayer name.
void isValidChanged()
Emitted when the validity of this layer changed.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
bool loadNamedMetadataFromDatabase(const QString &db, const QString &uri, QString &qmd)
Retrieve a named metadata for this layer from a sqlite database.
friend class QgsVectorLayer
virtual bool readXml(const QDomNode &layer_node, QgsReadWriteContext &context)
Called by readLayerXML(), used by children to read state specific to them from project files.
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
Q_DECL_DEPRECATED QString attribution() const
Returns the attribution of the layer used by QGIS Server in GetCapabilities request.
void setOriginalXmlProperties(const QString &originalXmlProperties)
Sets the original XML properties for the layer to originalXmlProperties.
void writeCustomProperties(QDomNode &layerNode, QDomDocument &doc) const
Write custom properties to project file.
QString mRefreshOnNofifyMessage
virtual int listStylesInDatabase(QStringList &ids, QStringList &names, QStringList &descriptions, QString &msgError)
Lists all the style in db split into related to the layer and not related to.
virtual QString loadDefaultStyle(bool &resultFlag)
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record...
void setDataSource(const QString &dataSource, const QString &baseName=QString(), const QString &provider=QString(), bool loadDefaultStyleFlag=false)
Updates the data source of the layer.
QString mLayerName
Name of the layer - used for display.
virtual QString loadNamedMetadata(const QString &uri, bool &resultFlag)
Retrieve a named metadata for this layer if one exists (either as a .qmd file on disk or as a record ...
virtual bool writeXml(QDomNode &layer_node, QDomDocument &document, const QgsReadWriteContext &context) const
Called by writeLayerXML(), used by children to write state specific to them to project files.
Q_DECL_DEPRECATED bool hasAutoRefreshEnabled() const
Returns true if auto refresh is enabled for the layer.
QString id
Definition qgsmaplayer.h:86
void mapTipTemplateChanged()
Emitted when the map tip template changes.
void triggerRepaint(bool deferredUpdate=false)
Will advise the map canvas (and any other interested party) that this layer requires to be repainted.
QString crsHtmlMetadata() const
Returns a HTML fragment containing the layer's CRS metadata, for use in the htmlMetadata() method.
Q_DECL_DEPRECATED void setAttributionUrl(const QString &attribUrl)
Sets the attribution URL of the layer used by QGIS Server in GetCapabilities request.
QgsMapLayer::SaveStyleResults saveStyleToDatabaseV2(const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Saves QML and SLD representations of the layer's style to a table in the database.
Q_DECL_DEPRECATED void setAutoRefreshEnabled(bool enabled)
Sets whether auto refresh is enabled for the layer.
void setMaximumScale(double scale)
Sets the maximum map scale (i.e.
QgsLayerMetadata metadata
Definition qgsmaplayer.h:89
static QString formatLayerName(const QString &name)
A convenience function to capitalize and format a layer name.
void renderer3DChanged()
Signal emitted when 3D renderer associated with the layer has changed.
Q_DECL_DEPRECATED QString abstract() const
Returns the abstract of the layer used by QGIS Server in GetCapabilities request.
QgsMapLayer(Qgis::LayerType type=Qgis::LayerType::Vector, const QString &name=QString(), const QString &source=QString())
Constructor for QgsMapLayer.
QString originalXmlProperties() const
Returns the XML properties of the original layer as they were when the layer was first read from the ...
Qgis::LayerType type
Definition qgsmaplayer.h:93
Q_DECL_DEPRECATED QString dataUrlFormat() const
Returns the DataUrl format of the layer used by QGIS Server in GetCapabilities request.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
Q_DECL_DEPRECATED void setDataUrl(const QString &dataUrl)
Sets the DataUrl of the layer used by QGIS Server in GetCapabilities request.
virtual void setOpacity(double opacity)
Sets the opacity for the layer, where opacity is a value between 0 (totally transparent) and 1....
Q_DECL_DEPRECATED void setKeywordList(const QString &keywords)
Sets the keyword list of the layerused by QGIS Server in GetCapabilities request.
Q_DECL_DEPRECATED void setAttribution(const QString &attrib)
Sets the attribution of the layerused by QGIS Server in GetCapabilities request.
void setFlags(QgsMapLayer::LayerFlags flags)
Returns the flags for this layer.
bool isRefreshOnNotifyEnabled() const
Returns true if the refresh on provider nofification is enabled.
QString publicSource(bool hidePassword=false) const
Gets a version of the internal layer definition that has sensitive bits removed (for example,...
Q_DECL_DEPRECATED QString shortName() const
Returns the short name of the layer used by QGIS Server to identify the layer.
QSet< QgsMapLayerDependency > mDependencies
List of layers that may modify this layer on modification.
void readCustomProperties(const QDomNode &layerNode, const QString &keyStartsWith=QString())
Read custom properties from project file.
virtual Qgis::MapLayerProperties properties() const
Returns the map layer properties of this layer.
virtual QString loadSldStyle(const QString &uri, bool &resultFlag)
Attempts to style the layer using the formatting from an SLD type file.
virtual void setMetadata(const QgsLayerMetadata &metadata)
Sets the layer's metadata store.
virtual bool readStyle(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)
Read the style for the current layer from the DOM node supplied.
virtual QString saveDefaultMetadata(bool &resultFlag)
Save the current metadata of this layer as the default metadata (either as a .qmd file on disk or as ...
virtual bool supportsEditing() const
Returns whether the layer supports editing or not.
Q_DECL_DEPRECATED void setDataUrlFormat(const QString &dataUrlFormat)
Sets the DataUrl format of the layer used by QGIS Server in GetCapabilities request.
QFlags< StyleCategory > StyleCategories
virtual Q_DECL_DEPRECATED void saveStyleToDatabase(const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Saves QML and SLD representations of the layer's style to a table in the database.
Q_INVOKABLE void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for layer.
QString mProviderKey
Data provider key (name of the data provider).
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
void styleChanged()
Signal emitted whenever a change affects the layer's style.
virtual bool isEditable() const
Returns true if the layer can be edited.
QUndoStack * undoStack()
Returns pointer to layer's undo stack.
std::unique_ptr< QgsDataProvider > mPreloadedProvider
Optionally used when loading a project, it is released when the layer is effectively created.
Q_DECL_DEPRECATED QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
void crsChanged()
Emitted when the crs() of the layer has changed.
virtual QgsError error() const
Gets current status error.
bool writeLayerXml(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context) const
Stores state in DOM node.
virtual QString styleURI() const
Retrieve the style URI for this layer (either as a .qml file on disk or as a record in the users styl...
void setScaleBasedVisibility(bool enabled)
Sets whether scale based visibility is enabled for the layer.
void dataSourceChanged()
Emitted whenever the layer's data source has been changed.
void idChanged(const QString &id)
Emitted when the layer's ID has been changed.
Q_DECL_DEPRECATED QString dataUrl() const
Returns the DataUrl of the layer used by QGIS Server in GetCapabilities request.
QgsMapLayer::LayerFlags flags
Definition qgsmaplayer.h:99
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
Q_DECL_DEPRECATED QString metadataUrlFormat() const
Returns the metadata format of the layer used by QGIS Server in GetCapabilities request.
void setRefreshOnNofifyMessage(const QString &message)
Set the notification message that triggers repaint If refresh on notification is enabled,...
static QString generateId(const QString &layerName)
Generates an unique identifier for this layer, the generate ID is prefixed by layerName.
QgsProviderMetadata * providerMetadata() const
Returns the layer data provider's metadata, it may be nullptr.
void opacityChanged(double opacity)
Emitted when the layer's opacity is changed, where opacity is a value between 0 (transparent) and 1 (...
virtual bool isModified() const
Returns true if the layer has been modified since last commit/save.
void styleLoaded(QgsMapLayer::StyleCategories categories)
Emitted when a style has been loaded.
virtual QString getStyleFromDatabase(const QString &styleId, QString &msgError)
Returns the named style corresponding to style id provided.
void emitStyleChanged()
Triggers an emission of the styleChanged() signal.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
QUndoStack * undoStackStyles()
Returns pointer to layer's style undo stack.
void dataChanged()
Data of layer changed.
virtual QStringList subLayers() const
Returns the sublayers of this layer.
virtual QString htmlMetadata() const
Obtain a formatted HTML string containing assorted metadata for this layer.
Q_DECL_DEPRECATED void setMetadataUrlFormat(const QString &metaUrlFormat)
Sets the metadata format of the layer used by QGIS Server in GetCapabilities request.
virtual bool loadNamedStyleFromDatabase(const QString &db, const QString &uri, QString &qml)
Retrieve a named style for this layer from a sqlite database.
void verticalCrsChanged()
Emitted when the verticalCrs() of the layer has changed.
virtual QgsBox3D extent3D() const
Returns the 3D extent of the layer.
static QString extensionPropertyType(PropertyType type)
Returns the extension of a Property.
virtual QgsMapLayer * clone() const =0
Returns a new instance equivalent to this one except for the id which is still unique.
void blendModeChanged(QPainter::CompositionMode blendMode)
Signal emitted when the blend mode is changed, through QgsMapLayer::setBlendMode().
void setName(const QString &name)
Set the display name of the layer.
void setAutoRefreshInterval(int interval)
Sets the auto refresh interval (in milliseconds) for the layer.
virtual bool readSymbology(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)=0
Read the symbology for the current layer from the DOM node supplied.
Q_DECL_DEPRECATED QString metadataUrl() const
Returns the metadata URL of the layer used by QGIS Server in GetCapabilities request.
virtual void setExtent(const QgsRectangle &rect)
Sets the extent.
virtual void resolveReferences(QgsProject *project)
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
QString saveNamedMetadata(const QString &uri, bool &resultFlag)
Save the current metadata of this layer as a named metadata (either as a .qmd file on disk or as a re...
QString mDataSource
Data source description string, varies by layer type.
void setAutoRefreshMode(Qgis::AutoRefreshMode mode)
Sets the automatic refresh mode for the layer.
QString refreshOnNotifyMessage() const
Returns the message that should be notified by the provider to triggerRepaint.
virtual bool readSld(const QDomNode &node, QString &errorMessage)
void setMapTipsEnabled(bool enabled)
Enable or disable map tips for this layer.
virtual QString loadDefaultMetadata(bool &resultFlag)
Retrieve the default metadata for this layer if one exists (either as a .qmd file on disk or as a rec...
virtual QString saveSldStyleV2(bool &resultFlag, QgsSldExportContext &exportContext) const
Saves the properties of this layer to an SLD format file.
@ FlagReadExtentFromXml
Read extent from xml and skip get extent from provider.
@ FlagTrustLayerMetadata
Trust layer metadata. Improves layer load time by skipping expensive checks like primary key unicity,...
@ FlagForceReadOnly
Force open as read only.
void setValid(bool valid)
Sets whether layer is valid or not.
Q_DECL_DEPRECATED QString attributionUrl() const
Returns the attribution URL of the layer used by QGIS Server in GetCapabilities request.
void readCommonStyle(const QDomElement &layerElement, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)
Read style data common to all layer types.
void customPropertyChanged(const QString &key)
Emitted when a custom property of the layer has been changed or removed.
virtual QDomDocument exportSldStyleV3(QgsSldExportContext &exportContext) const
Export the properties of this layer as SLD style in a QDomDocument.
QgsMapLayer::ReadFlags mReadFlags
Read flags. It's up to the subclass to respect these when restoring state from XML.
double minimumScale() const
Returns the minimum map scale (i.e.
QgsMapLayerStyleManager * styleManager() const
Gets access to the layer's style manager.
Q_DECL_DEPRECATED QString legendUrl() const
Returns the URL for the layer's legend.
void flagsChanged()
Emitted when layer's flags have been modified.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
Q_DECL_DEPRECATED void setLegendUrlFormat(const QString &legendUrlFormat)
Sets the format for a URL based layer legend.
void exportNamedMetadata(QDomDocument &doc, QString &errorMsg) const
Export the current metadata of this layer as named metadata in a QDomDocument.
virtual QString saveNamedStyle(const QString &uri, bool &resultFlag, StyleCategories categories=AllStyleCategories)
Save the properties of this layer as a named style (either as a .qml file on disk or as a record in t...
virtual Q_DECL_DEPRECATED void exportSldStyle(QDomDocument &doc, QString &errorMsg) const
Export the properties of this layer as SLD style in a QDomDocument.
void beforeResolveReferences(QgsProject *project)
Emitted when all layers are loaded and references can be resolved, just before the references of this...
void setMapTipTemplate(const QString &mapTipTemplate)
The mapTip is a pretty, html representation for feature information.
Q_DECL_DEPRECATED void setMetadataUrl(const QString &metaUrl)
Sets the metadata URL of the layer used by QGIS Server in GetCapabilities request.
virtual QgsMapLayerElevationProperties * elevationProperties()
Returns the layer's elevation properties.
bool setVerticalCrs(const QgsCoordinateReferenceSystem &crs, QString *errorMessage=nullptr)
Sets the layer's vertical coordinate reference system.
Q_INVOKABLE QStringList customPropertyKeys() const
Returns list of all keys within custom properties.
QgsProject * project() const
Returns the parent project if this map layer is added to a project.
Q_DECL_DEPRECATED void setMetadataUrlType(const QString &metaUrlType)
Set the metadata type of the layer used by QGIS Server in GetCapabilities request MetadataUrlType ind...
bool mapTipsEnabled
Definition qgsmaplayer.h:97
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags=QgsMapLayer::ReadFlags(), QgsDataProvider *preloadedProvider=nullptr)
Sets state from DOM document.
void setLegend(QgsMapLayerLegend *legend)
Assign a legend controller to the map layer.
double opacity
Definition qgsmaplayer.h:95
virtual QString decodedSource(const QString &source, const QString &dataProvider, const QgsReadWriteContext &context) const
Called by readLayerXML(), used by derived classes to decode provider's specific data source from proj...
void nameChanged()
Emitted when the name has been changed.
virtual QString metadataUri() const
Retrieve the metadata URI for this layer (either as a .qmd file on disk or as a record in the users s...
int autoRefreshInterval
Definition qgsmaplayer.h:88
QgsCoordinateReferenceSystem verticalCrs
Definition qgsmaplayer.h:91
virtual bool writeStyle(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const
Write just the symbology information for the layer into the document.
bool mIsRefreshOnNofifyEnabled
virtual Q_INVOKABLE QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
double mLayerOpacity
Layer opacity.
bool mValid
Indicates if the layer is valid and can be drawn.
@ LayerConfiguration
General configuration: identifiable, removable, searchable, display expression, read-only.
@ Symbology
Symbology.
@ Notes
Layer user notes.
@ Temporal
Temporal properties.
@ Rendering
Rendering: scale visibility, simplify method, opacity.
@ Elevation
Elevation settings.
@ Symbology3D
3D symbology
@ CustomProperties
Custom properties (by plugins for instance).
virtual Q_INVOKABLE void reload()
Synchronises with changes in the datasource.
virtual QDateTime timestamp() const
Time stamp of data source in the moment when data/metadata were loaded by provider.
void setProviderType(const QString &providerType)
Sets the providerType (provider key).
void mapTipsEnabledChanged()
Emitted when map tips are enabled or disabled for the layer.
virtual QString saveDefaultStyle(bool &resultFlag, StyleCategories categories)
Save the properties of this layer as the default style (either as a .qml file on disk or as a record ...
QFlags< SaveStyleResult > SaveStyleResults
Results of saving styles to database.
void setRenderer3D(QgsAbstract3DRenderer *renderer)
Sets 3D renderer for the layer.
~QgsMapLayer() override
QString customPropertyHtmlMetadata() const
Returns an HTML fragment containing custom property information, for use in the htmlMetadata() method...
const QgsObjectCustomProperties & customProperties() const
Read all custom properties from layer.
QString generalHtmlMetadata() const
Returns an HTML fragment containing general metadata information, for use in the htmlMetadata() metho...
Q_DECL_DEPRECATED QString metadataUrlType() const
Returns the metadata type of the layer used by QGIS Server in GetCapabilities request.
void writeCommonStyle(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const
Write style data common to all layer types.
double maximumScale() const
Returns the maximum map scale (i.e.
Q_DECL_DEPRECATED QString keywordList() const
Returns the keyword list of the layer used by QGIS Server in GetCapabilities request.
virtual void setLayerOrder(const QStringList &layers)
Reorders the previously selected sublayers of this layer from bottom to top.
void invalidateWgs84Extent()
Invalidates the WGS84 extent.
QString mapTipTemplate
Definition qgsmaplayer.h:96
Q_DECL_DEPRECATED void setTitle(const QString &title)
Sets the title of the layer used by QGIS Server in GetCapabilities request.
PropertyType
Maplayer has a style and a metadata property.
bool mShouldValidateCrs
true if the layer's CRS should be validated and invalid CRSes are not permitted.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Custom exception class which is raised when an operation is not supported.
Simple key-value store (keys = strings, values = variants) that supports loading/saving to/from XML i...
void readXml(const QDomNode &parentNode, const QString &keyStartsWith=QString())
Read store contents from an XML node.
An interface for classes which can visit various object entity (e.g.
A QgsObjectEntityVisitorInterface context object.
Contains information about a PROJ operation.
QString description() const
Description.
Convert from older project file versions to newer.
bool updateRevision(const QgsProjectVersion &version)
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
Describes the version of a project.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:113
bool removeAttachedFile(const QString &path)
Removes the attached file.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Holds data provider key, description, and associated shared library file or function pointer informat...
@ SaveLayerMetadata
Indicates that the provider supports saving native layer metadata.
QString getStyleById(const QString &providerKey, const QString &uri, const QString &styleId, QString &errCause)
Gets a layer style defined by styleId.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
bool saveLayerMetadata(const QString &providerKey, const QString &uri, const QgsLayerMetadata &metadata, QString &errorMessage)
Saves metadata to the layer corresponding to the specified uri.
bool deleteStyleById(const QString &providerKey, const QString &uri, const QString &styleId, QString &errCause)
Deletes a layer style defined by styleId.
QString loadStoredStyle(const QString &providerKey, const QString &uri, QString &styleName, QString &errCause)
Loads a layer style from the provider storage, reporting its name.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
int listStyles(const QString &providerKey, const QString &uri, QStringList &ids, QStringList &names, QStringList &descriptions, QString &errCause)
Lists stored layer styles in the provider defined by providerKey and uri.
Represents a raster layer.
Q_DECL_DEPRECATED bool writeSld(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QVariantMap &props=QVariantMap()) const
Writes the symbology of the layer into the document provided in SLD 1.0.0 format.
Allows entering a context category and takes care of leaving this category on deletion of the class.
A container for the context for various read/write operations on objects.
QgsReadWriteContextCategoryPopper enterCategory(const QString &category, const QString &details=QString()) const
Push a category to the stack.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
A rectangle specified with double values.
static bool equalToOrGreaterThanMinimumScale(const double scale, const double minScale)
Returns whether the scale is equal to or greater than the minScale, taking non-round numbers into acc...
static bool lessThanMaximumScale(const double scale, const double maxScale)
Returns whether the scale is less than the maxScale, taking non-round numbers into account.
void setMetadataUrls(const QList< QgsServerMetadataUrlProperties::MetadataUrl > &metaUrls)
Sets a the list of metadata URL for the layer.
QList< QgsServerMetadataUrlProperties::MetadataUrl > metadataUrls() const
Returns a list of metadataUrl resources associated for the layer.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
QString exportFilePath() const
Returns the export file path for the SLD.
QStringList errors() const
Returns a list of errors which occurred during the conversion.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
void setExportFilePath(const QString &exportFilePath)
Sets the export file path for the SLD to exportFilePath.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
void pushError(const QString &error)
Pushes a error message generated during the conversion.
static QString capitalize(const QString &string, Qgis::Capitalization capitalization)
Converts a string by applying capitalization rules to the string.
An interface for classes which can visit style entity (e.g.
static Q_INVOKABLE QString toString(Qgis::DistanceUnit unit)
Returns a translated string representing a distance unit.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
Q_DECL_DEPRECATED bool writeSld(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QVariantMap &props=QVariantMap()) const
Writes the symbology of the layer into the document provided in SLD 1.1 format.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
static T readFlagAttribute(const QDomElement &element, const QString &attributeName, T defaultValue)
Read a flag value from an attribute of the element.
static QgsBox3D readBox3D(const QDomElement &element)
Decodes a DOM element to a 3D box.
static QDomElement writeRectangle(const QgsRectangle &rect, QDomDocument &doc, const QString &elementName=u"extent"_s)
Encodes a rectangle to a DOM element.
static QgsRectangle readRectangle(const QDomElement &element)
static QDomElement writeBox3D(const QgsBox3D &box, QDomDocument &doc, const QString &elementName=u"extent3D"_s)
Encodes a 3D box to a DOM element.
Unique pointer for sqlite3 databases, which automatically closes the database when the pointer goes o...
sqlite3_statement_unique_ptr prepare(const QString &sql, int &resultCode) const
Prepares a sql statement, returning the result.
int open(const QString &path)
Opens the database at the specified file path.
int open_v2(const QString &path, int flags, const char *zVfs)
Opens the database at the specified file path.
Unique pointer for sqlite3 prepared statements, which automatically finalizes the statement when the ...
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:7278
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:6995
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7259
const QMap< T, QString > qgsEnumMap()
Returns a map of all enum entries.
Definition qgis.h:7242
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7077
void(* CUSTOM_CRS_VALIDATION)(QgsCoordinateReferenceSystem &)
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
#define QGIS_CHECK_QOBJECT_THREAD_EQUALITY(other)
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS_NON_FATAL
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS
Setting options for creating vector data providers.
QString format
Format specification of online resource.