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