QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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 "qgsrectangle.h"
29
30#include <QRegularExpression>
31
32QgsRectangle QgsMapLayerUtils::combinedExtent( const QList<QgsMapLayer *> &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext )
33{
34 // We can't use a constructor since QgsRectangle normalizes the rectangle upon construction
35 QgsRectangle fullExtent;
36 fullExtent.setNull();
37
38 // iterate through the map layers and test each layers extent
39 // against the current min and max values
40 QgsDebugMsgLevel( QStringLiteral( "Layer count: %1" ).arg( layers.count() ), 5 );
41 for ( const QgsMapLayer *layer : layers )
42 {
43 QgsDebugMsgLevel( "Updating extent using " + layer->name(), 5 );
44 QgsDebugMsgLevel( "Input extent: " + layer->extent().toString(), 5 );
45
46 if ( layer->extent().isNull() )
47 continue;
48
49 // Layer extents are stored in the coordinate system (CS) of the
50 // layer. The extent must be projected to the canvas CS
51 QgsCoordinateTransform ct( layer->crs(), crs, transformContext );
53 try
54 {
55 const QgsRectangle extent = ct.transformBoundingBox( layer->extent() );
56
57 QgsDebugMsgLevel( "Output extent: " + extent.toString(), 5 );
58 fullExtent.combineExtentWith( extent );
59 }
60 catch ( QgsCsException & )
61 {
62 QgsDebugError( QStringLiteral( "Could not reproject layer extent" ) );
63 }
64 }
65
66 if ( fullExtent.width() == 0.0 || fullExtent.height() == 0.0 )
67 {
68 // If all of the features are at the one point, buffer the
69 // rectangle a bit. If they are all at zero, do something a bit
70 // more crude.
71
72 if ( fullExtent.xMinimum() == 0.0 && fullExtent.xMaximum() == 0.0 &&
73 fullExtent.yMinimum() == 0.0 && fullExtent.yMaximum() == 0.0 )
74 {
75 fullExtent.set( -1.0, -1.0, 1.0, 1.0 );
76 }
77 else
78 {
79 const double padFactor = 1e-8;
80 const double widthPad = fullExtent.xMinimum() * padFactor;
81 const double heightPad = fullExtent.yMinimum() * padFactor;
82 const double xmin = fullExtent.xMinimum() - widthPad;
83 const double xmax = fullExtent.xMaximum() + widthPad;
84 const double ymin = fullExtent.yMinimum() - heightPad;
85 const double ymax = fullExtent.yMaximum() + heightPad;
86 fullExtent.set( xmin, ymin, xmax, ymax );
87 }
88 }
89
90 QgsDebugMsgLevel( "Full extent: " + fullExtent.toString(), 5 );
91 return fullExtent;
92}
93
95{
96 if ( !layer )
97 {
98 return nullptr;
99 }
100
101 try
102 {
104 if ( ! providerMetadata )
105 {
106 return nullptr;
107 }
108
109 std::unique_ptr< QgsAbstractDatabaseProviderConnection > conn { static_cast<QgsAbstractDatabaseProviderConnection *>( providerMetadata->createConnection( layer->source(), {} ) ) };
110 return conn.release();
111 }
112 catch ( const QgsProviderConnectionException &ex )
113 {
114 if ( !ex.what().contains( QLatin1String( "createConnection" ) ) )
115 {
116 QgsDebugError( QStringLiteral( "Error retrieving database connection for layer %1: %2" ).arg( layer->name(), ex.what() ) );
117 }
118 return nullptr;
119 }
120}
121
122bool QgsMapLayerUtils::layerSourceMatchesPath( const QgsMapLayer *layer, const QString &path )
123{
124 if ( !layer || path.isEmpty() )
125 return false;
126
127 const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
128 return parts.value( QStringLiteral( "path" ) ).toString() == path;
129}
130
131bool QgsMapLayerUtils::updateLayerSourcePath( QgsMapLayer *layer, const QString &newPath )
132{
133 if ( !layer || newPath.isEmpty() )
134 return false;
135
136 QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
137 if ( !parts.contains( QStringLiteral( "path" ) ) )
138 return false;
139
140 parts.insert( QStringLiteral( "path" ), newPath );
141 const QString newUri = QgsProviderRegistry::instance()->encodeUri( layer->providerType(), parts );
142 layer->setDataSource( newUri, layer->name(), layer->providerType() );
143 return true;
144}
145
146QList<QgsMapLayer *> QgsMapLayerUtils::sortLayersByType( const QList<QgsMapLayer *> &layers, const QList<Qgis::LayerType> &order )
147{
148 QList< QgsMapLayer * > res = layers;
149 std::sort( res.begin(), res.end(), [&order]( const QgsMapLayer * a, const QgsMapLayer * b ) -> bool
150 {
151 for ( Qgis::LayerType type : order )
152 {
153 if ( a->type() == type && b->type() != type )
154 return true;
155 else if ( b->type() == type )
156 return false;
157 }
158 return false;
159 } );
160 return res;
161}
162
163QString QgsMapLayerUtils::launderLayerName( const QString &name )
164{
165 QString laundered = name.toLower();
166 const thread_local QRegularExpression sRxSwapChars( QStringLiteral( "\\s" ) );
167 laundered.replace( sRxSwapChars, QStringLiteral( "_" ) );
168
169 const thread_local QRegularExpression sRxRemoveChars( QStringLiteral( "[^a-zA-Z0-9_]" ) );
170 laundered.replace( sRxRemoveChars, QString() );
171
172 return laundered;
173}
174
176{
177 if ( layer->providerType() == QLatin1String( "wms" ) )
178 {
179 if ( const QgsProviderMetadata *metadata = layer->providerMetadata() )
180 {
181 QVariantMap details = metadata->decodeUri( layer->source() );
182 QUrl url( details.value( QStringLiteral( "url" ) ).toString() );
183 if ( url.host().endsWith( QLatin1String( ".openstreetmap.org" ) ) || url.host().endsWith( QLatin1String( ".osm.org" ) ) )
184 {
185 return true;
186 }
187 }
188 }
189 return false;
190}
191
193{
194 switch ( type )
195 {
197 return QObject::tr( "Vector" );
199 return QObject::tr( "Raster" );
201 return QObject::tr( "Mesh" );
203 return QObject::tr( "Point Cloud" );
205 return QObject::tr( "Annotation" );
207 return QObject::tr( "Vector Tile" );
209 return QObject::tr( "Plugin" );
211 return QObject::tr( "Group" );
213 return QObject::tr( "Tiled Scene" );
214 }
215 Q_ASSERT( false );
216 return QString();
217}
LayerType
Types of layers that can be added to a map.
Definition qgis.h:190
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:198
@ Plugin
Plugin based layer.
Definition qgis.h:193
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
Definition qgis.h:199
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:196
@ Vector
Vector layer.
Definition qgis.h:191
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:195
@ Mesh
Mesh layer. Added in QGIS 3.2.
Definition qgis.h:194
@ Raster
Raster layer.
Definition qgis.h:192
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
Definition qgis.h:197
Provides common functionality for database based connections.
Represents a coordinate reference system (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.
QString what() const
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 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.
Base class for all map layer types.
Definition qgsmaplayer.h:80
QString name
Definition qgsmaplayer.h:84
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
void setDataSource(const QString &dataSource, const QString &baseName=QString(), const QString &provider=QString(), bool loadDefaultStyleFlag=false)
Updates the data source of the layer.
QgsProviderMetadata * providerMetadata() const
Returns the layer data provider's metadata, it may be nullptr.
Custom exception class for provider connection related exceptions.
Holds data provider key, description, and associated shared library file or function pointer informat...
virtual QgsAbstractProviderConnection * createConnection(const QString &uri, const QVariantMap &configuration)
Creates a new connection from uri and configuration, the newly created connection is not automaticall...
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 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 truncated to the sp...
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).
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:61
#define QgsDebugError(str)
Definition qgslogger.h:57