QGIS API Documentation 3.40.0-Bratislava (b56115d8743)
Loading...
Searching...
No Matches
qgsmbtilesvectortiledataprovider.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmbtilesvectortiledataprovider.cpp
3 --------------------------------------
4 Date : March 2020
5 Copyright : (C) 2020 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17#include "qgsthreadingutils.h"
18#include "qgsmbtiles.h"
19#include "qgstiles.h"
20#include "qgsvectortileloader.h"
21#include "qgsziputils.h"
22#include "qgslogger.h"
23#include "qgsapplication.h"
25#include "qgsproviderutils.h"
27
28#include <QIcon>
29#include <QFileInfo>
30
32
33QString QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY = QStringLiteral( "mbtilesvectortiles" );
34QString QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION = QObject::tr( "MBTile Vector Tiles data provider" );
35
36QgsMbTilesVectorTileDataProvider::QgsMbTilesVectorTileDataProvider( const QString &uri, const ProviderOptions &providerOptions, Qgis::DataProviderReadFlags flags )
37 : QgsVectorTileDataProvider( uri, providerOptions, flags )
38{
39 QgsDataSourceUri dsUri;
40 dsUri.setEncodedUri( uri );
41 const QString sourcePath = dsUri.param( QStringLiteral( "url" ) );
42
43 QgsMbTiles reader( sourcePath );
44 if ( !reader.open() )
45 {
46 QgsDebugError( QStringLiteral( "failed to open MBTiles file: " ) + sourcePath );
47 mIsValid = false;
48 return;
49 }
50
51 const QString format = reader.metadataValue( QStringLiteral( "format" ) );
52 if ( format != QLatin1String( "pbf" ) )
53 {
54 QgsDebugError( QStringLiteral( "Cannot open MBTiles for vector tiles. Format = " ) + format );
55 mIsValid = false;
56 return;
57 }
58
59 QgsDebugMsgLevel( QStringLiteral( "name: " ) + reader.metadataValue( QStringLiteral( "name" ) ), 2 );
60
62
63 bool minZoomOk, maxZoomOk;
64 const int minZoom = reader.metadataValue( QStringLiteral( "minzoom" ) ).toInt( &minZoomOk );
65 const int maxZoom = reader.metadataValue( QStringLiteral( "maxzoom" ) ).toInt( &maxZoomOk );
66 if ( minZoomOk )
67 mMatrixSet.dropMatricesOutsideZoomRange( minZoom, 99 );
68 if ( maxZoomOk )
69 mMatrixSet.dropMatricesOutsideZoomRange( 0, maxZoom );
70 QgsDebugMsgLevel( QStringLiteral( "zoom range: %1 - %2" ).arg( mMatrixSet.minimumZoom() ).arg( mMatrixSet.maximumZoom() ), 2 );
71
72 QgsRectangle r = reader.extent();
73 QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ),
74 QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3857" ) ), transformContext() );
75 ct.setBallparkTransformsAreAppropriate( true );
76 try
77 {
78 mExtent = ct.transformBoundingBox( r );
79 }
80 catch ( QgsCsException & )
81 {
82 QgsDebugError( QStringLiteral( "Could not transform layer extent to layer CRS" ) );
83 }
84
85 mIsValid = true;
86}
87
88QgsMbTilesVectorTileDataProvider::QgsMbTilesVectorTileDataProvider( const QgsMbTilesVectorTileDataProvider &other )
90{
91 mIsValid = other.mIsValid;
92 mExtent = other.mExtent;
93 mMatrixSet = other.mMatrixSet;
94}
95
96Qgis::DataProviderFlags QgsMbTilesVectorTileDataProvider::flags() const
97{
99}
100
101QString QgsMbTilesVectorTileDataProvider::name() const
102{
104
105 return MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY;
106}
107
108QString QgsMbTilesVectorTileDataProvider::description() const
109{
111
112 return MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION;
113}
114
115QgsVectorTileDataProvider *QgsMbTilesVectorTileDataProvider::clone() const
116{
118 return new QgsMbTilesVectorTileDataProvider( *this );
119}
120
121QString QgsMbTilesVectorTileDataProvider::sourcePath() const
122{
124
125 QgsDataSourceUri dsUri;
126 dsUri.setEncodedUri( dataSourceUri() );
127 return dsUri.param( QStringLiteral( "url" ) );
128}
129
130bool QgsMbTilesVectorTileDataProvider::isValid() const
131{
133
134 return mIsValid;
135}
136
137QgsRectangle QgsMbTilesVectorTileDataProvider::extent() const
138{
140
141 return mExtent;
142}
143
144QgsCoordinateReferenceSystem QgsMbTilesVectorTileDataProvider::crs() const
145{
147
148 return QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3857" ) );
149}
150
151const QgsVectorTileMatrixSet &QgsMbTilesVectorTileDataProvider::tileMatrixSet() const
152{
154
155 return mMatrixSet;
156}
157
158QgsVectorTileRawData QgsMbTilesVectorTileDataProvider::readTile( const QgsTileMatrixSet &, const QgsTileXYZ &id, QgsFeedback *feedback ) const
159{
161
162 QgsDataSourceUri dsUri;
163 dsUri.setEncodedUri( dataSourceUri() );
164
165 QgsMbTiles mbReader( dsUri.param( QStringLiteral( "url" ) ) );
166 mbReader.open();
167 return QgsVectorTileRawData( id, loadFromMBTiles( mbReader, id, feedback ) );
168}
169
170QList<QgsVectorTileRawData> QgsMbTilesVectorTileDataProvider::readTiles( const QgsTileMatrixSet &, const QVector<QgsTileXYZ> &tiles, QgsFeedback *feedback, Qgis::RendererUsage ) const
171{
173
174 QgsDataSourceUri dsUri;
175 dsUri.setEncodedUri( dataSourceUri() );
176
177 QgsMbTiles mbReader( dsUri.param( QStringLiteral( "url" ) ) );
178 mbReader.open();
179
180 QList<QgsVectorTileRawData> rawTiles;
181 rawTiles.reserve( tiles.size() );
182 for ( QgsTileXYZ id : std::as_const( tiles ) )
183 {
184 if ( feedback && feedback->isCanceled() )
185 break;
186
187 const QByteArray rawData = loadFromMBTiles( mbReader, id, feedback );
188 if ( !rawData.isEmpty() )
189 {
190 rawTiles.append( QgsVectorTileRawData( id, rawData ) );
191 }
192 }
193 return rawTiles;
194}
195
196QByteArray QgsMbTilesVectorTileDataProvider::loadFromMBTiles( QgsMbTiles &mbTileReader, const QgsTileXYZ &id, QgsFeedback *feedback )
197{
198 // MBTiles uses TMS specs with Y starting at the bottom while XYZ uses Y starting at the top
199 const int rowTMS = static_cast<int>( pow( 2, id.zoomLevel() ) - id.row() - 1 );
200 QByteArray gzippedTileData = mbTileReader.tileData( id.zoomLevel(), id.column(), rowTMS );
201 if ( gzippedTileData.isEmpty() )
202 {
203 return QByteArray();
204 }
205
206 if ( feedback && feedback->isCanceled() )
207 return QByteArray();
208
209 QByteArray data;
210 if ( !QgsZipUtils::decodeGzip( gzippedTileData, data ) )
211 {
212 QgsDebugError( QStringLiteral( "Failed to decompress tile " ) + id.toString() );
213 return QByteArray();
214 }
215
216 QgsDebugMsgLevel( QStringLiteral( "Tile blob size %1 -> uncompressed size %2" ).arg( gzippedTileData.size() ).arg( data.size() ), 2 );
217 return data;
218}
219
220
221//
222// QgsMbTilesVectorTileDataProviderMetadata
223//
224
225QgsMbTilesVectorTileDataProviderMetadata::QgsMbTilesVectorTileDataProviderMetadata()
226 : QgsProviderMetadata( QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY,
227 QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION )
228{
229}
230
231QgsProviderMetadata::ProviderMetadataCapabilities QgsMbTilesVectorTileDataProviderMetadata::capabilities() const
232{
233 return ProviderMetadataCapability::LayerTypesForUri
234 | ProviderMetadataCapability::PriorityForUri
235 | ProviderMetadataCapability::QuerySublayers;
236}
237
238QgsMbTilesVectorTileDataProvider *QgsMbTilesVectorTileDataProviderMetadata::createProvider( const QString &uri, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
239{
240 return new QgsMbTilesVectorTileDataProvider( uri, options, flags );
241}
242
243QIcon QgsMbTilesVectorTileDataProviderMetadata::icon() const
244{
245 return QgsApplication::getThemeIcon( QStringLiteral( "mIconVectorTileLayer.svg" ) );
246}
247
248QgsProviderMetadata::ProviderCapabilities QgsMbTilesVectorTileDataProviderMetadata::providerCapabilities() const
249{
250 return FileBasedUris;
251}
252
253QString QgsMbTilesVectorTileDataProviderMetadata::filters( Qgis::FileFilterType type )
254{
255 switch ( type )
256 {
263 return QString();
264
266 return QObject::tr( "Mbtiles Vector Tiles" ) + QStringLiteral( " (*.mbtiles *.MBTILES)" );
267 }
268 return QString();
269}
270
271QList<QgsProviderSublayerDetails> QgsMbTilesVectorTileDataProviderMetadata::querySublayers( const QString &uri, Qgis::SublayerQueryFlags flags, QgsFeedback * ) const
272{
273 QString fileName;
274 const QFileInfo fi( uri );
275 if ( fi.isFile() )
276 {
277 fileName = uri;
278 }
279 else
280 {
281 const QVariantMap parts = decodeUri( uri );
282 fileName = parts.value( QStringLiteral( "path" ) ).toString();
283 }
284
285 if ( fileName.isEmpty() )
286 return {};
287
288 if ( QFileInfo( fileName ).suffix().compare( QLatin1String( "mbtiles" ), Qt::CaseInsensitive ) == 0 )
289 {
290 QVariantMap parts;
291 parts.insert( QStringLiteral( "path" ), fileName );
292
294 {
295 // fast scan -- assume vector tile are available
297 details.setUri( encodeUri( parts ) );
298 details.setProviderKey( key() );
300 details.setSkippedContainerScan( true );
302 return {details};
303 }
304 else
305 {
306 // slower scan, check actual mbtiles format
307 QgsMbTiles reader( fileName );
308 if ( reader.open() )
309 {
310 if ( reader.metadataValue( "format" ) == QLatin1String( "pbf" ) )
311 {
313 details.setUri( encodeUri( parts ) );
314 details.setProviderKey( key() );
317 return {details};
318 }
319 }
320 }
321 }
322 return {};
323}
324
325int QgsMbTilesVectorTileDataProviderMetadata::priorityForUri( const QString &uri ) const
326{
327 if ( validLayerTypesForUri( uri ).contains( Qgis::LayerType::VectorTile ) )
328 return 100;
329
330 return 0;
331}
332
333QList<Qgis::LayerType> QgsMbTilesVectorTileDataProviderMetadata::validLayerTypesForUri( const QString &uri ) const
334{
335 const QFileInfo fi( uri );
336 if ( fi.isFile() && fi.suffix().compare( QLatin1String( "mbtiles" ), Qt::CaseInsensitive ) == 0 )
337 {
339 }
340
341 const QVariantMap parts = decodeUri( uri );
342 if ( parts.value( QStringLiteral( "path" ) ).toString().endsWith( ".mbtiles", Qt::CaseSensitivity::CaseInsensitive ) )
344
345 return {};
346}
347
348QVariantMap QgsMbTilesVectorTileDataProviderMetadata::decodeUri( const QString &uri ) const
349{
350 QgsDataSourceUri dsUri;
351 dsUri.setEncodedUri( uri );
352
353 QVariantMap uriComponents;
354 uriComponents.insert( QStringLiteral( "type" ), QStringLiteral( "mbtiles" ) );
355 uriComponents.insert( QStringLiteral( "path" ), dsUri.param( QStringLiteral( "url" ) ) );
356
357 return uriComponents;
358}
359
360QString QgsMbTilesVectorTileDataProviderMetadata::encodeUri( const QVariantMap &parts ) const
361{
362 QgsDataSourceUri dsUri;
363 dsUri.setParam( QStringLiteral( "type" ), QStringLiteral( "mbtiles" ) );
364 dsUri.setParam( QStringLiteral( "url" ), parts.value( parts.contains( QStringLiteral( "path" ) ) ? QStringLiteral( "path" ) : QStringLiteral( "url" ) ).toString() );
365 return dsUri.encodedUri();
366}
367
368QString QgsMbTilesVectorTileDataProviderMetadata::absoluteToRelativeUri( const QString &uri, const QgsReadWriteContext &context ) const
369{
370 QVariantMap parts = decodeUri( uri );
371
372 const QString originalPath = parts.value( QStringLiteral( "path" ) ).toString();
373 parts.insert( QStringLiteral( "path" ), context.pathResolver().writePath( originalPath ) );
374
375 return encodeUri( parts );
376}
377
378QString QgsMbTilesVectorTileDataProviderMetadata::relativeToAbsoluteUri( const QString &uri, const QgsReadWriteContext &context ) const
379{
380 QVariantMap parts = decodeUri( uri );
381
382 const QString originalPath = parts.value( QStringLiteral( "path" ) ).toString();
383 parts.insert( QStringLiteral( "path" ), context.pathResolver().readPath( originalPath ) );
384
385 return encodeUri( parts );
386}
387
388QList<Qgis::LayerType> QgsMbTilesVectorTileDataProviderMetadata::supportedLayerTypes() const
389{
391}
392
393
395
396
QFlags< DataProviderFlag > DataProviderFlags
Data provider flags.
Definition qgis.h:2147
FileFilterType
Type of file filters.
Definition qgis.h:1285
@ TiledScene
Tiled scene layers.
@ Vector
Vector layers.
@ VectorTile
Vector tile layers.
@ Mesh
Mesh layers.
@ Raster
Raster layers.
@ MeshDataset
Mesh datasets.
@ PointCloud
Point clouds.
@ FastExtent2D
Provider's 2D extent retrieval via QgsDataProvider::extent() is always guaranteed to be trivial/fast ...
@ FastScan
Indicates that the provider must scan for sublayers using the fastest possible approach – e....
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:450
QFlags< SublayerQueryFlag > SublayerQueryFlags
Sublayer query flags.
Definition qgis.h:1309
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
RendererUsage
Usage of the renderer.
Definition qgis.h:3188
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
This class represents a coordinate reference system (CRS).
Class for doing transforms between two map coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Class for storing the component parts of a RDBMS data source URI (e.g.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
void setEncodedUri(const QByteArray &uri)
Sets the complete encoded uri.
QString param(const QString &key) const
Returns a generic parameter value corresponding to the specified key.
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Utility class for reading and writing MBTiles files (which are SQLite3 databases).
Definition qgsmbtiles.h:39
QByteArray tileData(int z, int x, int y) const
Returns raw tile data for given tile.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
Holds data provider key, description, and associated shared library file or function pointer informat...
QFlags< ProviderMetadataCapability > ProviderMetadataCapabilities
QFlags< ProviderCapability > ProviderCapabilities
Contains details about a sub layer available from a dataset.
void setUri(const QString &uri)
Sets the layer's uri.
void setType(Qgis::LayerType type)
Sets the layer type.
void setName(const QString &name)
Sets the layer's name.
void setProviderKey(const QString &key)
Sets the associated data provider key.
void setSkippedContainerScan(bool skipped)
Set to true if the layer is a potential dataset container and an in-depth scan of its contents was sk...
static QString suggestLayerNameFromFilePath(const QString &path)
Suggests a suitable layer name given only a file path.
The class is used as a container of context for various read/write operations on other objects.
const QgsPathResolver & pathResolver() const
Returns path resolver for conversion between relative and absolute paths.
A rectangle specified with double values.
Defines a set of tile matrices for multiple zoom levels.
Definition qgstiles.h:252
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:40
Base class for vector tile layer data providers.
Encapsulates properties of a vector tile matrix set, including tile origins and scaling information.
static QgsVectorTileMatrixSet fromWebMercator(int minimumZoom=0, int maximumZoom=14)
Returns a vector tile structure corresponding to the standard web mercator/GoogleCRS84Quad setup.
Keeps track of raw tile data from one or more sources that need to be decoded.
CORE_EXPORT bool decodeGzip(const QByteArray &bytesIn, QByteArray &bytesOut)
Decodes gzip byte stream, returns true on success.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS
Setting options for creating vector data providers.