QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsmimedatautils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmimedatautils.cpp
3 ---------------------
4 begin : November 2011
5 copyright : (C) 2011 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#include "qgsmimedatautils.h"
16
17#include "qgslayertree.h"
18#include "qgslogger.h"
19#include "qgsmaplayerfactory.h"
20#include "qgsmeshlayer.h"
21#include "qgsrasterlayer.h"
22#include "qgsvectorlayer.h"
23
24#include <QRegularExpression>
25#include <QStringList>
26
27static const char *QGIS_URILIST_MIMETYPE = "application/x-vnd.qgis.qgis.uri";
28
29QgsMimeDataUtils::Uri::Uri( const QString &encData )
30{
31 QgsDebugMsgLevel( "encData: " + encData, 4 );
32 const QStringList decoded = decode( encData );
33 if ( decoded.size() < 4 )
34 return;
35
36 layerType = decoded[0];
37 providerKey = decoded[1];
38 name = decoded[2];
39 uri = decoded[3];
40
41 if ( layerType == QLatin1String( "raster" ) && decoded.size() >= 6 )
42 {
43 supportedCrs = decode( decoded[4] );
44 supportedFormats = decode( decoded[5] );
45 }
46 else
47 {
48 supportedCrs.clear();
49 supportedFormats.clear();
50 }
51
52 if ( decoded.size() > 6 )
53 layerId = decoded.at( 6 );
54 if ( decoded.size() > 7 )
55 pId = decoded.at( 7 );
56 if ( decoded.size() > 8 )
57 wkbType = QgsWkbTypes::parseType( decoded.at( 8 ) );
58 if ( decoded.size() > 9 )
59 filePath = decoded.at( 9 );
60
61 QgsDebugMsgLevel( QStringLiteral( "type:%1 key:%2 name:%3 uri:%4 supportedCRS:%5 supportedFormats:%6" )
63 supportedCrs.join( ',' ),
64 supportedFormats.join( ',' ) ), 2 );
65}
66
68 : providerKey( layer->providerType() )
69 , name( layer->name() )
70 , uri( layer->dataProvider() ? layer->dataProvider()->dataSourceUri() : layer->source() )
71 , layerId( layer->id() )
72 , pId( QString::number( QCoreApplication::applicationPid() ) )
73{
75 switch ( layer->type() )
76 {
78 {
79 wkbType = qobject_cast< QgsVectorLayer *>( layer )->wkbType();
80 break;
81 }
87 {
88 break;
89 }
90
94 {
95 // plugin layers do not have a standard way of storing their URI...
96 return;
97 }
98 }
99}
100
102{
103 return encode( { layerType,
105 name,
106 uri,
107 encode( supportedCrs ),
108 encode( supportedFormats ),
109 layerId,
110 pId,
113 } );
114}
115
116QgsVectorLayer *QgsMimeDataUtils::Uri::vectorLayer( bool &owner, QString &error ) const
117{
118 owner = false;
119 error.clear();
120 if ( layerType != QLatin1String( "vector" ) )
121 {
122 error = QObject::tr( "%1: Not a vector layer." ).arg( name );
123 return nullptr;
124 }
125
127 {
129 {
130 return vectorLayer;
131 }
132 }
133 if ( providerKey == QLatin1String( "memory" ) )
134 {
135 error = QObject::tr( "Cannot get memory layer." );
136 return nullptr;
137 }
138
139 owner = true;
140 const QgsVectorLayer::LayerOptions options { QgsProject::instance()->transformContext() }; // skip-keyword-check
141 return new QgsVectorLayer( uri, name, providerKey, options );
142}
143
144QgsRasterLayer *QgsMimeDataUtils::Uri::rasterLayer( bool &owner, QString &error ) const
145{
146 owner = false;
147 error.clear();
148 if ( layerType != QLatin1String( "raster" ) )
149 {
150 error = QObject::tr( "%1: Not a raster layer." ).arg( name );
151 return nullptr;
152 }
153
155 {
157 {
158 return rasterLayer;
159 }
160 }
161
162 owner = true;
163 return new QgsRasterLayer( uri, name, providerKey );
164}
165
166QgsMeshLayer *QgsMimeDataUtils::Uri::meshLayer( bool &owner, QString &error ) const
167{
168 owner = false;
169 error.clear();
170 if ( layerType != QLatin1String( "mesh" ) )
171 {
172 error = QObject::tr( "%1: Not a mesh layer." ).arg( name );
173 return nullptr;
174 }
175
177 {
179 {
180 return meshLayer;
181 }
182 }
183
184 owner = true;
185 return new QgsMeshLayer( uri, name, providerKey );
186}
187
189{
191 {
192 return QgsProject::instance()->mapLayer( layerId ); // skip-keyword-check
193 }
194 return nullptr;
195}
196
197// -----
198
199bool QgsMimeDataUtils::isUriList( const QMimeData *data )
200{
201 return data->hasFormat( QGIS_URILIST_MIMETYPE );
202}
203
205{
206 QMimeData *mimeData = new QMimeData();
207
208 mimeData->setData( QGIS_URILIST_MIMETYPE, uriListToByteArray( layers ) );
209 return mimeData;
210}
211
212
214{
215 QByteArray encodedData = data->data( QGIS_URILIST_MIMETYPE );
216 QDataStream stream( &encodedData, QIODevice::ReadOnly );
217 QString xUri; // extended uri: layer_type:provider_key:uri
218 UriList list;
219 while ( !stream.atEnd() )
220 {
221 stream >> xUri;
222 QgsDebugMsgLevel( xUri, 4 );
223 list.append( Uri( xUri ) );
224 }
225 return list;
226}
227
228
229static void _addLayerTreeNodeToUriList( QgsLayerTreeNode *node, QgsMimeDataUtils::UriList &uris )
230{
231 if ( QgsLayerTree::isGroup( node ) )
232 {
233 const auto constChildren = QgsLayerTree::toGroup( node )->children();
234 for ( QgsLayerTreeNode *child : constChildren )
235 _addLayerTreeNodeToUriList( child, uris );
236 }
237 else if ( QgsLayerTree::isLayer( node ) )
238 {
239 QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
240 QgsMapLayer *layer = nodeLayer->layer();
241 if ( !layer )
242 return;
243
244 if ( layer->type() == Qgis::LayerType::Plugin )
245 return; // plugin layers do not have a standard way of storing their URI...
246
247 uris << QgsMimeDataUtils::Uri( layer );
248 }
249}
250
251QByteArray QgsMimeDataUtils::layerTreeNodesToUriList( const QList<QgsLayerTreeNode *> &nodes )
252{
253 UriList uris;
254 const auto constNodes = nodes;
255 for ( QgsLayerTreeNode *node : constNodes )
256 _addLayerTreeNodeToUriList( node, uris );
257 return uriListToByteArray( uris );
258}
259
261{
262 if ( uri.pId.isEmpty() )
263 return false;
264
265 const qint64 pid = uri.pId.toLongLong();
266 return pid == QCoreApplication::applicationPid();
267}
268
269QString QgsMimeDataUtils::encode( const QStringList &items )
270{
271 QString encoded;
272 // Do not escape colon twice
273 const thread_local QRegularExpression re( QStringLiteral( "(?<!\\\\):" ) );
274 const auto constItems = items;
275 for ( const QString &item : constItems )
276 {
277 QString str = item;
278 str.replace( '\\', QLatin1String( "\\\\" ) );
279 str.replace( re, QStringLiteral( "\\:" ) );
280 encoded += str + ':';
281 }
282 return encoded.left( encoded.length() - 1 );
283}
284
285QStringList QgsMimeDataUtils::decode( const QString &encoded )
286{
287 QStringList items;
288 QString item;
289 bool inEscape = false;
290 const auto constEncoded = encoded;
291 for ( const QChar c : constEncoded )
292 {
293 if ( c == '\\' && inEscape )
294 {
295 item += c;
296 }
297 else if ( c == '\\' )
298 {
299 inEscape = true;
300 }
301 else if ( c == ':' && !inEscape )
302 {
303 items.append( item );
304 item.clear();
305 }
306 else
307 {
308 item += c;
309 inEscape = false;
310 }
311 }
312 items.append( item );
313 return items;
314}
315
316
317QByteArray QgsMimeDataUtils::uriListToByteArray( const QgsMimeDataUtils::UriList &layers )
318{
319 QByteArray encodedData;
320
321 QDataStream stream( &encodedData, QIODevice::WriteOnly );
322 const auto constLayers = layers;
323 for ( const Uri &u : constLayers )
324 {
325 stream << u.data();
326 }
327 return encodedData;
328}
@ 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
QgsMapLayer * layer() const
Returns the map layer associated with this node.
Base class for nodes in a layer tree.
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
static QgsLayerTreeLayer * toLayer(QgsLayerTreeNode *node)
Cast node to a layer.
static bool isLayer(const QgsLayerTreeNode *node)
Check whether the node is a valid layer node.
static bool isGroup(QgsLayerTreeNode *node)
Check whether the node is a valid group node.
static QgsLayerTreeGroup * toGroup(QgsLayerTreeNode *node)
Cast node to a group.
static QString typeToString(Qgis::LayerType type)
Converts a map layer type to a string value.
Base class for all map layer types.
Definition qgsmaplayer.h:80
Qgis::LayerType type
Definition qgsmaplayer.h:90
Represents a mesh layer supporting display of data on structured or unstructured meshes.
static QByteArray layerTreeNodesToUriList(const QList< QgsLayerTreeNode * > &nodes)
Returns encoded URI list from a list of layer tree nodes.
static bool isUriList(const QMimeData *data)
QList< QgsMimeDataUtils::Uri > UriList
static QMimeData * encodeUriList(const UriList &layers)
Encodes a URI list to a new QMimeData object.
static UriList decodeUriList(const QMimeData *data)
static bool hasOriginatedFromCurrentAppInstance(const QgsMimeDataUtils::Uri &uri)
Returns true if uri originated from the current QGIS application instance.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:116
Represents a raster layer.
Represents a vector layer which manages a vector based dataset.
static Qgis::WkbType parseType(const QString &wktStr)
Attempts to extract the WKB type from a WKT string.
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...
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
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:61
QgsMeshLayer * meshLayer(bool &owner, QString &error) const
Gets mesh layer from uri if possible, otherwise returns nullptr and error is set.
Qgis::WkbType wkbType
WKB type, if associated with a vector layer, or QgsWkbTypes::Unknown if not yet known.
QString filePath
Path to file, if uri is associated with a file.
QString uri
Identifier of the data source recognized by its providerKey.
QString name
Human readable name to be used e.g. in layer tree.
QgsMapLayer * mapLayer() const
Returns the layer from the active project corresponding to this uri (if possible),...
QString pId
Unique ID associated with application instance.
QgsRasterLayer * rasterLayer(bool &owner, QString &error) const
Gets raster layer from uri if possible, otherwise returns nullptr and error is set.
QString providerKey
For "vector" / "raster" type: provider id.
QgsVectorLayer * vectorLayer(bool &owner, QString &error) const
Gets vector layer from uri if possible, otherwise returns nullptr and error is set.
QString layerId
Layer ID, if uri is associated with a layer from a QgsProject.
QString data() const
Returns encoded representation of the object.
Uri()=default
Constructs invalid URI.
QString layerType
Type of URI.
Setting options for loading vector layers.