QGIS API Documentation 4.3.0-Master (0cef2469b72)
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 "qgsmaplayerutils.h"
39#include "qgsmessagelog.h"
40#include "qgsobjectvisitor.h"
41#include "qgspathresolver.h"
42#include "qgsproject.h"
44#include "qgsprojoperation.h"
45#include "qgsprovidermetadata.h"
46#include "qgsproviderregistry.h"
47#include "qgsrasterlayer.h"
48#include "qgsreadwritecontext.h"
49#include "qgsrectangle.h"
50#include "qgsscaleutils.h"
51#include "qgssldexportcontext.h"
52#include "qgssqliteutils.h"
53#include "qgsstringutils.h"
54#include "qgsthreadingutils.h"
55#include "qgsunittypes.h"
56#include "qgsvectorlayer.h"
57#include "qgsxmlutils.h"
58
59#include <QDir>
60#include <QDomDocument>
61#include <QDomElement>
62#include <QDomImplementation>
63#include <QDomNode>
64#include <QFile>
65#include <QFileInfo>
66#include <QLocale>
67#include <QRegularExpression>
68#include <QStandardPaths>
69#include <QString>
70#include <QTextStream>
71#include <QTimer>
72#include <QUrl>
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( new 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 mServerProperties->copyTo( layer->serverProperties() );
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 )
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 QString projectFileName;
1643 if ( QgsProject *lProject = project() )
1644 {
1645 projectFileName = lProject->fileName();
1646 }
1647
1648 const QFileInfo project( projectFileName );
1649 QgsDebugMsgLevel( u"project fileName: %1"_s.arg( project.absoluteFilePath() ), 4 );
1650
1651 QString xml;
1652 switch ( type )
1653 {
1654 case QgsMapLayer::Style:
1655 {
1656 if ( loadNamedStyleFromDatabase( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ), uri, xml )
1657 || ( project.exists() && loadNamedStyleFromDatabase( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), uri, xml ) )
1658 || loadNamedStyleFromDatabase( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( u"resources/qgis.qmldb"_s ), uri, xml ) )
1659 {
1660 namedPropertyExists = true;
1661 propertySuccessfullyLoaded = myDocument.setContent( xml, &myErrorMessage, &line, &column );
1662 if ( !propertySuccessfullyLoaded )
1663 {
1664 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
1665 }
1666 }
1667 else
1668 {
1670 {
1671 myErrorMessage = tr( "Style not found in database" );
1672 }
1673 }
1674 break;
1675 }
1677 {
1678 if ( loadNamedMetadataFromDatabase( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ), uri, xml )
1679 || ( project.exists() && loadNamedMetadataFromDatabase( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), uri, xml ) )
1680 || loadNamedMetadataFromDatabase( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( u"resources/qgis.qmldb"_s ), uri, xml ) )
1681 {
1682 namedPropertyExists = true;
1683 propertySuccessfullyLoaded = myDocument.setContent( xml, &myErrorMessage, &line, &column );
1684 if ( !propertySuccessfullyLoaded )
1685 {
1686 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
1687 }
1688 }
1689 else
1690 {
1691 myErrorMessage = tr( "Metadata not found in database" );
1692 }
1693 break;
1694 }
1695 }
1696 }
1697
1698 if ( !propertySuccessfullyLoaded )
1699 {
1700 return myErrorMessage;
1701 }
1702
1703 switch ( type )
1704 {
1705 case QgsMapLayer::Style:
1706 propertySuccessfullyLoaded = importNamedStyle( myDocument, myErrorMessage, categories );
1707 if ( !propertySuccessfullyLoaded )
1708 myErrorMessage = tr( "Loading style file %1 failed because:\n%2" ).arg( uri, myErrorMessage );
1709 break;
1711 propertySuccessfullyLoaded = importNamedMetadata( myDocument, myErrorMessage );
1712 if ( !propertySuccessfullyLoaded )
1713 myErrorMessage = tr( "Loading metadata file %1 failed because:\n%2" ).arg( uri, myErrorMessage );
1714 break;
1715 }
1716 return myErrorMessage;
1717}
1718
1719bool QgsMapLayer::importNamedMetadata( QDomDocument &document, QString &errorMessage )
1720{
1722
1723 const QDomElement myRoot = document.firstChildElement( u"qgis"_s );
1724 if ( myRoot.isNull() )
1725 {
1726 errorMessage = tr( "Root <qgis> element could not be found" );
1727 return false;
1728 }
1729
1730 return mMetadata.readMetadataXml( myRoot );
1731}
1732
1733bool QgsMapLayer::importNamedStyle( QDomDocument &myDocument, QString &myErrorMessage, QgsMapLayer::StyleCategories categories )
1734{
1736
1737 const QDomElement myRoot = myDocument.firstChildElement( u"qgis"_s );
1738 if ( myRoot.isNull() )
1739 {
1740 myErrorMessage = tr( "Root <qgis> element could not be found" );
1741 return false;
1742 }
1743
1744 // get style file version string, if any
1745 const QgsProjectVersion fileVersion( myRoot.attribute( u"version"_s ) );
1746 const QgsProjectVersion thisVersion( Qgis::version() );
1747
1748 if ( thisVersion > fileVersion )
1749 {
1750 QgsProjectFileTransform styleFile( myDocument, fileVersion );
1751 styleFile.updateRevision( thisVersion );
1752 }
1753
1754 // Get source categories
1755 const QgsMapLayer::StyleCategories sourceCategories = QgsXmlUtils::readFlagAttribute( myRoot, u"styleCategories"_s, QgsMapLayer::AllStyleCategories );
1756
1757 //Test for matching geometry type on vector layers when applying, if geometry type is given in the style
1758 if ( ( sourceCategories.testFlag( QgsMapLayer::Symbology ) || sourceCategories.testFlag( QgsMapLayer::Symbology3D ) )
1759 && ( categories.testFlag( QgsMapLayer::Symbology ) || categories.testFlag( QgsMapLayer::Symbology3D ) ) )
1760 {
1761 if ( type() == Qgis::LayerType::Vector && !myRoot.firstChildElement( u"layerGeometryType"_s ).isNull() )
1762 {
1763 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( this );
1764 const Qgis::GeometryType importLayerGeometryType = static_cast<Qgis::GeometryType>( myRoot.firstChildElement( u"layerGeometryType"_s ).text().toInt() );
1765 if ( importLayerGeometryType != Qgis::GeometryType::Unknown && vl->geometryType() != importLayerGeometryType )
1766 {
1767 myErrorMessage = tr( "Cannot apply style with symbology to layer with a different geometry type" );
1768 return false;
1769 }
1770 }
1771 }
1772
1773 // Pass the intersection between the desired categories and those that are really in the document
1775 return readSymbology( myRoot, myErrorMessage, context, categories & sourceCategories ); // TODO: support relative paths in QML?
1776}
1777
1778void QgsMapLayer::exportNamedMetadata( QDomDocument &doc, QString &errorMsg ) const
1779{
1781
1782 QDomImplementation DomImplementation;
1783 const QDomDocumentType documentType = DomImplementation.createDocumentType( u"qgis"_s, u"http://mrcc.com/qgis.dtd"_s, u"SYSTEM"_s );
1784 QDomDocument myDocument( documentType );
1785
1786 QDomElement myRootNode = myDocument.createElement( u"qgis"_s );
1787 myRootNode.setAttribute( u"version"_s, Qgis::version() );
1788 myDocument.appendChild( myRootNode );
1789
1790 if ( !mMetadata.writeMetadataXml( myRootNode, myDocument ) )
1791 {
1792 errorMsg = QObject::tr( "Could not save metadata" );
1793 return;
1794 }
1795
1796 doc = myDocument;
1797}
1798
1799void QgsMapLayer::exportNamedStyle( QDomDocument &doc, QString &errorMsg, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories ) const
1800{
1802
1803 QDomImplementation DomImplementation;
1804 const QDomDocumentType documentType = DomImplementation.createDocumentType( u"qgis"_s, u"http://mrcc.com/qgis.dtd"_s, u"SYSTEM"_s );
1805 QDomDocument myDocument( documentType );
1806
1807 QDomElement myRootNode = myDocument.createElement( u"qgis"_s );
1808 myRootNode.setAttribute( u"version"_s, Qgis::version() );
1809 myDocument.appendChild( myRootNode );
1810
1811 if ( !writeSymbology( myRootNode, myDocument, errorMsg, context, categories ) ) // TODO: support relative paths in QML?
1812 {
1813 errorMsg = QObject::tr( "Could not save symbology because:\n%1" ).arg( errorMsg );
1814 return;
1815 }
1816
1817 /*
1818 * Check to see if the layer is vector - in which case we should also export its geometryType
1819 * to avoid eventually pasting to a layer with a different geometry
1820 */
1821 if ( type() == Qgis::LayerType::Vector )
1822 {
1823 //Getting the selectionLayer geometry
1824 const QgsVectorLayer *vl = qobject_cast<const QgsVectorLayer *>( this );
1825 const QString geoType = QString::number( static_cast<int>( vl->geometryType() ) );
1826
1827 //Adding geometryinformation
1828 QDomElement layerGeometryType = myDocument.createElement( u"layerGeometryType"_s );
1829 const QDomText type = myDocument.createTextNode( geoType );
1830
1831 layerGeometryType.appendChild( type );
1832 myRootNode.appendChild( layerGeometryType );
1833 }
1834
1835 doc = myDocument;
1836}
1837
1838QString QgsMapLayer::saveDefaultStyle( bool &resultFlag )
1839{
1841
1842 return saveDefaultStyle( resultFlag, AllStyleCategories );
1843}
1844
1845QString QgsMapLayer::saveDefaultStyle( bool &resultFlag, StyleCategories categories )
1846{
1848
1849 return saveNamedStyle( styleURI(), resultFlag, categories );
1850}
1851
1852QString QgsMapLayer::saveNamedMetadata( const QString &uri, bool &resultFlag )
1853{
1855
1856 return saveNamedProperty( uri, QgsMapLayer::Metadata, resultFlag );
1857}
1858
1859QString QgsMapLayer::loadNamedMetadata( const QString &uri, bool &resultFlag )
1860{
1862
1863 bool metadataExists = false;
1864 bool metadataSuccessfullyLoaded = false;
1865 const QString message = loadNamedProperty( uri, QgsMapLayer::Metadata, metadataExists, metadataSuccessfullyLoaded );
1866
1867 // TODO QGIS 5.0 -- fix API for loadNamedMetadata so we can return metadataExists too
1868 ( void ) metadataExists;
1869 resultFlag = metadataSuccessfullyLoaded;
1870 return message;
1871}
1872
1873QString QgsMapLayer::saveNamedProperty( const QString &uri, QgsMapLayer::PropertyType type, bool &resultFlag, StyleCategories categories )
1874{
1876
1877 // check if the uri is a file or ends with .qml/.qmd,
1878 // which indicates that it should become one
1879 // everything else goes to the database
1880 QString filename;
1881
1882 QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
1883 if ( vlayer && vlayer->providerType() == "ogr"_L1 )
1884 {
1885 QStringList theURIParts = uri.split( '|' );
1886 filename = theURIParts[0];
1887 }
1888 else if ( vlayer && vlayer->providerType() == "gpx"_L1 )
1889 {
1890 QStringList theURIParts = uri.split( '?' );
1891 filename = theURIParts[0];
1892 }
1893 else if ( vlayer && vlayer->providerType() == "delimitedtext"_L1 )
1894 {
1895 filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile();
1896 // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml"
1897 if ( filename.isEmpty() )
1898 filename = uri;
1899 }
1900 else
1901 {
1902 filename = uri;
1903 }
1904
1905 QString myErrorMessage;
1906 QDomDocument myDocument;
1907 switch ( type )
1908 {
1909 case Metadata:
1910 exportNamedMetadata( myDocument, myErrorMessage );
1911 break;
1912
1913 case Style:
1914 const QgsReadWriteContext context;
1915 exportNamedStyle( myDocument, myErrorMessage, context, categories );
1916 break;
1917 }
1918
1919 const QFileInfo myFileInfo( filename );
1920 if ( myFileInfo.exists() || filename.endsWith( QgsMapLayer::extensionPropertyType( type ), Qt::CaseInsensitive ) )
1921 {
1922 const QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name
1923 if ( !myDirInfo.isWritable() )
1924 {
1925 resultFlag = false;
1926 return tr( "The directory containing your dataset needs to be writable!" );
1927 }
1928
1929 // now construct the file name for our .qml or .qmd file
1930 const QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + QgsMapLayer::extensionPropertyType( type );
1931
1932 QFile myFile( myFileName );
1933 if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
1934 {
1935 QTextStream myFileStream( &myFile );
1936 // save as utf-8 with 2 spaces for indents
1937 myDocument.save( myFileStream, 2 );
1938 myFile.close();
1939 resultFlag = true;
1940 switch ( type )
1941 {
1942 case Metadata:
1943 return tr( "Created default metadata file as %1" ).arg( myFileName );
1944
1945 case Style:
1946 return tr( "Created default style file as %1" ).arg( myFileName );
1947 }
1948 }
1949 else
1950 {
1951 resultFlag = false;
1952 switch ( type )
1953 {
1954 case Metadata:
1955 return tr( "ERROR: Failed to created default metadata file as %1. Check file permissions and retry." ).arg( myFileName );
1956
1957 case Style:
1958 return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
1959 }
1960 }
1961 }
1962 else
1963 {
1964 const QString qml = myDocument.toString();
1965
1966 // read from database
1967 sqlite3_database_unique_ptr database;
1968 sqlite3_statement_unique_ptr statement;
1969
1970 int myResult = database.open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( u"qgis.qmldb"_s ) );
1971 if ( myResult != SQLITE_OK )
1972 {
1973 return tr( "User database could not be opened." );
1974 }
1975
1976 QByteArray param0 = uri.toUtf8();
1977 QByteArray param1 = qml.toUtf8();
1978
1979 QString mySql;
1980 switch ( type )
1981 {
1982 case Metadata:
1983 mySql = u"create table if not exists tbl_metadata(metadata varchar primary key,qmd varchar)"_s;
1984 break;
1985
1986 case Style:
1987 mySql = u"create table if not exists tbl_styles(style varchar primary key,qml varchar)"_s;
1988 break;
1989 }
1990
1991 statement = database.prepare( mySql, myResult );
1992 if ( myResult == SQLITE_OK )
1993 {
1994 if ( sqlite3_step( statement.get() ) != SQLITE_DONE )
1995 {
1996 resultFlag = false;
1997 switch ( type )
1998 {
1999 case Metadata:
2000 return tr( "The metadata table could not be created." );
2001
2002 case Style:
2003 return tr( "The style table could not be created." );
2004 }
2005 }
2006 }
2007
2008 switch ( type )
2009 {
2010 case Metadata:
2011 mySql = u"insert into tbl_metadata(metadata,qmd) values (?,?)"_s;
2012 break;
2013
2014 case Style:
2015 mySql = u"insert into tbl_styles(style,qml) values (?,?)"_s;
2016 break;
2017 }
2018 statement = database.prepare( mySql, myResult );
2019 if ( myResult == SQLITE_OK )
2020 {
2021 if ( sqlite3_bind_text( statement.get(), 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK
2022 && sqlite3_bind_text( statement.get(), 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK
2023 && sqlite3_step( statement.get() ) == SQLITE_DONE )
2024 {
2025 resultFlag = true;
2026 switch ( type )
2027 {
2028 case Metadata:
2029 myErrorMessage = tr( "The metadata %1 was saved to database" ).arg( uri );
2030 break;
2031
2032 case Style:
2033 myErrorMessage = tr( "The style %1 was saved to database" ).arg( uri );
2034 break;
2035 }
2036 }
2037 }
2038
2039 if ( !resultFlag )
2040 {
2041 QString mySql;
2042 switch ( type )
2043 {
2044 case Metadata:
2045 mySql = u"update tbl_metadata set qmd=? where metadata=?"_s;
2046 break;
2047
2048 case Style:
2049 mySql = u"update tbl_styles set qml=? where style=?"_s;
2050 break;
2051 }
2052 statement = database.prepare( mySql, myResult );
2053 if ( myResult == SQLITE_OK )
2054 {
2055 if ( sqlite3_bind_text( statement.get(), 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK
2056 && sqlite3_bind_text( statement.get(), 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK
2057 && sqlite3_step( statement.get() ) == SQLITE_DONE )
2058 {
2059 resultFlag = true;
2060 switch ( type )
2061 {
2062 case Metadata:
2063 myErrorMessage = tr( "The metadata %1 was updated in the database." ).arg( uri );
2064 break;
2065
2066 case Style:
2067 myErrorMessage = tr( "The style %1 was updated in the database." ).arg( uri );
2068 break;
2069 }
2070 }
2071 else
2072 {
2073 resultFlag = false;
2074 switch ( type )
2075 {
2076 case Metadata:
2077 myErrorMessage = tr( "The metadata %1 could not be updated in the database." ).arg( uri );
2078 break;
2079
2080 case Style:
2081 myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( uri );
2082 break;
2083 }
2084 }
2085 }
2086 else
2087 {
2088 resultFlag = false;
2089 switch ( type )
2090 {
2091 case Metadata:
2092 myErrorMessage = tr( "The metadata %1 could not be inserted into database." ).arg( uri );
2093 break;
2094
2095 case Style:
2096 myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( uri );
2097 break;
2098 }
2099 }
2100 }
2101 }
2102
2103 return myErrorMessage;
2104}
2105
2106QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag, StyleCategories categories )
2107{
2109
2110 return saveNamedProperty( uri, QgsMapLayer::Style, resultFlag, categories );
2111}
2112
2113void QgsMapLayer::exportSldStyle( QDomDocument &doc, QString &errorMsg ) const
2114{
2115 QgsSldExportContext exportContext;
2116 doc = exportSldStyleV3( exportContext );
2117 if ( !exportContext.errors().empty() )
2118 errorMsg = exportContext.errors().join( "\n" );
2119}
2120
2121void QgsMapLayer::exportSldStyleV2( QDomDocument &doc, QString &errorMsg, QgsSldExportContext &exportContext ) const
2122{
2124 doc = exportSldStyleV3( exportContext );
2125 if ( !exportContext.errors().empty() )
2126 errorMsg = exportContext.errors().join( "\n" );
2127}
2128
2129QDomDocument QgsMapLayer::exportSldStyleV3( QgsSldExportContext &exportContext ) const
2130{
2132
2133 QDomDocument myDocument = QDomDocument();
2134
2135 const QDomNode header = myDocument.createProcessingInstruction( u"xml"_s, u"version=\"1.0\" encoding=\"UTF-8\""_s );
2136 myDocument.appendChild( header );
2137
2138 const QgsVectorLayer *vlayer = qobject_cast<const QgsVectorLayer *>( this );
2139 const QgsRasterLayer *rlayer = qobject_cast<const QgsRasterLayer *>( this );
2140 if ( !vlayer && !rlayer )
2141 {
2142 exportContext.pushError( tr( "Could not save symbology because:\n%1" ).arg( tr( "Only vector and raster layers are supported" ) ) );
2143 return myDocument;
2144 }
2145
2146 // Create the root element
2147 QDomElement root = myDocument.createElementNS( u"http://www.opengis.net/sld"_s, u"StyledLayerDescriptor"_s );
2148 QDomElement layerNode;
2149 if ( vlayer )
2150 {
2151 root.setAttribute( u"version"_s, u"1.1.0"_s );
2152 root.setAttribute( u"xsi:schemaLocation"_s, u"http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd"_s );
2153 root.setAttribute( u"xmlns:ogc"_s, u"http://www.opengis.net/ogc"_s );
2154 root.setAttribute( u"xmlns:se"_s, u"http://www.opengis.net/se"_s );
2155 root.setAttribute( u"xmlns:xlink"_s, u"http://www.w3.org/1999/xlink"_s );
2156 root.setAttribute( u"xmlns:xsi"_s, u"http://www.w3.org/2001/XMLSchema-instance"_s );
2157 myDocument.appendChild( root );
2158
2159 // Create the NamedLayer element
2160 layerNode = myDocument.createElement( u"NamedLayer"_s );
2161 root.appendChild( layerNode );
2162 }
2163
2164 // note: Only SLD 1.0 version is generated because seems none is using SE1.1.0 at least for rasters
2165 if ( rlayer )
2166 {
2167 // Create the root element
2168 root.setAttribute( u"version"_s, u"1.0.0"_s );
2169 root.setAttribute( u"xmlns:gml"_s, u"http://www.opengis.net/gml"_s );
2170 root.setAttribute( u"xmlns:ogc"_s, u"http://www.opengis.net/ogc"_s );
2171 root.setAttribute( u"xmlns:sld"_s, u"http://www.opengis.net/sld"_s );
2172 myDocument.appendChild( root );
2173
2174 // Create the NamedLayer element
2175 layerNode = myDocument.createElement( u"UserLayer"_s );
2176 root.appendChild( layerNode );
2177 }
2178
2179 QVariantMap props = exportContext.extraProperties();
2180
2181 QVariant context;
2182 context.setValue( exportContext );
2183
2184 // TODO -- move this to proper members of QgsSldExportContext
2185 props[u"SldExportContext"_s] = context;
2186
2188 {
2189 props[u"scaleMinDenom"_s] = QString::number( mMinScale );
2190 props[u"scaleMaxDenom"_s] = QString::number( mMaxScale );
2191 }
2192 exportContext.setExtraProperties( props );
2193
2194 if ( vlayer )
2195 {
2196 if ( !vlayer->writeSld( layerNode, myDocument, exportContext ) )
2197 {
2198 return myDocument;
2199 }
2200 }
2201 else if ( rlayer )
2202 {
2203 if ( !rlayer->writeSld( layerNode, myDocument, exportContext ) )
2204 {
2205 return myDocument;
2206 }
2207 }
2208
2209 return myDocument;
2210}
2211
2212QString QgsMapLayer::saveSldStyle( const QString &uri, bool &resultFlag ) const
2213{
2214 QgsSldExportContext context;
2215 context.setExportFilePath( uri );
2216 return saveSldStyleV2( resultFlag, context );
2217}
2218
2219QString QgsMapLayer::saveSldStyleV2( bool &resultFlag, QgsSldExportContext &exportContext ) const
2220{
2222
2223 const QgsMapLayer *mlayer = qobject_cast<const QgsMapLayer *>( this );
2224
2225 const QString uri { exportContext.exportFilePath() };
2226
2227 // check if the uri is a file or ends with .sld,
2228 // which indicates that it should become one
2229 QString filename;
2230 if ( mlayer->providerType() == "ogr"_L1 )
2231 {
2232 QStringList theURIParts = uri.split( '|' );
2233 filename = theURIParts[0];
2234 }
2235 else if ( mlayer->providerType() == "gpx"_L1 )
2236 {
2237 QStringList theURIParts = uri.split( '?' );
2238 filename = theURIParts[0];
2239 }
2240 else if ( mlayer->providerType() == "delimitedtext"_L1 )
2241 {
2242 filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile();
2243 // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml"
2244 if ( filename.isEmpty() )
2245 filename = uri;
2246 }
2247 else
2248 {
2249 filename = uri;
2250 }
2251
2252 const QFileInfo myFileInfo( filename );
2253 if ( myFileInfo.exists() || filename.endsWith( ".sld"_L1, Qt::CaseInsensitive ) )
2254 {
2255 const QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name
2256 if ( !myDirInfo.isWritable() )
2257 {
2258 resultFlag = false;
2259 return tr( "The directory containing your dataset needs to be writable!" );
2260 }
2261
2262 // now construct the file name for our .sld style file
2263 const QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".sld";
2264
2265 QgsSldExportContext context { exportContext };
2266 context.setExportFilePath( myFileName );
2267
2268 QDomDocument myDocument = mlayer->exportSldStyleV3( context );
2269
2270 if ( !context.errors().empty() )
2271 {
2272 resultFlag = false;
2273 return context.errors().join( '\n' );
2274 }
2275
2276 QFile myFile( myFileName );
2277 if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
2278 {
2279 QTextStream myFileStream( &myFile );
2280 // save as utf-8 with 2 spaces for indents
2281 myDocument.save( myFileStream, 2 );
2282 myFile.close();
2283 resultFlag = true;
2284 return tr( "Created default style file as %1" ).arg( myFileName );
2285 }
2286 }
2287
2288 resultFlag = false;
2289 return tr( "ERROR: Failed to created SLD style file as %1. Check file permissions and retry." ).arg( filename );
2290}
2291
2292QString QgsMapLayer::loadSldStyle( const QString &uri, bool &resultFlag )
2293{
2295
2296 resultFlag = false;
2297
2298 QDomDocument myDocument;
2299
2300 // location of problem associated with errorMsg
2301 int line = 0, column = 0;
2302 QString myErrorMessage;
2303
2304 QFile myFile( uri );
2305 if ( myFile.open( QFile::ReadOnly ) )
2306 {
2307 // read file
2308#if QT_VERSION >= QT_VERSION_CHECK( 6, 5, 0 )
2309 QXmlStreamReader xmlReader( &myFile );
2310 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"sld"_s, u"http://www.opengis.net/sld"_s ) );
2311 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"fes"_s, u"http://www.opengis.net/fes/2.0"_s ) );
2312 xmlReader.addExtraNamespaceDeclaration( QXmlStreamNamespaceDeclaration( u"ogc"_s, u"http://www.opengis.net/ogc"_s ) );
2313 const QDomDocument::ParseResult result = myDocument.setContent( &xmlReader, QDomDocument::ParseOption::UseNamespaceProcessing );
2314 if ( result )
2315 {
2316 resultFlag = true;
2317 }
2318 else
2319 {
2320 myErrorMessage = result.errorMessage;
2321 line = result.errorLine;
2322 column = result.errorColumn;
2323 }
2324#else
2325 resultFlag = myDocument.setContent( &myFile, true, &myErrorMessage, &line, &column );
2326#endif
2327 if ( !resultFlag )
2328 myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
2329 myFile.close();
2330 }
2331 else
2332 {
2333 myErrorMessage = tr( "Unable to open file %1" ).arg( uri );
2334 }
2335
2336 if ( !resultFlag )
2337 {
2338 return myErrorMessage;
2339 }
2340
2341 // check for root SLD element
2342 const QDomElement myRoot = myDocument.firstChildElement( u"StyledLayerDescriptor"_s );
2343 if ( myRoot.isNull() )
2344 {
2345 myErrorMessage = u"Error: StyledLayerDescriptor element not found in %1"_s.arg( uri );
2346 resultFlag = false;
2347 return myErrorMessage;
2348 }
2349
2350 // now get the style node out and pass it over to the layer
2351 // to deserialise...
2352 const QDomElement namedLayerElem = myRoot.firstChildElement( u"NamedLayer"_s );
2353 if ( namedLayerElem.isNull() )
2354 {
2355 myErrorMessage = u"Info: NamedLayer element not found."_s;
2356 resultFlag = false;
2357 return myErrorMessage;
2358 }
2359
2360 QString errorMsg;
2361 resultFlag = readSld( namedLayerElem, errorMsg );
2362 if ( !resultFlag )
2363 {
2364 myErrorMessage = tr( "Loading style file %1 failed because:\n%2" ).arg( uri, errorMsg );
2365 return myErrorMessage;
2366 }
2367
2368 return QString();
2369}
2370
2371bool QgsMapLayer::readStyle( const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories )
2372{
2374
2375 Q_UNUSED( node )
2376 Q_UNUSED( errorMessage )
2377 Q_UNUSED( context )
2378 Q_UNUSED( categories )
2379 return false;
2380}
2381
2382bool QgsMapLayer::writeStyle( QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories ) const
2383{
2385
2386 Q_UNUSED( node )
2387 Q_UNUSED( doc )
2388 Q_UNUSED( errorMessage )
2389 Q_UNUSED( context )
2390 Q_UNUSED( categories )
2391 return false;
2392}
2393
2394
2395void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, bool loadDefaultStyleFlag )
2396{
2398
2400
2402 if ( loadDefaultStyleFlag )
2403 {
2405 }
2406
2408 {
2410 }
2411 setDataSource( dataSource, baseName.isEmpty() ? mLayerName : baseName, provider.isEmpty() ? mProviderKey : provider, options, flags );
2412}
2413
2414void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, bool loadDefaultStyleFlag )
2415{
2417
2419 if ( loadDefaultStyleFlag )
2420 {
2422 }
2423
2425 {
2427 }
2428 setDataSource( dataSource, baseName, provider, options, flags );
2429}
2430
2431void QgsMapLayer::setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
2432{
2434
2436 {
2438 }
2439 setDataSourcePrivate( dataSource, baseName, provider, options, flags );
2440 emit dataSourceChanged();
2441 emit dataChanged();
2443}
2444
2445
2446void QgsMapLayer::setDataSourcePrivate( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
2447{
2449
2450 Q_UNUSED( dataSource )
2451 Q_UNUSED( baseName )
2452 Q_UNUSED( provider )
2453 Q_UNUSED( options )
2454 Q_UNUSED( flags )
2455}
2456
2457
2459{
2461
2462 return mProviderKey;
2463}
2464
2465void QgsMapLayer::readCommonStyle( const QDomElement &layerElement, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories )
2466{
2468
2469 if ( categories.testFlag( Symbology3D ) )
2470 {
2471 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "3D Symbology" ) );
2472
2473 QgsAbstract3DRenderer *r3D = nullptr;
2474 QDomElement renderer3DElem = layerElement.firstChildElement( u"renderer-3d"_s );
2475 if ( !renderer3DElem.isNull() )
2476 {
2477 const QString type3D = renderer3DElem.attribute( u"type"_s );
2479 if ( meta3D )
2480 {
2481 r3D = meta3D->createRenderer( renderer3DElem, context );
2482 }
2483 }
2484 setRenderer3D( r3D );
2485 }
2486
2487 if ( categories.testFlag( CustomProperties ) )
2488 {
2489 // read custom properties before passing reading further to a subclass, so that
2490 // the subclass can also read custom properties
2491 readCustomProperties( layerElement );
2492 }
2493
2494 // use scale dependent visibility flag
2495 if ( categories.testFlag( Rendering ) )
2496 {
2497 setScaleBasedVisibility( layerElement.attribute( u"hasScaleBasedVisibilityFlag"_s ).toInt() == 1 );
2498 if ( layerElement.hasAttribute( u"minimumScale"_s ) )
2499 {
2500 // older element, when scales were reversed
2501 setMaximumScale( layerElement.attribute( u"minimumScale"_s ).toDouble() );
2502 setMinimumScale( layerElement.attribute( u"maximumScale"_s ).toDouble() );
2503 }
2504 else
2505 {
2506 setMaximumScale( layerElement.attribute( u"maxScale"_s ).toDouble() );
2507 setMinimumScale( layerElement.attribute( u"minScale"_s ).toDouble() );
2508 }
2509 if ( layerElement.hasAttribute( u"autoRefreshMode"_s ) )
2510 {
2511 setAutoRefreshInterval( layerElement.attribute( u"autoRefreshTime"_s ).toInt() );
2512 setAutoRefreshMode( qgsEnumKeyToValue( layerElement.attribute( u"autoRefreshMode"_s ), Qgis::AutoRefreshMode::Disabled ) );
2513 }
2514 }
2515
2516 if ( categories.testFlag( LayerConfiguration ) )
2517 {
2518 // flags
2519 const QDomElement flagsElem = layerElement.firstChildElement( u"flags"_s );
2520 LayerFlags flags = mFlags;
2521 const auto enumMap = qgsEnumMap<QgsMapLayer::LayerFlag>();
2522 for ( auto it = enumMap.constBegin(); it != enumMap.constEnd(); ++it )
2523 {
2524 const QDomNode flagNode = flagsElem.namedItem( it.value() );
2525 if ( flagNode.isNull() )
2526 continue;
2527 const bool flagValue = flagNode.toElement().text() == "1" ? true : false;
2528 if ( flags.testFlag( it.key() ) && !flagValue )
2529 flags &= ~it.key();
2530 else if ( !flags.testFlag( it.key() ) && flagValue )
2531 flags |= it.key();
2532 }
2533 setFlags( flags );
2534 }
2535
2536 if ( categories.testFlag( Temporal ) )
2537 {
2538 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "Temporal" ) );
2539
2541 properties->readXml( layerElement.toElement(), context );
2542 }
2543
2544 if ( categories.testFlag( Elevation ) )
2545 {
2546 const QgsReadWriteContextCategoryPopper p = context.enterCategory( tr( "Elevation" ) );
2547
2549 properties->readXml( layerElement.toElement(), context );
2550 }
2551
2552 if ( categories.testFlag( Notes ) )
2553 {
2554 const QDomElement notesElem = layerElement.firstChildElement( u"userNotes"_s );
2555 if ( !notesElem.isNull() )
2556 {
2557 const QString notes = notesElem.attribute( u"value"_s );
2558 QgsLayerNotesUtils::setLayerNotes( this, notes );
2559 }
2560 }
2561}
2562
2564{
2566
2567 return mUndoStack;
2568}
2569
2571{
2573
2574 return mUndoStackStyles;
2575}
2576
2578{
2580
2581 return mCustomProperties.keys();
2582}
2583
2584void QgsMapLayer::setCustomProperty( const QString &key, const QVariant &value )
2585{
2587
2588 if ( !mCustomProperties.contains( key ) || mCustomProperties.value( key ) != value )
2589 {
2590 mCustomProperties.setValue( key, value );
2591 emit customPropertyChanged( key );
2592 }
2593}
2594
2596{
2598
2599 mCustomProperties = properties;
2600 for ( const QString &key : mCustomProperties.keys() )
2601 {
2602 emit customPropertyChanged( key );
2603 }
2604}
2605
2607{
2609
2610 return mCustomProperties;
2611}
2612
2613QVariant QgsMapLayer::customProperty( const QString &value, const QVariant &defaultValue ) const
2614{
2615 // non fatal for now -- the "rasterize" processing algorithm is not thread safe and calls this
2617
2618 return mCustomProperties.value( value, defaultValue );
2619}
2620
2621void QgsMapLayer::removeCustomProperty( const QString &key )
2622{
2624
2625 if ( mCustomProperties.contains( key ) )
2626 {
2627 mCustomProperties.remove( key );
2628 emit customPropertyChanged( key );
2629 }
2630}
2631
2632int QgsMapLayer::listStylesInDatabase( QStringList &ids, QStringList &names, QStringList &descriptions, QString &msgError )
2633{
2635
2636 return QgsProviderRegistry::instance()->listStyles( mProviderKey, mDataSource, ids, names, descriptions, msgError );
2637}
2638
2639QString QgsMapLayer::getStyleFromDatabase( const QString &styleId, QString &msgError )
2640{
2642
2643 return QgsProviderRegistry::instance()->getStyleById( mProviderKey, mDataSource, styleId, msgError );
2644}
2645
2646bool QgsMapLayer::deleteStyleFromDatabase( const QString &styleId, QString &msgError )
2647{
2649
2651}
2652
2653void QgsMapLayer::saveStyleToDatabase( const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories )
2654{
2655 saveStyleToDatabaseV2( name, description, useAsDefault, uiFileContent, msgError, categories );
2656}
2657
2659 const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError, QgsMapLayer::StyleCategories categories
2660)
2661{
2663
2666 msgError = result.providerSaveStyleError.isEmpty() ? result.qmlError : result.providerSaveStyleError;
2667 return result.saveResult;
2668}
2669
2671 const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, const Qgis::SaveStyleFormats formats, QgsMapLayer::StyleCategories categories
2672)
2673{
2675
2676 return QgsMapLayerUtils::saveLayerStyleToDatabase( this, mProviderKey, mDataSource, name, description, useAsDefault, uiFileContent, formats, categories );
2677}
2678
2679QString QgsMapLayer::loadNamedStyle( const QString &theURI, bool &resultFlag, bool loadFromLocalDB, QgsMapLayer::StyleCategories categories, Qgis::LoadStyleFlags flags )
2680{
2682
2683 QString returnMessage;
2684 QString qml, errorMsg;
2685 QString styleName;
2686 if ( !loadFromLocalDB && dataProvider() && dataProvider()->styleStorageCapabilities().testFlag( Qgis::ProviderStyleStorageCapability::LoadFromDatabase ) )
2687 {
2689 }
2690
2691 // Style was successfully loaded from provider storage
2692 if ( !qml.isEmpty() )
2693 {
2694 QDomDocument myDocument( u"qgis"_s );
2695 myDocument.setContent( qml );
2696 resultFlag = importNamedStyle( myDocument, errorMsg );
2697 returnMessage = QObject::tr( "Loaded from Provider" );
2698 }
2699 else
2700 {
2702
2703 bool styleExists = false;
2704 bool styleSuccessfullyLoaded = false;
2705
2706 returnMessage = loadNamedProperty( theURI, PropertyType::Style, styleExists, styleSuccessfullyLoaded, categories, flags );
2707
2708 // TODO QGIS 5.0 -- fix API for loadNamedStyle so we can return styleExists too
2709 ( void ) styleExists;
2710 resultFlag = styleSuccessfullyLoaded;
2711 }
2712
2713 if ( !styleName.isEmpty() )
2714 {
2715 styleManager()->renameStyle( styleManager()->currentStyle(), styleName );
2716 }
2717
2718 if ( resultFlag )
2719 emit styleLoaded( categories );
2720
2721 return returnMessage;
2722}
2723
2730
2732{
2734
2735 return false;
2736}
2737
2739{
2741
2742 return false;
2743}
2744
2746{
2748
2749 return true;
2750}
2751
2753{
2755
2756 // invalid layers are temporary? -- who knows?!
2757 if ( !isValid() )
2758 return false;
2759
2760 if ( mProviderKey == "memory"_L1 )
2761 return true;
2762
2763 const QVariantMap sourceParts = QgsProviderRegistry::instance()->decodeUri( mProviderKey, mDataSource );
2764 const QString path = sourceParts.value( u"path"_s ).toString();
2765 if ( path.isEmpty() )
2766 return false;
2767
2768 const QFileInfo fileInfo( path );
2769 const QString cleanedPath = QDir::cleanPath( fileInfo.canonicalFilePath() );
2770
2771 // check if layer path is inside one of the standard temporary file locations for this platform
2772 const QStringList tempPaths = QStandardPaths::standardLocations( QStandardPaths::TempLocation );
2773 for ( const QString &tempPath : std::as_const( tempPaths ) )
2774 {
2775#if defined( Q_OS_WIN )
2776 if ( cleanedPath.startsWith( tempPath, Qt::CaseSensitivity::CaseInsensitive ) )
2777#else
2778 if ( cleanedPath.startsWith( tempPath, Qt::CaseSensitivity::CaseSensitive ) )
2779#endif
2780 return true;
2781 }
2782
2783 return false;
2784}
2785
2786void QgsMapLayer::setValid( bool valid )
2787{
2789
2790 if ( mValid == valid )
2791 return;
2792
2793 mValid = valid;
2794 emit isValidChanged();
2795}
2796
2798{
2800
2801 if ( legend == mLegend )
2802 return;
2803
2804 delete mLegend;
2805 mLegend = legend;
2806
2807 if ( mLegend )
2808 {
2809 mLegend->setParent( this );
2810 connect( mLegend, &QgsMapLayerLegend::itemsChanged, this, &QgsMapLayer::legendChanged, Qt::UniqueConnection );
2811 }
2812
2813 emit legendChanged();
2814}
2815
2817{
2819
2820 return mLegend;
2821}
2822
2824{
2826
2827 return mStyleManager;
2828}
2829
2831{
2833
2834 if ( renderer == m3DRenderer.get() )
2835 return;
2836
2837 m3DRenderer.reset( renderer );
2838
2839 emit renderer3DChanged();
2841}
2842
2844{
2846
2847 return m3DRenderer.get();
2848}
2849
2850void QgsMapLayer::triggerRepaint( bool deferredUpdate )
2851{
2853
2854 if ( mRepaintRequestedFired )
2855 return;
2856 mRepaintRequestedFired = true;
2857 emit repaintRequested( deferredUpdate );
2858 mRepaintRequestedFired = false;
2859}
2860
2867
2869{
2871
2872 mMetadata = metadata;
2873 // mMetadata.saveToLayer( this );
2874 emit metadataChanged();
2875}
2876
2878{
2880
2881 return QString();
2882}
2883
2884QDateTime QgsMapLayer::timestamp() const
2885{
2887
2888 return QDateTime();
2889}
2890
2898
2900{
2901 updateExtent( extent );
2902}
2903
2905{
2907
2908 updateExtent( extent );
2909}
2910
2911bool QgsMapLayer::isReadOnly() const
2912{
2914
2915 return true;
2916}
2917
2919{
2921
2922 return mOriginalXmlProperties;
2923}
2924
2926{
2928
2929 mOriginalXmlProperties = originalXmlProperties;
2930}
2931
2932QString QgsMapLayer::generateId( const QString &layerName )
2933{
2934 constexpr int UUID_SUFFIX_LENGTH = 36 + 1;
2935 constexpr int MAX_ID_LENGTH = 100;
2936 constexpr int MAX_PREFIX_LENGTH = MAX_ID_LENGTH - UUID_SUFFIX_LENGTH;
2937
2938 // cap length of layer name to avoid potentially huge names
2939 const QString prefix = layerName.left( MAX_PREFIX_LENGTH );
2940
2941 return QgsStringUtils::createUniqueId( prefix );
2942}
2943
2945{
2947
2948 return true;
2949}
2950
2957
2959{
2961
2962 return mapTipsEnabled() && !mMapTipTemplate.isEmpty();
2963}
2964
2971
2972QSet<QgsMapLayerDependency> QgsMapLayer::dependencies() const
2973{
2975
2976 return mDependencies;
2977}
2978
2979bool QgsMapLayer::setDependencies( const QSet<QgsMapLayerDependency> &oDeps )
2980{
2982
2983 QSet<QgsMapLayerDependency> deps;
2984 const auto constODeps = oDeps;
2985 for ( const QgsMapLayerDependency &dep : constODeps )
2986 {
2987 if ( dep.origin() == QgsMapLayerDependency::FromUser )
2988 deps << dep;
2989 }
2990
2991 mDependencies = deps;
2992 emit dependenciesChanged();
2993 return true;
2994}
2995
2997{
2999
3000 QgsDataProvider *lDataProvider = dataProvider();
3001
3002 if ( !lDataProvider )
3003 return;
3004
3005 if ( enabled && !isRefreshOnNotifyEnabled() )
3006 {
3007 lDataProvider->setListening( enabled );
3008 connect( lDataProvider, &QgsDataProvider::notify, this, &QgsMapLayer::onNotified );
3009 }
3010 else if ( !enabled && isRefreshOnNotifyEnabled() )
3011 {
3012 // we don't want to disable provider listening because someone else could need it (e.g. actions)
3013 disconnect( lDataProvider, &QgsDataProvider::notify, this, &QgsMapLayer::onNotified );
3014 }
3015 mIsRefreshOnNofifyEnabled = enabled;
3016}
3017
3019{
3020 // aggregate based tests aren't thread safe
3022
3023 if ( QgsMapLayerStore *store = qobject_cast<QgsMapLayerStore *>( parent() ) )
3024 {
3025 return qobject_cast<QgsProject *>( store->parent() );
3026 }
3027 return nullptr;
3028}
3029
3030void QgsMapLayer::onNotified( const QString &message )
3031{
3033
3034 if ( refreshOnNotifyMessage().isEmpty() || refreshOnNotifyMessage() == message )
3035 {
3037 emit dataChanged();
3038 }
3039}
3040
3041QgsRectangle QgsMapLayer::wgs84Extent( bool forceRecalculate ) const
3042{
3044
3045 if ( !crs().isEarthCrs() )
3046 {
3047 return QgsRectangle();
3048 }
3049
3050 // if this function is called without previous call to extent() it will return empty rectangle as both mExtent2D and mExtent3D are null
3051 // to avoid this call extent here to force extent calculation
3052 ( void ) extent();
3053
3055
3056 if ( !forceRecalculate && !mWgs84Extent.isNull() )
3057 {
3058 wgs84Extent = mWgs84Extent;
3059 }
3060 else if ( !mExtent2D.isNull() || !mExtent3D.isNull() )
3061 {
3062 QgsCoordinateTransform transformer { crs(), QgsCoordinateReferenceSystem( u"EPSG:4326"_s ), transformContext() };
3063 transformer.setBallparkTransformsAreAppropriate( true );
3064 try
3065 {
3066 if ( mExtent2D.isNull() )
3067 wgs84Extent = transformer.transformBoundingBox( mExtent3D.toRectangle() );
3068 else
3069 wgs84Extent = transformer.transformBoundingBox( mExtent2D );
3070 }
3071 catch ( const QgsCsException &cse )
3072 {
3073 QgsMessageLog::logMessage( tr( "Error transforming extent: %1" ).arg( cse.what() ) );
3075 }
3076 }
3077 return wgs84Extent;
3078}
3079
3080void QgsMapLayer::updateExtent( const QgsRectangle &extent ) const
3081{
3083
3084 if ( extent == mExtent2D )
3085 return;
3086
3087 mExtent2D = extent;
3088
3089 // do not update the wgs84 extent if we trust layer metadata
3091 return;
3092
3093 mWgs84Extent = wgs84Extent( true );
3094}
3095
3096void QgsMapLayer::updateExtent( const QgsBox3D &extent ) const
3097{
3099
3100 if ( extent == mExtent3D )
3101 return;
3102
3103 if ( extent.isNull() )
3104 {
3105 if ( !extent.toRectangle().isNull() )
3106 {
3107 // bad 3D extent param but valid in 2d --> update 2D extent
3108 updateExtent( extent.toRectangle() );
3109 }
3110 else
3111 {
3112 QgsDebugMsgLevel( u"Unable to update extent with empty parameter"_s, 1 );
3113 }
3114 }
3115 else
3116 {
3117 mExtent3D = extent;
3118
3119 // do not update the wgs84 extent if we trust layer metadata
3121 return;
3122
3123 mWgs84Extent = wgs84Extent( true );
3124 }
3125}
3126
3127bool QgsMapLayer::rebuildCrs3D( QString *error )
3128{
3129 bool res = true;
3130 if ( !mCRS.isValid() )
3131 {
3132 mCrs3D = QgsCoordinateReferenceSystem();
3133 }
3134 else if ( !mVerticalCrs.isValid() )
3135 {
3136 mCrs3D = mCRS;
3137 }
3138 else
3139 {
3140 switch ( mCRS.type() )
3141 {
3145 mCrs3D = mCRS;
3146 break;
3147
3149 {
3150 QString tempError;
3151 mCrs3D = mCRS.hasVerticalAxis() ? mCRS : QgsCoordinateReferenceSystem::createCompoundCrs( mCRS, mVerticalCrs, error ? *error : tempError );
3152 res = mCrs3D.isValid();
3153 break;
3154 }
3155
3157 // nonsense situation
3158 mCrs3D = QgsCoordinateReferenceSystem();
3159 res = false;
3160 break;
3161
3170 {
3171 QString tempError;
3172 mCrs3D = QgsCoordinateReferenceSystem::createCompoundCrs( mCRS, mVerticalCrs, error ? *error : tempError );
3173 res = mCrs3D.isValid();
3174 break;
3175 }
3176 }
3177 }
3178 return res;
3179}
3180
3182{
3184
3185 // do not update the wgs84 extent if we trust layer metadata
3187 return;
3188
3189 mWgs84Extent = QgsRectangle();
3190}
3191
3193{
3195
3196 QString metadata = u"<h1>"_s + tr( "General" ) + u"</h1>\n<hr>\n"_s + u"<table class=\"list-view\">\n"_s;
3197
3198 // name
3199 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Name" ) + u"</td><td>"_s + name() + u"</td></tr>\n"_s;
3200
3201 const QString lPublicSource = publicSource();
3202
3203 QString path;
3204 bool isLocalPath = false;
3205 if ( dataProvider() )
3206 {
3207 // local path
3208 QVariantMap uriComponents = QgsProviderRegistry::instance()->decodeUri( dataProvider()->name(), lPublicSource );
3209 if ( uriComponents.contains( u"path"_s ) )
3210 {
3211 path = uriComponents[u"path"_s].toString();
3212 QFileInfo fi( path );
3213 if ( fi.exists() )
3214 {
3215 isLocalPath = true;
3216 metadata += u"<tr><td class=\"highlight\">"_s
3217 + tr( "Path" )
3218 + u"</td><td>%1"_s.arg( u"<a href=\"%1\">%2</a>"_s.arg( QUrl::fromLocalFile( path ).toString(), QDir::toNativeSeparators( path ) ) )
3219 + u"</td></tr>\n"_s;
3220
3221 QDateTime lastModified = fi.lastModified();
3222 QString lastModifiedFileName;
3223 QSet<QString> sidecarFiles = QgsFileUtils::sidecarFilesForPath( path );
3224 if ( fi.isFile() )
3225 {
3226 qint64 fileSize = fi.size();
3227 if ( !sidecarFiles.isEmpty() )
3228 {
3229 lastModifiedFileName = fi.fileName();
3230 QStringList sidecarFileNames;
3231 for ( const QString &sidecarFile : sidecarFiles )
3232 {
3233 QFileInfo sidecarFi( sidecarFile );
3234 fileSize += sidecarFi.size();
3235 if ( sidecarFi.lastModified() > lastModified )
3236 {
3237 lastModified = sidecarFi.lastModified();
3238 lastModifiedFileName = sidecarFi.fileName();
3239 }
3240 sidecarFileNames << sidecarFi.fileName();
3241 }
3242 metadata += u"<tr><td class=\"highlight\">"_s
3243 + ( sidecarFiles.size() > 1 ? tr( "Sidecar files" ) : tr( "Sidecar file" ) )
3244 + u"</td><td>%1"_s.arg( sidecarFileNames.join( ", "_L1 ) )
3245 + u"</td></tr>\n"_s;
3246 }
3247 metadata += u"<tr><td class=\"highlight\">"_s
3248 + ( !sidecarFiles.isEmpty() ? tr( "Total size" ) : tr( "Size" ) )
3249 + u"</td><td>%1"_s.arg( QgsFileUtils::representFileSize( fileSize ) )
3250 + u"</td></tr>\n"_s;
3251 }
3252 metadata += u"<tr><td class=\"highlight\">"_s
3253 + tr( "Last modified" )
3254 + u"</td><td>%1"_s.arg( QLocale().toString( fi.lastModified() ) )
3255 + ( !lastModifiedFileName.isEmpty() ? u" (%1)"_s.arg( lastModifiedFileName ) : QString() )
3256 + u"</td></tr>\n"_s;
3257 }
3258 }
3259 if ( uriComponents.contains( u"url"_s ) )
3260 {
3261 QUrl decodedUri = QUrl::fromPercentEncoding( uriComponents[u"url"_s].toString().toLocal8Bit() );
3262 const QString url = decodedUri.toString();
3263 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;
3264 }
3265 }
3266
3267 // data source
3268 if ( lPublicSource != path || !isLocalPath )
3269 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Source" ) + u"</td><td>%1"_s.arg( lPublicSource != path ? lPublicSource : path ) + u"</td></tr>\n"_s;
3270
3271 // provider
3272 if ( dataProvider() )
3273 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Provider" ) + u"</td><td>%1"_s.arg( dataProvider()->name() ) + u"</td></tr>\n"_s;
3274
3275 // Layer ID
3276 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Layer ID" ) + u"</td><td>%1"_s.arg( id() ) + u"</td></tr>\n"_s;
3277
3278 metadata += "</table>\n<br><br>"_L1;
3279
3280 return metadata;
3281}
3282
3284{
3285 QString metadata;
3286 // custom properties
3287 if ( const auto keys = customPropertyKeys(); !keys.isEmpty() )
3288 {
3289 metadata += u"<h1>"_s + tr( "Custom properties" ) + u"</h1>\n<hr>\n"_s;
3290 metadata += "<table class=\"list-view\">\n<tbody>"_L1;
3291 for ( const QString &key : keys )
3292 {
3293 // keys prefaced with _ are considered private/internal details
3294 if ( key.startsWith( '_' ) )
3295 continue;
3296
3297 const QVariant propValue = customProperty( key );
3298 QString stringValue;
3299 if ( propValue.typeId() == QMetaType::Type::QVariantList || propValue.typeId() == QMetaType::Type::QStringList )
3300 {
3301 for ( const QString &s : propValue.toStringList() )
3302 {
3303 stringValue += "<p style=\"margin: 0;\">" + s.toHtmlEscaped() + "</p>";
3304 }
3305 }
3306 else
3307 {
3308 stringValue = propValue.toString().toHtmlEscaped();
3309
3310 //if the result string is empty but propValue is not, the conversion has failed
3311 if ( stringValue.isEmpty() && !QgsVariantUtils::isNull( propValue ) )
3312 stringValue = tr( "<i>value cannot be displayed</i>" );
3313 }
3314
3315 metadata += u"<tr><td class=\"highlight\">%1</td><td>%2</td></tr>"_s.arg( key.toHtmlEscaped(), stringValue );
3316 }
3317 metadata += "</tbody></table>\n"_L1;
3318 metadata += "<br><br>\n"_L1;
3319 }
3320 return metadata;
3321}
3322
3324{
3326 QString metadata;
3327
3328 auto addCrsInfo = [&metadata]( const QgsCoordinateReferenceSystem &c, bool includeType, bool includeOperation, bool includeCelestialBody ) {
3329 if ( !c.isValid() )
3330 metadata += u"<tr><td colspan=\"2\" class=\"highlight\">"_s + tr( "Unknown" ) + u"</td></tr>\n"_s;
3331 else
3332 {
3333 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Name" ) + u"</td><td>"_s + c.userFriendlyIdentifier( Qgis::CrsIdentifierType::FullString ) + u"</td></tr>\n"_s;
3334
3335 // map units
3336 metadata += u"<tr><td class=\"highlight\">"_s
3337 + tr( "Units" )
3338 + u"</td><td>"_s
3339 + ( c.isGeographic() ? tr( "Geographic (uses latitude and longitude for coordinates)" ) : QgsUnitTypes::toString( c.mapUnits() ) )
3340 + u"</td></tr>\n"_s;
3341
3342 if ( includeType )
3343 {
3344 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Type" ) + u"</td><td>"_s + QgsCoordinateReferenceSystemUtils::crsTypeToString( c.type() ) + u"</td></tr>\n"_s;
3345 }
3346
3347 if ( includeOperation )
3348 {
3349 // operation
3350 const QgsProjOperation operation = c.operation();
3351 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Method" ) + u"</td><td>"_s + operation.description() + u"</td></tr>\n"_s;
3352 }
3353
3354 if ( includeCelestialBody )
3355 {
3356 // celestial body
3357 try
3358 {
3359 const QString celestialBody = c.celestialBodyName();
3360 if ( !celestialBody.isEmpty() )
3361 {
3362 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Celestial Body" ) + u"</td><td>"_s + celestialBody + u"</td></tr>\n"_s;
3363 }
3364 }
3365 catch ( QgsNotSupportedException & )
3366 {}
3367 }
3368
3369 QString accuracyString;
3370 // dynamic crs with no epoch?
3371 if ( c.isDynamic() && std::isnan( c.coordinateEpoch() ) )
3372 {
3373 accuracyString = tr( "Based on a dynamic CRS, but no coordinate epoch is set. Coordinates are ambiguous and of limited accuracy." );
3374 }
3375
3376 // based on datum ensemble?
3377 try
3378 {
3379 const QgsDatumEnsemble ensemble = c.datumEnsemble();
3380 if ( ensemble.isValid() )
3381 {
3382 QString id;
3383 if ( !ensemble.code().isEmpty() )
3384 id = u"<i>%1</i> (%2:%3)"_s.arg( ensemble.name(), ensemble.authority(), ensemble.code() );
3385 else
3386 id = u"<i>%1</i>”"_s.arg( ensemble.name() );
3387
3388 if ( ensemble.accuracy() > 0 )
3389 {
3390 accuracyString = tr( "Based on %1, which has a limited accuracy of <b>at best %2 meters</b>." ).arg( id ).arg( ensemble.accuracy() );
3391 }
3392 else
3393 {
3394 accuracyString = tr( "Based on %1, which has a limited accuracy." ).arg( id );
3395 }
3396 }
3397 }
3398 catch ( QgsNotSupportedException & )
3399 {}
3400
3401 if ( !accuracyString.isEmpty() )
3402 {
3403 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Accuracy" ) + u"</td><td>"_s + accuracyString + u"</td></tr>\n"_s;
3404 }
3405
3406 // static/dynamic
3407 metadata += u"<tr><td class=\"highlight\">"_s
3408 + tr( "Reference" )
3409 + 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)" ) );
3410
3411 // coordinate epoch
3412 if ( !std::isnan( c.coordinateEpoch() ) )
3413 {
3414 metadata += u"<tr><td class=\"highlight\">"_s + tr( "Coordinate Epoch" ) + u"</td><td>%1</td></tr>\n"_s.arg( qgsDoubleToString( c.coordinateEpoch(), 3 ) );
3415 }
3416 }
3417 };
3418
3419 metadata += u"<h1>"_s + tr( "Coordinate Reference System (CRS)" ) + u"</h1>\n<hr>\n"_s;
3420 metadata += "<table class=\"list-view\">\n"_L1;
3421 addCrsInfo( crs().horizontalCrs(), true, true, true );
3422 metadata += "</table>\n<br><br>\n"_L1;
3423
3424 if ( verticalCrs().isValid() )
3425 {
3426 metadata += u"<h1>"_s + tr( "Vertical Coordinate Reference System (CRS)" ) + u"</h1>\n<hr>\n"_s;
3427 metadata += "<table class=\"list-view\">\n"_L1;
3428 addCrsInfo( verticalCrs(), false, false, false );
3429 metadata += "</table>\n<br><br>\n"_L1;
3430 }
3431
3432 return metadata;
3433}
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:2606
@ SLD
SLD style format.
Definition qgis.h:7348
@ QML
QML style format.
Definition qgis.h:7347
@ Vertical
Vertical CRS.
Definition qgis.h:2519
@ Temporal
Temporal CRS.
Definition qgis.h:2522
@ Compound
Compound (horizontal + vertical) CRS.
Definition qgis.h:2521
@ Projected
Projected CRS.
Definition qgis.h:2520
@ Other
Other type.
Definition qgis.h:2525
@ Bound
Bound CRS.
Definition qgis.h:2524
@ DerivedProjected
Derived projected CRS.
Definition qgis.h:2526
@ Unknown
Unknown type.
Definition qgis.h:2514
@ Engineering
Engineering CRS.
Definition qgis.h:2523
@ Geographic3d
3D geopraphic CRS
Definition qgis.h:2518
@ Geodetic
Geodetic CRS.
Definition qgis.h:2515
@ Geographic2d
2D geographic CRS
Definition qgis.h:2517
@ Geocentric
Geocentric CRS.
Definition qgis.h:2516
@ RemoveCredentials
Completely remove credentials (eg passwords) from the URI. This flag is not compatible with the Redac...
Definition qgis.h:1528
@ RedactCredentials
Replace the value of credentials (eg passwords) with 'xxxxxxxx'. This flag is not compatible with the...
Definition qgis.h:1529
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
Definition qgis.h:3643
QFlags< SaveStyleFormat > SaveStyleFormats
Definition qgis.h:7351
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:399
@ Unknown
Unknown types.
Definition qgis.h:403
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:532
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:2471
QFlags< LoadStyleFlag > LoadStyleFlags
Flags for loading layer styles.
Definition qgis.h:283
@ LoadDefaultStyle
Reset the layer's style to the default for the datasource.
Definition qgis.h:515
@ ForceReadOnly
Open layer in a read-only mode.
Definition qgis.h:518
@ SkipGetExtent
Skip the extent from provider.
Definition qgis.h:516
@ TrustDataSource
Trust datasource config (primary key unicity, geometry type and srid, etc). Improves provider load ti...
Definition qgis.h:512
@ 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:273
AutoRefreshMode
Map layer automatic refresh modes.
Definition qgis.h:2481
@ RedrawOnly
Redraw current data only.
Definition qgis.h:2484
@ ReloadData
Reload data (and draw the new data).
Definition qgis.h:2483
@ Disabled
Automatic refreshing is disabled.
Definition qgis.h:2482
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.
@ FromUser
Dependency given by the user.
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 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.
static QgsSaveStyleResult saveLayerStyleToDatabase(QgsMapLayer *layer, const QString &providerKey, const QString &targetDataSource, const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, const Qgis::SaveStyleFormats formats=Qgis::SaveStyleFormats(Qgis::SaveStyleFormat::QML|Qgis::SaveStyleFormat::SLD), QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Saves QML and SLD representations of layer's style to a table in the database identified by providerK...
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:88
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.
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:93
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:91
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:87
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:90
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:94
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
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 the layer with the specified 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:98
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:96
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...
QgsSaveStyleResult saveStyleToDatabaseV3(const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, const Qgis::SaveStyleFormats formats, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Saves selected representation of the layer's style to a table in the database.
int autoRefreshInterval
Definition qgsmaplayer.h:89
QgsCoordinateReferenceSystem verticalCrs
Definition qgsmaplayer.h:92
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:97
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:114
bool removeAttachedFile(const QString &path)
Removes the attached file.
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.
Represents the result of saving a style.
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.
static QString createUniqueId(const QString &base=QString())
Generates a unique identifier by appending a random UUID to base.
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:8104
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:7718
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:8085
const QMap< T, QString > qgsEnumMap()
Returns a map of all enum entries.
Definition qgis.h:8068
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
void(* CUSTOM_CRS_VALIDATION)(QgsCoordinateReferenceSystem &)
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
#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.