QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
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
18#include "qgsapplication.h"
20#include "qgslogger.h"
21#include "qgsmbtiles.h"
23#include "qgsproviderutils.h"
24#include "qgsthreadingutils.h"
25#include "qgstiles.h"
26#include "qgsvectortileloader.h"
27#include "qgsziputils.h"
28
29#include <QFileInfo>
30#include <QIcon>
31#include <QString>
32
33#include "moc_qgsmbtilesvectortiledataprovider.cpp"
34
35using namespace Qt::StringLiterals;
36
38
39QString QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY = u"mbtilesvectortiles"_s;
40QString QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION = QObject::tr( "MBTile Vector Tiles data provider" );
41
42QgsMbTilesVectorTileDataProvider::QgsMbTilesVectorTileDataProvider( const QString &uri, const ProviderOptions &providerOptions, Qgis::DataProviderReadFlags flags )
43 : QgsVectorTileDataProvider( uri, providerOptions, flags )
44{
45 QgsDataSourceUri dsUri;
46 dsUri.setEncodedUri( uri );
47 const QString sourcePath = dsUri.param( u"url"_s );
48
49 QgsMbTiles reader( sourcePath );
50 if ( !reader.open() )
51 {
52 QgsDebugError( u"failed to open MBTiles file: "_s + sourcePath );
53 mIsValid = false;
54 return;
55 }
56
57 const QString format = reader.metadataValue( u"format"_s );
58 if ( format != "pbf"_L1 )
59 {
60 QgsDebugError( u"Cannot open MBTiles for vector tiles. Format = "_s + format );
61 mIsValid = false;
62 return;
63 }
64
65 QgsDebugMsgLevel( u"name: "_s + reader.metadataValue( u"name"_s ), 2 );
66
67 bool minZoomOk, maxZoomOk;
68 const int minZoom = reader.metadataValue( u"minzoom"_s ).toInt( &minZoomOk );
69 const int maxZoom = reader.metadataValue( u"maxzoom"_s ).toInt( &maxZoomOk );
70 if ( minZoomOk && maxZoomOk )
71 {
72 mMatrixSet = QgsVectorTileMatrixSet::fromWebMercator( minZoom, maxZoom );
73 }
74 else if ( minZoomOk )
75 {
76 mMatrixSet = QgsVectorTileMatrixSet::fromWebMercator( minZoom, 99 );
77 }
78 else if ( maxZoomOk )
79 {
80 mMatrixSet = QgsVectorTileMatrixSet::fromWebMercator( 0, maxZoom );
81 }
82 else
83 {
85 }
86
87 QgsDebugMsgLevel( u"zoom range: %1 - %2"_s.arg( mMatrixSet.minimumZoom() ).arg( mMatrixSet.maximumZoom() ), 2 );
88
89 QgsRectangle r = reader.extent();
90 QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( u"EPSG:4326"_s ), QgsCoordinateReferenceSystem( u"EPSG:3857"_s ), transformContext() );
91 ct.setBallparkTransformsAreAppropriate( true );
92 try
93 {
94 mExtent = ct.transformBoundingBox( r );
95 }
96 catch ( QgsCsException & )
97 {
98 QgsDebugError( u"Could not transform layer extent to layer CRS"_s );
99 }
100
101 mIsValid = true;
102}
103
104QgsMbTilesVectorTileDataProvider::QgsMbTilesVectorTileDataProvider( const QgsMbTilesVectorTileDataProvider &other )
106{
107 mIsValid = other.mIsValid;
108 mExtent = other.mExtent;
109 mMatrixSet = other.mMatrixSet;
110}
111
112Qgis::DataProviderFlags QgsMbTilesVectorTileDataProvider::flags() const
113{
115}
116
117QString QgsMbTilesVectorTileDataProvider::name() const
118{
120
121 return MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY;
122}
123
124QString QgsMbTilesVectorTileDataProvider::description() const
125{
127
128 return MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION;
129}
130
131QgsVectorTileDataProvider *QgsMbTilesVectorTileDataProvider::clone() const
132{
134 return new QgsMbTilesVectorTileDataProvider( *this );
135}
136
137QString QgsMbTilesVectorTileDataProvider::sourcePath() const
138{
140
141 QgsDataSourceUri dsUri;
142 dsUri.setEncodedUri( dataSourceUri() );
143 return dsUri.param( u"url"_s );
144}
145
146bool QgsMbTilesVectorTileDataProvider::isValid() const
147{
149
150 return mIsValid;
151}
152
153QgsRectangle QgsMbTilesVectorTileDataProvider::extent() const
154{
156
157 return mExtent;
158}
159
160QgsCoordinateReferenceSystem QgsMbTilesVectorTileDataProvider::crs() const
161{
163
164 return QgsCoordinateReferenceSystem( u"EPSG:3857"_s );
165}
166
167const QgsVectorTileMatrixSet &QgsMbTilesVectorTileDataProvider::tileMatrixSet() const
168{
170
171 return mMatrixSet;
172}
173
174QgsVectorTileRawData QgsMbTilesVectorTileDataProvider::readTile( const QgsTileMatrixSet &, const QgsTileXYZ &id, QgsFeedback *feedback ) const
175{
177
178 QgsDataSourceUri dsUri;
179 dsUri.setEncodedUri( dataSourceUri() );
180
181 QgsMbTiles mbReader( dsUri.param( u"url"_s ) );
182 mbReader.open();
183 return QgsVectorTileRawData( id, loadFromMBTiles( mbReader, id, feedback ) );
184}
185
186QList<QgsVectorTileRawData> QgsMbTilesVectorTileDataProvider::readTiles( const QgsTileMatrixSet &, const QVector<QgsTileXYZ> &tiles, QgsFeedback *feedback, Qgis::RendererUsage ) const
187{
189
190 QgsDataSourceUri dsUri;
191 dsUri.setEncodedUri( dataSourceUri() );
192
193 QgsMbTiles mbReader( dsUri.param( u"url"_s ) );
194 mbReader.open();
195
196 QList<QgsVectorTileRawData> rawTiles;
197 rawTiles.reserve( tiles.size() );
198 for ( QgsTileXYZ id : std::as_const( tiles ) )
199 {
200 if ( feedback && feedback->isCanceled() )
201 break;
202
203 const QByteArray rawData = loadFromMBTiles( mbReader, id, feedback );
204 if ( !rawData.isEmpty() )
205 {
206 rawTiles.append( QgsVectorTileRawData( id, rawData ) );
207 }
208 }
209 return rawTiles;
210}
211
212QByteArray QgsMbTilesVectorTileDataProvider::loadFromMBTiles( QgsMbTiles &mbTileReader, const QgsTileXYZ &id, QgsFeedback *feedback )
213{
214 // MBTiles uses TMS specs with Y starting at the bottom while XYZ uses Y starting at the top
215 const int rowTMS = static_cast<int>( pow( 2, id.zoomLevel() ) - id.row() - 1 );
216 QByteArray gzippedTileData = mbTileReader.tileData( id.zoomLevel(), id.column(), rowTMS );
217 if ( gzippedTileData.isEmpty() )
218 {
219 return QByteArray();
220 }
221
222 if ( feedback && feedback->isCanceled() )
223 return QByteArray();
224
225 QByteArray data;
226 if ( !QgsZipUtils::decodeGzip( gzippedTileData, data ) )
227 {
228 QgsDebugError( u"Failed to decompress tile "_s + id.toString() );
229 return QByteArray();
230 }
231
232 QgsDebugMsgLevel( u"Tile blob size %1 -> uncompressed size %2"_s.arg( gzippedTileData.size() ).arg( data.size() ), 2 );
233 return data;
234}
235
236
237//
238// QgsMbTilesVectorTileDataProviderMetadata
239//
240
241QgsMbTilesVectorTileDataProviderMetadata::QgsMbTilesVectorTileDataProviderMetadata()
242 : QgsProviderMetadata( QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_KEY, QgsMbTilesVectorTileDataProvider::MB_TILES_VECTOR_TILE_DATA_PROVIDER_DESCRIPTION )
243{}
244
245QgsProviderMetadata::ProviderMetadataCapabilities QgsMbTilesVectorTileDataProviderMetadata::capabilities() const
246{
247 return ProviderMetadataCapability::LayerTypesForUri | ProviderMetadataCapability::PriorityForUri | ProviderMetadataCapability::QuerySublayers;
248}
249
250QgsMbTilesVectorTileDataProvider *QgsMbTilesVectorTileDataProviderMetadata::createProvider( const QString &uri, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
251{
252 return new QgsMbTilesVectorTileDataProvider( uri, options, flags );
253}
254
255QIcon QgsMbTilesVectorTileDataProviderMetadata::icon() const
256{
257 return QgsApplication::getThemeIcon( u"mIconVectorTileLayer.svg"_s );
258}
259
260QgsProviderMetadata::ProviderCapabilities QgsMbTilesVectorTileDataProviderMetadata::providerCapabilities() const
261{
262 return FileBasedUris;
263}
264
265QString QgsMbTilesVectorTileDataProviderMetadata::filters( Qgis::FileFilterType type )
266{
267 switch ( type )
268 {
275 return QString();
276
278 return QObject::tr( "Mbtiles Vector Tiles" ) + u" (*.mbtiles *.MBTILES)"_s;
279 }
280 return QString();
281}
282
283QList<QgsProviderSublayerDetails> QgsMbTilesVectorTileDataProviderMetadata::querySublayers( const QString &uri, Qgis::SublayerQueryFlags flags, QgsFeedback * ) const
284{
285 QString fileName;
286 const QFileInfo fi( uri );
287 if ( fi.isFile() )
288 {
289 fileName = uri;
290 }
291 else
292 {
293 const QVariantMap parts = decodeUri( uri );
294 fileName = parts.value( u"path"_s ).toString();
295 }
296
297 if ( fileName.isEmpty() )
298 return {};
299
300 if ( QFileInfo( fileName ).suffix().compare( "mbtiles"_L1, Qt::CaseInsensitive ) == 0 )
301 {
302 QVariantMap parts;
303 parts.insert( u"path"_s, fileName );
304
306 {
307 // fast scan -- assume vector tile are available
309 details.setUri( encodeUri( parts ) );
310 details.setProviderKey( key() );
312 details.setSkippedContainerScan( true );
314 return { details };
315 }
316 else
317 {
318 // slower scan, check actual mbtiles format
319 QgsMbTiles reader( fileName );
320 if ( reader.open() )
321 {
322 if ( reader.metadataValue( "format" ) == "pbf"_L1 )
323 {
325 details.setUri( encodeUri( parts ) );
326 details.setProviderKey( key() );
329 return { details };
330 }
331 }
332 }
333 }
334 return {};
335}
336
337int QgsMbTilesVectorTileDataProviderMetadata::priorityForUri( const QString &uri ) const
338{
339 if ( validLayerTypesForUri( uri ).contains( Qgis::LayerType::VectorTile ) )
340 return 100;
341
342 return 0;
343}
344
345QList<Qgis::LayerType> QgsMbTilesVectorTileDataProviderMetadata::validLayerTypesForUri( const QString &uri ) const
346{
347 const QFileInfo fi( uri );
348 if ( fi.isFile() && fi.suffix().compare( "mbtiles"_L1, Qt::CaseInsensitive ) == 0 )
349 {
351 }
352
353 const QVariantMap parts = decodeUri( uri );
354 if ( parts.value( u"path"_s ).toString().endsWith( ".mbtiles", Qt::CaseSensitivity::CaseInsensitive ) )
356
357 return {};
358}
359
360QVariantMap QgsMbTilesVectorTileDataProviderMetadata::decodeUri( const QString &uri ) const
361{
362 QgsDataSourceUri dsUri;
363 dsUri.setEncodedUri( uri );
364
365 QVariantMap uriComponents;
366 uriComponents.insert( u"type"_s, u"mbtiles"_s );
367 uriComponents.insert( u"path"_s, dsUri.param( u"url"_s ) );
368
369 return uriComponents;
370}
371
372QString QgsMbTilesVectorTileDataProviderMetadata::encodeUri( const QVariantMap &parts ) const
373{
374 QgsDataSourceUri dsUri;
375 dsUri.setParam( u"type"_s, u"mbtiles"_s );
376 dsUri.setParam( u"url"_s, parts.value( parts.contains( u"path"_s ) ? u"path"_s : u"url"_s ).toString() );
377 return dsUri.encodedUri();
378}
379
380QString QgsMbTilesVectorTileDataProviderMetadata::absoluteToRelativeUri( const QString &uri, const QgsReadWriteContext &context ) const
381{
382 QVariantMap parts = decodeUri( uri );
383
384 const QString originalPath = parts.value( u"path"_s ).toString();
385 parts.insert( u"path"_s, context.pathResolver().writePath( originalPath ) );
386
387 return encodeUri( parts );
388}
389
390QString QgsMbTilesVectorTileDataProviderMetadata::relativeToAbsoluteUri( const QString &uri, const QgsReadWriteContext &context ) const
391{
392 QVariantMap parts = decodeUri( uri );
393
394 const QString originalPath = parts.value( u"path"_s ).toString();
395 parts.insert( u"path"_s, context.pathResolver().readPath( originalPath ) );
396
397 return encodeUri( parts );
398}
399
400QList<Qgis::LayerType> QgsMbTilesVectorTileDataProviderMetadata::supportedLayerTypes() const
401{
403}
404
405
QFlags< DataProviderFlag > DataProviderFlags
Data provider flags.
Definition qgis.h:2397
FileFilterType
Type of file filters.
Definition qgis.h:1419
@ TiledScene
Tiled scene layers.
Definition qgis.h:1426
@ Vector
Vector layers.
Definition qgis.h:1420
@ VectorTile
Vector tile layers.
Definition qgis.h:1425
@ Mesh
Mesh layers.
Definition qgis.h:1422
@ Raster
Raster layers.
Definition qgis.h:1421
@ MeshDataset
Mesh datasets.
Definition qgis.h:1423
@ PointCloud
Point clouds.
Definition qgis.h:1424
@ FastExtent2D
Provider's 2D extent retrieval via QgsDataProvider::extent() is always guaranteed to be trivial/fast ...
Definition qgis.h:2392
@ FastScan
Indicates that the provider must scan for sublayers using the fastest possible approach – e....
Definition qgis.h:1470
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:512
QFlags< SublayerQueryFlag > SublayerQueryFlags
Sublayer query flags.
Definition qgis.h:1477
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:211
RendererUsage
Usage of the renderer.
Definition qgis.h:3559
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
Represents a coordinate reference system (CRS).
Handles coordinate transforms between two coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Stores the component parts of a 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:56
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.
A container for the context for various read/write operations on 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:284
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:43
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.
static bool decodeGzip(const QByteArray &bytesIn, QByteArray &bytesOut)
Decodes gzip byte stream, returns true on success.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
#define QGIS_PROTECT_QOBJECT_THREAD_ACCESS
Setting options for creating vector data providers.