QGIS API Documentation 4.3.0-Master (91d4a333d5d)
Loading...
Searching...
No Matches
qgsmaplayerutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmaplayerutils.cpp
3 -------------------
4 begin : May 2021
5 copyright : (C) 2021 Nyall Dawson
6 email : nyall dot dawson at gmail dot 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#include "qgsmaplayerutils.h"
19
24#include "qgslogger.h"
25#include "qgsmaplayer.h"
26#include "qgsprovidermetadata.h"
27#include "qgsproviderregistry.h"
28#include "qgsreadwritecontext.h"
29#include "qgsrectangle.h"
32#include "qgssldexportcontext.h"
33#include "qgsvectorlayer.h"
34
35#include <QRegularExpression>
36#include <QString>
37
38using namespace Qt::StringLiterals;
39
40QgsRectangle QgsMapLayerUtils::combinedExtent( const QList<QgsMapLayer *> &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext )
41{
42 // We can't use a constructor since QgsRectangle normalizes the rectangle upon construction
43 QgsRectangle fullExtent;
44 fullExtent.setNull();
45
46 // iterate through the map layers and test each layers extent
47 // against the current min and max values
48 QgsDebugMsgLevel( u"Layer count: %1"_s.arg( layers.count() ), 5 );
49 for ( const QgsMapLayer *layer : layers )
50 {
51 QgsDebugMsgLevel( "Updating extent using " + layer->name(), 5 );
52 QgsDebugMsgLevel( "Input extent: " + layer->extent().toString(), 5 );
53
54 if ( layer->extent().isNull() )
55 continue;
56
57 // Layer extents are stored in the coordinate system (CS) of the
58 // layer. The extent must be projected to the canvas CS
59 QgsCoordinateTransform ct( layer->crs(), crs, transformContext );
61 try
62 {
63 const QgsRectangle extent = ct.transformBoundingBox( layer->extent() );
64
65 QgsDebugMsgLevel( "Output extent: " + extent.toString(), 5 );
66 fullExtent.combineExtentWith( extent );
67 }
68 catch ( QgsCsException & )
69 {
70 QgsDebugError( u"Could not reproject layer extent"_s );
71 }
72 }
73
74 if ( fullExtent.width() == 0.0 || fullExtent.height() == 0.0 )
75 {
76 // If all of the features are at the one point, buffer the
77 // rectangle a bit. If they are all at zero, do something a bit
78 // more crude.
79
80 if ( fullExtent.xMinimum() == 0.0 && fullExtent.xMaximum() == 0.0 && fullExtent.yMinimum() == 0.0 && fullExtent.yMaximum() == 0.0 )
81 {
82 fullExtent.set( -1.0, -1.0, 1.0, 1.0 );
83 }
84 else
85 {
86 const double padFactor = 1e-8;
87 const double widthPad = fullExtent.xMinimum() * padFactor;
88 const double heightPad = fullExtent.yMinimum() * padFactor;
89 const double xmin = fullExtent.xMinimum() - widthPad;
90 const double xmax = fullExtent.xMaximum() + widthPad;
91 const double ymin = fullExtent.yMinimum() - heightPad;
92 const double ymax = fullExtent.yMaximum() + heightPad;
93 fullExtent.set( xmin, ymin, xmax, ymax );
94 }
95 }
96
97 QgsDebugMsgLevel( "Full extent: " + fullExtent.toString(), 5 );
98 return fullExtent;
99}
100
102{
103 if ( !layer )
104 {
105 return nullptr;
106 }
107
108 try
109 {
111 if ( !providerMetadata )
112 {
113 return nullptr;
114 }
115
116 std::unique_ptr< QgsAbstractDatabaseProviderConnection > conn { static_cast<QgsAbstractDatabaseProviderConnection *>( providerMetadata->createConnection( layer->source(), {} ) ) };
117 return conn.release();
118 }
119 catch ( const QgsProviderConnectionException &ex )
120 {
121 if ( !ex.what().contains( "createConnection"_L1 ) )
122 {
123 QgsDebugError( u"Error retrieving database connection for layer %1: %2"_s.arg( layer->name(), ex.what() ) );
124 }
125 return nullptr;
126 }
127}
128
129bool QgsMapLayerUtils::layerSourceMatchesPath( const QgsMapLayer *layer, const QString &path )
130{
131 if ( !layer || path.isEmpty() )
132 return false;
133
134 const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
135 return parts.value( u"path"_s ).toString() == path;
136}
137
138bool QgsMapLayerUtils::layerRefersToUri( const QgsMapLayer *layer, const QString &uri, Qgis::SourceHierarchyLevel level )
139{
140 if ( !layer )
141 return false;
142
144 if ( !metadata )
145 {
146 throw QgsNotSupportedException( u"Could not retrieve metadata for %1 provider"_s.arg( layer->providerType() ) );
147 }
148
150 {
151 throw QgsNotSupportedException( u"%1 provider does not support UrisReferToSame capability"_s.arg( layer->providerType() ) );
152 }
153
154 return metadata->urisReferToSame( layer->source(), uri, level );
155}
156
157bool QgsMapLayerUtils::updateLayerSourcePath( QgsMapLayer *layer, const QString &newPath )
158{
159 if ( !layer || newPath.isEmpty() )
160 return false;
161
162 QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
163 if ( !parts.contains( u"path"_s ) )
164 return false;
165
166 parts.insert( u"path"_s, newPath );
167 const QString newUri = QgsProviderRegistry::instance()->encodeUri( layer->providerType(), parts );
168 layer->setDataSource( newUri, layer->name(), layer->providerType() );
169 return true;
170}
171
172QList<QgsMapLayer *> QgsMapLayerUtils::sortLayersByType( const QList<QgsMapLayer *> &layers, const QList<Qgis::LayerType> &order )
173{
174 QList< QgsMapLayer * > res = layers;
175 std::sort( res.begin(), res.end(), [&order]( const QgsMapLayer *a, const QgsMapLayer *b ) -> bool {
176 for ( Qgis::LayerType type : order )
177 {
178 if ( a->type() == type && b->type() != type )
179 return true;
180 else if ( b->type() == type )
181 return false;
182 }
183 return false;
184 } );
185 return res;
186}
187
188QString QgsMapLayerUtils::launderLayerName( const QString &name )
189{
190 QString laundered = name.toLower();
191 const thread_local QRegularExpression sRxSwapChars( u"\\s"_s );
192 laundered.replace( sRxSwapChars, u"_"_s );
193
194 const thread_local QRegularExpression sRxRemoveChars( u"[^a-zA-Z0-9_]"_s );
195 laundered.replace( sRxRemoveChars, QString() );
196
197 return laundered;
198}
199
201{
202 if ( !layer )
203 {
204 return false;
205 }
206
207 return QgsMapLayerUtils::isOpenStreetMapUri( layer->source(), layer->providerType() );
208}
209
210bool QgsMapLayerUtils::isOpenStreetMapUri( const QString &uri, const QString &providerType )
211{
212 QUrl url;
213 if ( providerType == "wms"_L1 )
214 {
215 if ( const QgsProviderMetadata *metadata = QgsProviderRegistry::instance()->providerMetadata( providerType ) )
216 {
217 QVariantMap details = metadata->decodeUri( uri );
218 url = QUrl( details.value( u"url"_s ).toString() );
219 }
220 }
221 else if ( providerType == "xyzvectortiles"_L1 )
222 {
223 if ( const QgsProviderMetadata *metadata = QgsProviderRegistry::instance()->providerMetadata( providerType ) )
224 {
225 QVariantMap details = metadata->decodeUri( uri );
226 url = QUrl( details.value( u"url"_s ).toString() );
227 }
228 }
229 return !url.isEmpty() && ( url.host().endsWith( ".openstreetmap.org"_L1 ) || url.host().endsWith( ".osm.org"_L1 ) );
230}
231
233{
234 switch ( type )
235 {
237 return QObject::tr( "Vector" );
239 return QObject::tr( "Raster" );
241 return QObject::tr( "Mesh" );
243 return QObject::tr( "Point Cloud" );
245 return QObject::tr( "Annotation" );
247 return QObject::tr( "Vector Tile" );
249 return QObject::tr( "Plugin" );
251 return QObject::tr( "Group" );
253 return QObject::tr( "Tiled Scene" );
254 }
255 Q_ASSERT( false );
256 return QString();
257}
258
260{
261 if ( layer )
262 {
263 QStringList parts;
264 QString title = !layer->metadata().title().isEmpty() ? layer->metadata().title()
265 : ( layer->serverProperties()->title().isEmpty() ? layer->serverProperties()->shortName() : layer->serverProperties()->title() );
266 if ( title.isEmpty() )
267 title = layer->name();
268 title = "<b>" + title + "</b>";
269 if ( layer->isSpatial() && layer->crs().isValid() )
270 {
271 QString layerCrs = layer->crs().authid();
272 if ( !std::isnan( layer->crs().coordinateEpoch() ) )
273 {
274 layerCrs += u" @ %1"_s.arg( qgsDoubleToString( layer->crs().coordinateEpoch(), 3 ) );
275 }
276 if ( const QgsVectorLayer *vl = qobject_cast<const QgsVectorLayer *>( layer ) )
277 title = QObject::tr( "%1 (%2 - %3)" ).arg( title, QgsWkbTypes::displayString( vl->wkbType() ), layerCrs );
278 else
279 title = QObject::tr( "%1 (%2)" ).arg( title, layerCrs );
280 }
281 parts << title;
282
283 QString abstract = !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->serverProperties()->abstract();
284 if ( !abstract.isEmpty() )
285 parts << "<br/>" + abstract.replace( "\n"_L1, "<br/>"_L1 );
286 parts << "<i>" + layer->publicSource() + "</i>";
288 {
289 parts << QObject::tr( "ID: %1" ).arg( layer->id() );
290 }
291 return parts.join( "<br/>"_L1 );
292 }
293 return QString();
294}
295
297 QgsMapLayer *layer,
298 const QString &providerKey,
299 const QString &dataSource,
300 const QString &name,
301 const QString &description,
302 bool useAsDefault,
303 const QString &uiFileContent,
304 const Qgis::SaveStyleFormats formats,
306)
307{
308 QgsSaveStyleResult result;
309
310 QString sldStyle, qmlStyle, qmlError;
311
312 if ( formats.testFlag( Qgis::SaveStyleFormat::QML ) )
313 {
314 QDomDocument qmlDocument;
315 QgsReadWriteContext context;
316 layer->exportNamedStyle( qmlDocument, qmlError, context, categories );
317 if ( !qmlError.isEmpty() )
318 {
320 result.qmlError = qmlError;
321 }
322 else
323 {
324 qmlStyle = qmlDocument.toString();
325 }
326 }
327
328 if ( formats.testFlag( Qgis::SaveStyleFormat::SLD ) )
329 {
330 QgsSldExportContext sldContext;
331 QDomDocument sldDocument = layer->exportSldStyleV3( sldContext );
332 if ( !sldContext.errors().empty() )
333 {
335 result.sldErrorMessages.append( sldContext.errors() );
336 result.sldWarningMessages.append( sldContext.warnings() );
337 }
338 else
339 {
340 sldStyle = sldDocument.toString();
341 }
342 }
343
344 QString providerSaveStyleError;
345 if ( !QgsProviderRegistry::instance()->saveStyle( providerKey, dataSource, qmlStyle, sldStyle, name, description, uiFileContent, useAsDefault, providerSaveStyleError ) )
346 {
348 result.providerSaveStyleError = providerSaveStyleError;
349 }
350
351 return result;
352}
@ SLD
SLD style format.
Definition qgis.h:7348
@ QML
QML style format.
Definition qgis.h:7347
QFlags< SaveStyleFormat > SaveStyleFormats
Definition qgis.h:7351
LayerType
Types of layers that can be added to a map.
Definition qgis.h:206
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:214
@ Plugin
Plugin based layer.
Definition qgis.h:209
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
Definition qgis.h:215
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:212
@ Vector
Vector layer.
Definition qgis.h:207
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:211
@ Mesh
Mesh layer. Added in QGIS 3.2.
Definition qgis.h:210
@ Raster
Raster layer.
Definition qgis.h:208
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
Definition qgis.h:213
SourceHierarchyLevel
Defines the structural levels within a data source hierarchy.
Definition qgis.h:1547
Provides common functionality for database based connections.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
double coordinateEpoch() const
Returns the coordinate epoch, as a decimal year.
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.
QString what() const
QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
QString shortName() const
Returns the short name of the layer used by QGIS Server to identify the layer.
QString abstract() const
Returns the abstract of the layerused by QGIS Server in GetCapabilities request.
static QString layerToolTip(const QgsMapLayer *layer)
Returns the consistent tooltip for the given layer.
static bool updateLayerSourcePath(QgsMapLayer *layer, const QString &newPath)
Updates a layer's data source, replacing its data source with a path referring to newPath.
static QgsSaveStyleResult saveLayerStyleToDatabase(QgsMapLayer *layer, const QString &providerKey, const QString &targetDataSource, const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, const Qgis::SaveStyleFormats formats=Qgis::SaveStyleFormats(Qgis::SaveStyleFormat::QML|Qgis::SaveStyleFormat::SLD), QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Saves QML and SLD representations of layer's style to a table in the database identified by providerK...
static bool layerRefersToUri(const QgsMapLayer *layer, const QString &uri, Qgis::SourceHierarchyLevel level=Qgis::SourceHierarchyLevel::Object)
Returns true if a layer and uri point to the same resource at the specified hierarchy level.
static QgsRectangle combinedExtent(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext)
Returns the combined extent of a list of layers.
static QgsAbstractDatabaseProviderConnection * databaseConnection(const QgsMapLayer *layer)
Creates and returns the (possibly nullptr) database connection for a layer.
static QString layerTypeToString(Qgis::LayerType type)
Returns the translated name of the type for a given layer type.
static QList< QgsMapLayer * > sortLayersByType(const QList< QgsMapLayer * > &layers, const QList< Qgis::LayerType > &order)
Sorts a list of map layers by their layer type, respecting the order of types specified.
static QString launderLayerName(const QString &name)
Launders a layer's name, converting it into a format which is general suitable for file names or data...
static bool isOpenStreetMapLayer(QgsMapLayer *layer)
Returns true if the layer is served by OpenStreetMap server.
static bool layerSourceMatchesPath(const QgsMapLayer *layer, const QString &path)
Returns true if the source of the specified layer matches the given path.
static bool isOpenStreetMapUri(const QString &uri, const QString &providerType)
Returns true if the uri for a given provider is served by OpenStreetMap server.
Base class for all map layer types.
Definition qgsmaplayer.h:84
QString name
Definition qgsmaplayer.h:88
virtual bool isSpatial() const
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
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.
QString source() const
Returns the source for the layer.
@ 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.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:91
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
void setDataSource(const QString &dataSource, const QString &baseName=QString(), const QString &provider=QString(), bool loadDefaultStyleFlag=false)
Updates the data source of the layer.
QString id
Definition qgsmaplayer.h:87
QgsLayerMetadata metadata
Definition qgsmaplayer.h:90
QString publicSource(bool hidePassword=false) const
Gets a version of the internal layer definition that has sensitive bits removed (for example,...
QFlags< StyleCategory > StyleCategories
virtual QDomDocument exportSldStyleV3(QgsSldExportContext &exportContext) const
Export the properties of this layer as SLD style in a QDomDocument.
Custom exception class which is raised when an operation is not supported.
Custom exception class for provider connection related exceptions.
Holds data provider key, description, and associated shared library file or function pointer informat...
virtual bool urisReferToSame(const QString &uri1, const QString &uri2, Qgis::SourceHierarchyLevel level=Qgis::SourceHierarchyLevel::Object) const
Returns true if the URI uri1 and uri2 point to the same resource at the specified hierarchy level.
virtual QgsAbstractProviderConnection * createConnection(const QString &uri, const QVariantMap &configuration)
Creates a new connection from uri and configuration, the newly created connection is not automaticall...
@ UrisReferToSame
Indicates that the metadata can check whether layer URIs refer to the same object.
virtual QgsProviderMetadata::ProviderMetadataCapabilities capabilities() const
Returns the provider metadata capabilities.
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.
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be rounded to the spec...
double xMinimum
double yMinimum
double xMaximum
void set(const QgsPointXY &p1, const QgsPointXY &p2, bool normalize=true)
Sets the rectangle from two QgsPoints.
double yMaximum
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
void setNull()
Mark a rectangle as being null (holding no spatial information).
Represents the result of saving a style.
QStringList sldWarningMessages
List of warning messages generated while exporting the style to SLD.
QStringList sldErrorMessages
List of error messages generated while exporting the style to SLD.
QString qmlError
Error message generated while saving the style as QML, or an empty string if no error occurred.
QString providerSaveStyleError
Error message reported by the data provider when saving the style, or an empty string if no error occ...
QgsMapLayer::SaveStyleResults saveResult
Flags representing which style formats (QML and/or SLD) were successfully saved.
static const QgsSettingsEntryBool * settingsLayerTreeShowIdInLayerTooltips
Settings entry for hidden ID in layer tooltips.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
QStringList warnings() const
Returns a list of warnings which occurred during the conversion.
QStringList errors() const
Returns a list of errors which occurred during the conversion.
Represents a vector layer which manages a vector based dataset.
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:7718
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71