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