QGIS API Documentation  3.18.1-Zürich (202f1bf7e5)
qgsogrutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsogrutils.cpp
3  ---------------
4  begin : February 2016
5  copyright : (C) 2016 Nyall Dawson
6  email : nyall dot dawson 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 
16 #include "qgsogrutils.h"
17 #include "qgsapplication.h"
18 #include "qgslogger.h"
19 #include "qgsgeometry.h"
20 #include "qgsfields.h"
21 #include "qgslinestring.h"
22 #include "qgsmultipoint.h"
23 #include "qgsmultilinestring.h"
24 #include "qgsogrprovider.h"
25 #include <QTextCodec>
26 #include <QUuid>
27 #include <cpl_error.h>
28 #include <QJsonDocument>
29 #include <QFileInfo>
30 #include <QDir>
31 #include <QTextStream>
32 #include <QDataStream>
33 
34 #include "ogr_srs_api.h"
35 
36 // Starting with GDAL 2.2, there are 2 concepts: unset fields and null fields
37 // whereas previously there was only unset fields. For QGIS purposes, both
38 // states (unset/null) are equivalent.
39 #ifndef OGRNullMarker
40 #define OGR_F_IsFieldSetAndNotNull OGR_F_IsFieldSet
41 #endif
42 
43 
44 
45 void gdal::OGRDataSourceDeleter::operator()( OGRDataSourceH source )
46 {
47  OGR_DS_Destroy( source );
48 }
49 
50 
51 void gdal::OGRGeometryDeleter::operator()( OGRGeometryH geometry )
52 {
53  OGR_G_DestroyGeometry( geometry );
54 }
55 
56 void gdal::OGRFldDeleter::operator()( OGRFieldDefnH definition )
57 {
58  OGR_Fld_Destroy( definition );
59 }
60 
61 void gdal::OGRFeatureDeleter::operator()( OGRFeatureH feature )
62 {
63  OGR_F_Destroy( feature );
64 }
65 
67 {
68  GDALClose( dataset );
69 }
70 
71 void gdal::fast_delete_and_close( gdal::dataset_unique_ptr &dataset, GDALDriverH driver, const QString &path )
72 {
73  // see https://github.com/qgis/QGIS/commit/d024910490a39e65e671f2055c5b6543e06c7042#commitcomment-25194282
74  // faster if we close the handle AFTER delete, but doesn't work for windows
75 #ifdef Q_OS_WIN
76  // close dataset handle
77  dataset.reset();
78 #endif
79 
80  CPLPushErrorHandler( CPLQuietErrorHandler );
81  GDALDeleteDataset( driver, path.toUtf8().constData() );
82  CPLPopErrorHandler();
83 
84 #ifndef Q_OS_WIN
85  // close dataset handle
86  dataset.reset();
87 #endif
88 }
89 
90 
91 void gdal::GDALWarpOptionsDeleter::operator()( GDALWarpOptions *options )
92 {
93  GDALDestroyWarpOptions( options );
94 }
95 
96 QgsFeature QgsOgrUtils::readOgrFeature( OGRFeatureH ogrFet, const QgsFields &fields, QTextCodec *encoding )
97 {
98  QgsFeature feature;
99  if ( !ogrFet )
100  {
101  feature.setValid( false );
102  return feature;
103  }
104 
105  feature.setId( OGR_F_GetFID( ogrFet ) );
106  feature.setValid( true );
107 
108  if ( !readOgrFeatureGeometry( ogrFet, feature ) )
109  {
110  feature.setValid( false );
111  }
112 
113  if ( !readOgrFeatureAttributes( ogrFet, fields, feature, encoding ) )
114  {
115  feature.setValid( false );
116  }
117 
118  return feature;
119 }
120 
121 QgsFields QgsOgrUtils::readOgrFields( OGRFeatureH ogrFet, QTextCodec *encoding )
122 {
123  QgsFields fields;
124 
125  if ( !ogrFet )
126  return fields;
127 
128  int fieldCount = OGR_F_GetFieldCount( ogrFet );
129  for ( int i = 0; i < fieldCount; ++i )
130  {
131  OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, i );
132  if ( !fldDef )
133  {
134  fields.append( QgsField() );
135  continue;
136  }
137 
138  QString name = encoding ? encoding->toUnicode( OGR_Fld_GetNameRef( fldDef ) ) : QString::fromUtf8( OGR_Fld_GetNameRef( fldDef ) );
139  QVariant::Type varType;
140  switch ( OGR_Fld_GetType( fldDef ) )
141  {
142  case OFTInteger:
143  if ( OGR_Fld_GetSubType( fldDef ) == OFSTBoolean )
144  varType = QVariant::Bool;
145  else
146  varType = QVariant::Int;
147  break;
148  case OFTInteger64:
149  varType = QVariant::LongLong;
150  break;
151  case OFTReal:
152  varType = QVariant::Double;
153  break;
154  case OFTDate:
155  varType = QVariant::Date;
156  break;
157  case OFTTime:
158  varType = QVariant::Time;
159  break;
160  case OFTDateTime:
161  varType = QVariant::DateTime;
162  break;
163  case OFTString:
164 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,4,0)
165  if ( OGR_Fld_GetSubType( fldDef ) == OFSTJSON )
166  varType = QVariant::Map;
167  else
168  varType = QVariant::String;
169  break;
170 #endif
171  default:
172  varType = QVariant::String; // other unsupported, leave it as a string
173  }
174  fields.append( QgsField( name, varType ) );
175  }
176  return fields;
177 }
178 
179 
180 QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsFields &fields, int attIndex, QTextCodec *encoding, bool *ok )
181 {
182  if ( attIndex < 0 || attIndex >= fields.count() )
183  {
184  if ( ok )
185  *ok = false;
186  return QVariant();
187  }
188 
189  const QgsField field = fields.at( attIndex );
190  return getOgrFeatureAttribute( ogrFet, field, attIndex, encoding, ok );
191 }
192 
193 QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsField &field, int attIndex, QTextCodec *encoding, bool *ok )
194 {
195  if ( !ogrFet || attIndex < 0 )
196  {
197  if ( ok )
198  *ok = false;
199  return QVariant();
200  }
201 
202  OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attIndex );
203 
204  if ( ! fldDef )
205  {
206  if ( ok )
207  *ok = false;
208 
209  QgsDebugMsg( QStringLiteral( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ) );
210  return QVariant();
211  }
212 
213  QVariant value;
214 
215  if ( ok )
216  *ok = true;
217 
218  if ( OGR_F_IsFieldSetAndNotNull( ogrFet, attIndex ) )
219  {
220  switch ( field.type() )
221  {
222  case QVariant::String:
223  {
224  if ( encoding )
225  value = QVariant( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) );
226  else
227  value = QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) );
228 
229 #ifdef Q_OS_WIN
230  // Fixes GH #41076 (empty strings shown as NULL), because we have checked before that it was NOT NULL
231  // Note: QVariant( QString( ) ).isNull( ) is still true on windows so we really need string literal :(
232  if ( value.isNull() )
233  value = QVariant( QStringLiteral( "" ) ); // skip-keyword-check
234 #endif
235 
236  break;
237  }
238  case QVariant::Int:
239  value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) );
240  break;
241  case QVariant::Bool:
242  value = QVariant( bool( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) ) );
243  break;
244  case QVariant::LongLong:
245  value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attIndex ) );
246  break;
247  case QVariant::Double:
248  value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attIndex ) );
249  break;
250  case QVariant::Date:
251  case QVariant::DateTime:
252  case QVariant::Time:
253  {
254  int year, month, day, hour, minute, second, tzf;
255 
256  OGR_F_GetFieldAsDateTime( ogrFet, attIndex, &year, &month, &day, &hour, &minute, &second, &tzf );
257  if ( field.type() == QVariant::Date )
258  value = QDate( year, month, day );
259  else if ( field.type() == QVariant::Time )
260  value = QTime( hour, minute, second );
261  else
262  value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) );
263  }
264  break;
265 
266  case QVariant::ByteArray:
267  {
268  int size = 0;
269  const GByte *b = OGR_F_GetFieldAsBinary( ogrFet, attIndex, &size );
270 
271  // QByteArray::fromRawData is funny. It doesn't take ownership of the data, so we have to explicitly call
272  // detach on it to force a copy which owns the data
273  QByteArray ba = QByteArray::fromRawData( reinterpret_cast<const char *>( b ), size );
274  ba.detach();
275 
276  value = ba;
277  break;
278  }
279 
280  case QVariant::List:
281  {
282  if ( field.subType() == QVariant::String )
283  {
284  QStringList list;
285  char **lst = OGR_F_GetFieldAsStringList( ogrFet, attIndex );
286  const int count = CSLCount( lst );
287  if ( count > 0 )
288  {
289  for ( int i = 0; i < count; i++ )
290  {
291  if ( encoding )
292  list << encoding->toUnicode( lst[i] );
293  else
294  list << QString::fromUtf8( lst[i] );
295  }
296  }
297  value = list;
298  }
299  else
300  {
301  Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" );
302  if ( ok )
303  *ok = false;
304  }
305  break;
306  }
307 
308  case QVariant::Map:
309  {
310  //it has to be JSON
311  //it's null if no json format
312  if ( encoding )
313  value = QJsonDocument::fromJson( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ).toUtf8() ).toVariant();
314  else
315  value = QJsonDocument::fromJson( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ).toUtf8() ).toVariant();
316  break;
317  }
318  default:
319  Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" );
320  if ( ok )
321  *ok = false;
322  }
323  }
324  else
325  {
326  value = QVariant( field.type() );
327  }
328 
329  return value;
330 }
331 
332 bool QgsOgrUtils::readOgrFeatureAttributes( OGRFeatureH ogrFet, const QgsFields &fields, QgsFeature &feature, QTextCodec *encoding )
333 {
334  // read all attributes
335  feature.initAttributes( fields.count() );
336  feature.setFields( fields );
337 
338  if ( !ogrFet )
339  return false;
340 
341  bool ok = false;
342  for ( int idx = 0; idx < fields.count(); ++idx )
343  {
344  QVariant value = getOgrFeatureAttribute( ogrFet, fields, idx, encoding, &ok );
345  if ( ok )
346  {
347  feature.setAttribute( idx, value );
348  }
349  }
350  return true;
351 }
352 
353 bool QgsOgrUtils::readOgrFeatureGeometry( OGRFeatureH ogrFet, QgsFeature &feature )
354 {
355  if ( !ogrFet )
356  return false;
357 
358  OGRGeometryH geom = OGR_F_GetGeometryRef( ogrFet );
359  if ( !geom )
360  feature.clearGeometry();
361  else
362  feature.setGeometry( ogrGeometryToQgsGeometry( geom ) );
363 
364  return true;
365 }
366 
367 std::unique_ptr< QgsPoint > ogrGeometryToQgsPoint( OGRGeometryH geom )
368 {
369  QgsWkbTypes::Type wkbType = static_cast<QgsWkbTypes::Type>( OGR_G_GetGeometryType( geom ) );
370 
371  double x, y, z, m;
372  OGR_G_GetPointZM( geom, 0, &x, &y, &z, &m );
373  return qgis::make_unique< QgsPoint >( wkbType, x, y, z, m );
374 }
375 
376 std::unique_ptr< QgsMultiPoint > ogrGeometryToQgsMultiPoint( OGRGeometryH geom )
377 {
378  std::unique_ptr< QgsMultiPoint > mp = qgis::make_unique< QgsMultiPoint >();
379 
380  const int count = OGR_G_GetGeometryCount( geom );
381  mp->reserve( count );
382  for ( int i = 0; i < count; ++i )
383  {
384  mp->addGeometry( ogrGeometryToQgsPoint( OGR_G_GetGeometryRef( geom, i ) ).release() );
385  }
386 
387  return mp;
388 }
389 
390 std::unique_ptr< QgsLineString > ogrGeometryToQgsLineString( OGRGeometryH geom )
391 {
392  QgsWkbTypes::Type wkbType = static_cast<QgsWkbTypes::Type>( OGR_G_GetGeometryType( geom ) );
393 
394  int count = OGR_G_GetPointCount( geom );
395  QVector< double > x( count );
396  QVector< double > y( count );
397  QVector< double > z;
398  double *pz = nullptr;
399  if ( QgsWkbTypes::hasZ( wkbType ) )
400  {
401  z.resize( count );
402  pz = z.data();
403  }
404  double *pm = nullptr;
405  QVector< double > m;
406  if ( QgsWkbTypes::hasM( wkbType ) )
407  {
408  m.resize( count );
409  pm = m.data();
410  }
411  OGR_G_GetPointsZM( geom, x.data(), sizeof( double ), y.data(), sizeof( double ), pz, sizeof( double ), pm, sizeof( double ) );
412 
413  return qgis::make_unique< QgsLineString>( x, y, z, m, wkbType == QgsWkbTypes::LineString25D );
414 }
415 
416 std::unique_ptr< QgsMultiLineString > ogrGeometryToQgsMultiLineString( OGRGeometryH geom )
417 {
418  std::unique_ptr< QgsMultiLineString > mp = qgis::make_unique< QgsMultiLineString >();
419 
420  const int count = OGR_G_GetGeometryCount( geom );
421  mp->reserve( count );
422  for ( int i = 0; i < count; ++i )
423  {
424  mp->addGeometry( ogrGeometryToQgsLineString( OGR_G_GetGeometryRef( geom, i ) ).release() );
425  }
426 
427  return mp;
428 }
429 
431 {
432  switch ( ogrGeomType )
433  {
434  case wkbUnknown: return QgsWkbTypes::Type::Unknown;
435  case wkbPoint: return QgsWkbTypes::Type::Point;
436  case wkbLineString: return QgsWkbTypes::Type::LineString;
437  case wkbPolygon: return QgsWkbTypes::Type::Polygon;
438  case wkbMultiPoint: return QgsWkbTypes::Type::MultiPoint;
439  case wkbMultiLineString: return QgsWkbTypes::Type::MultiLineString;
440  case wkbMultiPolygon: return QgsWkbTypes::Type::MultiPolygon;
441  case wkbGeometryCollection: return QgsWkbTypes::Type::GeometryCollection;
442  case wkbCircularString: return QgsWkbTypes::Type::CircularString;
443  case wkbCompoundCurve: return QgsWkbTypes::Type::CompoundCurve;
444  case wkbCurvePolygon: return QgsWkbTypes::Type::CurvePolygon;
445  case wkbMultiCurve: return QgsWkbTypes::Type::MultiCurve;
446  case wkbMultiSurface: return QgsWkbTypes::Type::MultiSurface;
447  case wkbCurve: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
448  case wkbSurface: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
449  case wkbPolyhedralSurface: return QgsWkbTypes::Type::Unknown; // no actual matching
450  case wkbTIN: return QgsWkbTypes::Type::Unknown; // no actual matching
451  case wkbTriangle: return QgsWkbTypes::Type::Triangle;
452 
453  case wkbNone: return QgsWkbTypes::Type::NoGeometry;
454  case wkbLinearRing: return QgsWkbTypes::Type::LineString; // approximate match
455 
456  case wkbCircularStringZ: return QgsWkbTypes::Type::CircularStringZ;
457  case wkbCompoundCurveZ: return QgsWkbTypes::Type::CompoundCurveZ;
458  case wkbCurvePolygonZ: return QgsWkbTypes::Type::CurvePolygonZ;
459  case wkbMultiCurveZ: return QgsWkbTypes::Type::MultiCurveZ;
460  case wkbMultiSurfaceZ: return QgsWkbTypes::Type::MultiSurfaceZ;
461  case wkbCurveZ: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
462  case wkbSurfaceZ: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
463  case wkbPolyhedralSurfaceZ: return QgsWkbTypes::Type::Unknown; // no actual matching
464  case wkbTINZ: return QgsWkbTypes::Type::Unknown; // no actual matching
465  case wkbTriangleZ: return QgsWkbTypes::Type::TriangleZ;
466 
467  case wkbPointM: return QgsWkbTypes::Type::PointM;
468  case wkbLineStringM: return QgsWkbTypes::Type::LineStringM;
469  case wkbPolygonM: return QgsWkbTypes::Type::PolygonM;
470  case wkbMultiPointM: return QgsWkbTypes::Type::MultiPointM;
471  case wkbMultiLineStringM: return QgsWkbTypes::Type::MultiLineStringM;
472  case wkbMultiPolygonM: return QgsWkbTypes::Type::MultiPolygonM;
473  case wkbGeometryCollectionM: return QgsWkbTypes::Type::GeometryCollectionM;
474  case wkbCircularStringM: return QgsWkbTypes::Type::CircularStringM;
475  case wkbCompoundCurveM: return QgsWkbTypes::Type::CompoundCurveM;
476  case wkbCurvePolygonM: return QgsWkbTypes::Type::CurvePolygonM;
477  case wkbMultiCurveM: return QgsWkbTypes::Type::MultiCurveM;
478  case wkbMultiSurfaceM: return QgsWkbTypes::Type::MultiSurfaceM;
479  case wkbCurveM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
480  case wkbSurfaceM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
481  case wkbPolyhedralSurfaceM: return QgsWkbTypes::Type::Unknown; // no actual matching
482  case wkbTINM: return QgsWkbTypes::Type::Unknown; // no actual matching
483  case wkbTriangleM: return QgsWkbTypes::Type::TriangleM;
484 
485  case wkbPointZM: return QgsWkbTypes::Type::PointZM;
486  case wkbLineStringZM: return QgsWkbTypes::Type::LineStringZM;
487  case wkbPolygonZM: return QgsWkbTypes::Type::PolygonZM;
488  case wkbMultiPointZM: return QgsWkbTypes::Type::MultiPointZM;
489  case wkbMultiLineStringZM: return QgsWkbTypes::Type::MultiLineStringZM;
490  case wkbMultiPolygonZM: return QgsWkbTypes::Type::MultiPolygonZM;
491  case wkbGeometryCollectionZM: return QgsWkbTypes::Type::GeometryCollectionZM;
492  case wkbCircularStringZM: return QgsWkbTypes::Type::CircularStringZM;
493  case wkbCompoundCurveZM: return QgsWkbTypes::Type::CompoundCurveZM;
494  case wkbCurvePolygonZM: return QgsWkbTypes::Type::CurvePolygonZM;
495  case wkbMultiCurveZM: return QgsWkbTypes::Type::MultiCurveZM;
496  case wkbMultiSurfaceZM: return QgsWkbTypes::Type::MultiSurfaceZM;
497  case wkbCurveZM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
498  case wkbSurfaceZM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
499  case wkbPolyhedralSurfaceZM: return QgsWkbTypes::Type::Unknown; // no actual matching
500  case wkbTINZM: return QgsWkbTypes::Type::Unknown; // no actual matching
501  case wkbTriangleZM: return QgsWkbTypes::Type::TriangleZM;
502 
503  case wkbPoint25D: return QgsWkbTypes::Type::PointZ;
504  case wkbLineString25D: return QgsWkbTypes::Type::LineStringZ;
505  case wkbPolygon25D: return QgsWkbTypes::Type::PolygonZ;
506  case wkbMultiPoint25D: return QgsWkbTypes::Type::MultiPointZ;
507  case wkbMultiLineString25D: return QgsWkbTypes::Type::MultiLineStringZ;
508  case wkbMultiPolygon25D: return QgsWkbTypes::Type::MultiPolygonZ;
509  case wkbGeometryCollection25D: return QgsWkbTypes::Type::GeometryCollectionZ;
510  }
511 
512  // should not reach that point normally
513  return QgsWkbTypes::Type::Unknown;
514 }
515 
517 {
518  if ( !geom )
519  return QgsGeometry();
520 
521  const auto ogrGeomType = OGR_G_GetGeometryType( geom );
522  QgsWkbTypes::Type wkbType = ogrGeometryTypeToQgsWkbType( ogrGeomType );
523 
524  // optimised case for some geometry classes, avoiding wkb conversion on OGR/QGIS sides
525  // TODO - extend to other classes!
526  switch ( QgsWkbTypes::flatType( wkbType ) )
527  {
528  case QgsWkbTypes::Point:
529  {
530  return QgsGeometry( ogrGeometryToQgsPoint( geom ) );
531  }
532 
534  {
535  return QgsGeometry( ogrGeometryToQgsMultiPoint( geom ) );
536  }
537 
539  {
540  // optimised case for line -- avoid wkb conversion
541  return QgsGeometry( ogrGeometryToQgsLineString( geom ) );
542  }
543 
545  {
546  // optimised case for line -- avoid wkb conversion
548  }
549 
550  default:
551  break;
552  };
553 
554  // Fallback to inefficient WKB conversions
555 
556  if ( wkbFlatten( wkbType ) == wkbGeometryCollection )
557  {
558  // Shapefile MultiPatch can be reported as GeometryCollectionZ of TINZ
559  if ( OGR_G_GetGeometryCount( geom ) >= 1 &&
560  wkbFlatten( OGR_G_GetGeometryType( OGR_G_GetGeometryRef( geom, 0 ) ) ) == wkbTIN )
561  {
562  auto newGeom = OGR_G_ForceToMultiPolygon( OGR_G_Clone( geom ) );
563  auto ret = ogrGeometryToQgsGeometry( newGeom );
564  OGR_G_DestroyGeometry( newGeom );
565  return ret;
566  }
567  }
568 
569  // get the wkb representation
570  int memorySize = OGR_G_WkbSize( geom );
571  unsigned char *wkb = new unsigned char[memorySize];
572  OGR_G_ExportToWkb( geom, static_cast<OGRwkbByteOrder>( QgsApplication::endian() ), wkb );
573 
574  // Read original geometry type
575  uint32_t origGeomType;
576  memcpy( &origGeomType, wkb + 1, sizeof( uint32_t ) );
577  bool hasZ = ( origGeomType >= 1000 && origGeomType < 2000 ) || ( origGeomType >= 3000 && origGeomType < 4000 );
578  bool hasM = ( origGeomType >= 2000 && origGeomType < 3000 ) || ( origGeomType >= 3000 && origGeomType < 4000 );
579 
580  // PolyhedralSurface and TINs are not supported, map them to multipolygons...
581  if ( origGeomType % 1000 == 16 ) // is TIN, TINZ, TINM or TINZM
582  {
583  // TIN has the same wkb layout as a multipolygon, just need to overwrite the geom types...
584  int nDims = 2 + hasZ + hasM;
585  uint32_t newMultiType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::MultiPolygon, hasZ, hasM ) );
586  uint32_t newSingleType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::Polygon, hasZ, hasM ) );
587  unsigned char *wkbptr = wkb;
588 
589  // Endianness
590  wkbptr += 1;
591 
592  // Overwrite geom type
593  memcpy( wkbptr, &newMultiType, sizeof( uint32_t ) );
594  wkbptr += 4;
595 
596  // Geom count
597  uint32_t numGeoms;
598  memcpy( &numGeoms, wkb + 5, sizeof( uint32_t ) );
599  wkbptr += 4;
600 
601  // For each part, overwrite the geometry type to polygon (Z|M)
602  for ( uint32_t i = 0; i < numGeoms; ++i )
603  {
604  // Endianness
605  wkbptr += 1;
606 
607  // Overwrite geom type
608  memcpy( wkbptr, &newSingleType, sizeof( uint32_t ) );
609  wkbptr += sizeof( uint32_t );
610 
611  // skip coordinates
612  uint32_t nRings;
613  memcpy( &nRings, wkbptr, sizeof( uint32_t ) );
614  wkbptr += sizeof( uint32_t );
615 
616  for ( uint32_t j = 0; j < nRings; ++j )
617  {
618  uint32_t nPoints;
619  memcpy( &nPoints, wkbptr, sizeof( uint32_t ) );
620  wkbptr += sizeof( uint32_t ) + sizeof( double ) * nDims * nPoints;
621  }
622  }
623  }
624  else if ( origGeomType % 1000 == 15 ) // PolyhedralSurface, PolyhedralSurfaceZ, PolyhedralSurfaceM or PolyhedralSurfaceZM
625  {
626  // PolyhedralSurface has the same wkb layout as a MultiPolygon, just need to overwrite the geom type...
627  uint32_t newType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::MultiPolygon, hasZ, hasM ) );
628  // Overwrite geom type
629  memcpy( wkb + 1, &newType, sizeof( uint32_t ) );
630  }
631 
632  QgsGeometry g;
633  g.fromWkb( wkb, memorySize );
634  return g;
635 }
636 
637 QgsFeatureList QgsOgrUtils::stringToFeatureList( const QString &string, const QgsFields &fields, QTextCodec *encoding )
638 {
639  QgsFeatureList features;
640  if ( string.isEmpty() )
641  return features;
642 
643  QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() );
644 
645  // create memory file system object from string buffer
646  QByteArray ba = string.toUtf8();
647  VSIFCloseL( VSIFileFromMemBuffer( randomFileName.toUtf8().constData(), reinterpret_cast< GByte * >( ba.data() ),
648  static_cast< vsi_l_offset >( ba.size() ), FALSE ) );
649 
650  gdal::ogr_datasource_unique_ptr hDS( OGROpen( randomFileName.toUtf8().constData(), false, nullptr ) );
651  if ( !hDS )
652  {
653  VSIUnlink( randomFileName.toUtf8().constData() );
654  return features;
655  }
656 
657  OGRLayerH ogrLayer = OGR_DS_GetLayer( hDS.get(), 0 );
658  if ( !ogrLayer )
659  {
660  hDS.reset();
661  VSIUnlink( randomFileName.toUtf8().constData() );
662  return features;
663  }
664 
666  while ( oFeat.reset( OGR_L_GetNextFeature( ogrLayer ) ), oFeat )
667  {
668  QgsFeature feat = readOgrFeature( oFeat.get(), fields, encoding );
669  if ( feat.isValid() )
670  features << feat;
671  }
672 
673  hDS.reset();
674  VSIUnlink( randomFileName.toUtf8().constData() );
675 
676  return features;
677 }
678 
679 QgsFields QgsOgrUtils::stringToFields( const QString &string, QTextCodec *encoding )
680 {
681  QgsFields fields;
682  if ( string.isEmpty() )
683  return fields;
684 
685  QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() );
686 
687  // create memory file system object from buffer
688  QByteArray ba = string.toUtf8();
689  VSIFCloseL( VSIFileFromMemBuffer( randomFileName.toUtf8().constData(), reinterpret_cast< GByte * >( ba.data() ),
690  static_cast< vsi_l_offset >( ba.size() ), FALSE ) );
691 
692  gdal::ogr_datasource_unique_ptr hDS( OGROpen( randomFileName.toUtf8().constData(), false, nullptr ) );
693  if ( !hDS )
694  {
695  VSIUnlink( randomFileName.toUtf8().constData() );
696  return fields;
697  }
698 
699  OGRLayerH ogrLayer = OGR_DS_GetLayer( hDS.get(), 0 );
700  if ( !ogrLayer )
701  {
702  hDS.reset();
703  VSIUnlink( randomFileName.toUtf8().constData() );
704  return fields;
705  }
706 
708  //read in the first feature only
709  if ( oFeat.reset( OGR_L_GetNextFeature( ogrLayer ) ), oFeat )
710  {
711  fields = readOgrFields( oFeat.get(), encoding );
712  }
713 
714  hDS.reset();
715  VSIUnlink( randomFileName.toUtf8().constData() );
716  return fields;
717 }
718 
719 QStringList QgsOgrUtils::cStringListToQStringList( char **stringList )
720 {
721  QStringList strings;
722 
723  // presume null terminated string list
724  for ( qgssize i = 0; stringList[i]; ++i )
725  {
726  strings.append( QString::fromUtf8( stringList[i] ) );
727  }
728 
729  return strings;
730 }
731 
733 {
734  if ( !srs )
735  return QString();
736 
737  char *pszWkt = nullptr;
738 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,0,0)
739  const QByteArray multiLineOption = QStringLiteral( "MULTILINE=NO" ).toLocal8Bit();
740  const QByteArray formatOption = QStringLiteral( "FORMAT=WKT2" ).toLocal8Bit();
741  const char *const options[] = {multiLineOption.constData(), formatOption.constData(), nullptr};
742  OSRExportToWktEx( srs, &pszWkt, options );
743 #else
744  OSRExportToWkt( srs, &pszWkt );
745 #endif
746 
747  const QString res( pszWkt );
748  CPLFree( pszWkt );
749  return res;
750 }
751 
753 {
754  const QString wkt = OGRSpatialReferenceToWkt( srs );
755  if ( wkt.isEmpty() )
757 
759 }
760 
761 QString QgsOgrUtils::readShapefileEncoding( const QString &path )
762 {
763  const QString cpgEncoding = readShapefileEncodingFromCpg( path );
764  if ( !cpgEncoding.isEmpty() )
765  return cpgEncoding;
766 
767  return readShapefileEncodingFromLdid( path );
768 }
769 
770 QString QgsOgrUtils::readShapefileEncodingFromCpg( const QString &path )
771 {
772 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,1,0)
773  QString errCause;
774  QgsOgrLayerUniquePtr layer = QgsOgrProviderUtils::getLayer( path, false, QStringList(), 0, errCause, false );
775  return layer ? layer->GetMetadataItem( QStringLiteral( "ENCODING_FROM_CPG" ), QStringLiteral( "SHAPEFILE" ) ) : QString();
776 #else
777  if ( !QFileInfo::exists( path ) )
778  return QString();
779 
780  // first try to read cpg file, if present
781  const QFileInfo fi( path );
782  const QString baseName = fi.completeBaseName();
783  const QString cpgPath = fi.dir().filePath( QStringLiteral( "%1.%2" ).arg( baseName, fi.suffix() == QLatin1String( "SHP" ) ? QStringLiteral( "CPG" ) : QStringLiteral( "cpg" ) ) );
784  if ( QFile::exists( cpgPath ) )
785  {
786  QFile cpgFile( cpgPath );
787  if ( cpgFile.open( QIODevice::ReadOnly ) )
788  {
789  QTextStream cpgStream( &cpgFile );
790  const QString cpgString = cpgStream.readLine();
791  cpgFile.close();
792 
793  if ( !cpgString.isEmpty() )
794  {
795  // from OGRShapeLayer::ConvertCodePage
796  // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp#L342
797  bool ok = false;
798  int cpgCodePage = cpgString.toInt( &ok );
799  if ( ok && ( ( cpgCodePage >= 437 && cpgCodePage <= 950 )
800  || ( cpgCodePage >= 1250 && cpgCodePage <= 1258 ) ) )
801  {
802  return QStringLiteral( "CP%1" ).arg( cpgCodePage );
803  }
804  else if ( cpgString.startsWith( QLatin1String( "8859" ) ) )
805  {
806  if ( cpgString.length() > 4 && cpgString.at( 4 ) == '-' )
807  return QStringLiteral( "ISO-8859-%1" ).arg( cpgString.mid( 5 ) );
808  else
809  return QStringLiteral( "ISO-8859-%1" ).arg( cpgString.mid( 4 ) );
810  }
811  else if ( cpgString.startsWith( QLatin1String( "UTF-8" ), Qt::CaseInsensitive ) ||
812  cpgString.startsWith( QLatin1String( "UTF8" ), Qt::CaseInsensitive ) )
813  return QStringLiteral( "UTF-8" );
814  else if ( cpgString.startsWith( QLatin1String( "ANSI 1251" ), Qt::CaseInsensitive ) )
815  return QStringLiteral( "CP1251" );
816 
817  return cpgString;
818  }
819  }
820  }
821 
822  return QString();
823 #endif
824 }
825 
826 QString QgsOgrUtils::readShapefileEncodingFromLdid( const QString &path )
827 {
828 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,1,0)
829  QString errCause;
830  QgsOgrLayerUniquePtr layer = QgsOgrProviderUtils::getLayer( path, false, QStringList(), 0, errCause, false );
831  return layer ? layer->GetMetadataItem( QStringLiteral( "ENCODING_FROM_LDID" ), QStringLiteral( "SHAPEFILE" ) ) : QString();
832 #else
833  // from OGRShapeLayer::ConvertCodePage
834  // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp#L342
835 
836  if ( !QFileInfo::exists( path ) )
837  return QString();
838 
839  // first try to read cpg file, if present
840  const QFileInfo fi( path );
841  const QString baseName = fi.completeBaseName();
842 
843  // fallback to LDID value, read from DBF file
844  const QString dbfPath = fi.dir().filePath( QStringLiteral( "%1.%2" ).arg( baseName, fi.suffix() == QLatin1String( "SHP" ) ? QStringLiteral( "DBF" ) : QStringLiteral( "dbf" ) ) );
845  if ( QFile::exists( dbfPath ) )
846  {
847  QFile dbfFile( dbfPath );
848  if ( dbfFile.open( QIODevice::ReadOnly ) )
849  {
850  dbfFile.read( 29 );
851  QDataStream dbfIn( &dbfFile );
852  dbfIn.setByteOrder( QDataStream::LittleEndian );
853  quint8 ldid;
854  dbfIn >> ldid;
855  dbfFile.close();
856 
857  int nCP = -1; // Windows code page.
858 
859  // http://www.autopark.ru/ASBProgrammerGuide/DBFSTRUC.HTM
860  switch ( ldid )
861  {
862  case 1: nCP = 437; break;
863  case 2: nCP = 850; break;
864  case 3: nCP = 1252; break;
865  case 4: nCP = 10000; break;
866  case 8: nCP = 865; break;
867  case 10: nCP = 850; break;
868  case 11: nCP = 437; break;
869  case 13: nCP = 437; break;
870  case 14: nCP = 850; break;
871  case 15: nCP = 437; break;
872  case 16: nCP = 850; break;
873  case 17: nCP = 437; break;
874  case 18: nCP = 850; break;
875  case 19: nCP = 932; break;
876  case 20: nCP = 850; break;
877  case 21: nCP = 437; break;
878  case 22: nCP = 850; break;
879  case 23: nCP = 865; break;
880  case 24: nCP = 437; break;
881  case 25: nCP = 437; break;
882  case 26: nCP = 850; break;
883  case 27: nCP = 437; break;
884  case 28: nCP = 863; break;
885  case 29: nCP = 850; break;
886  case 31: nCP = 852; break;
887  case 34: nCP = 852; break;
888  case 35: nCP = 852; break;
889  case 36: nCP = 860; break;
890  case 37: nCP = 850; break;
891  case 38: nCP = 866; break;
892  case 55: nCP = 850; break;
893  case 64: nCP = 852; break;
894  case 77: nCP = 936; break;
895  case 78: nCP = 949; break;
896  case 79: nCP = 950; break;
897  case 80: nCP = 874; break;
898  case 87: return QStringLiteral( "ISO-8859-1" );
899  case 88: nCP = 1252; break;
900  case 89: nCP = 1252; break;
901  case 100: nCP = 852; break;
902  case 101: nCP = 866; break;
903  case 102: nCP = 865; break;
904  case 103: nCP = 861; break;
905  case 104: nCP = 895; break;
906  case 105: nCP = 620; break;
907  case 106: nCP = 737; break;
908  case 107: nCP = 857; break;
909  case 108: nCP = 863; break;
910  case 120: nCP = 950; break;
911  case 121: nCP = 949; break;
912  case 122: nCP = 936; break;
913  case 123: nCP = 932; break;
914  case 124: nCP = 874; break;
915  case 134: nCP = 737; break;
916  case 135: nCP = 852; break;
917  case 136: nCP = 857; break;
918  case 150: nCP = 10007; break;
919  case 151: nCP = 10029; break;
920  case 200: nCP = 1250; break;
921  case 201: nCP = 1251; break;
922  case 202: nCP = 1254; break;
923  case 203: nCP = 1253; break;
924  case 204: nCP = 1257; break;
925  default: break;
926  }
927 
928  if ( nCP != -1 )
929  {
930  return QStringLiteral( "CP%1" ).arg( nCP );
931  }
932  }
933  }
934  return QString();
935 #endif
936 }
static endian_t endian()
Returns whether this machine uses big or little endian.
This class represents a coordinate reference system (CRS).
static QgsCoordinateReferenceSystem fromWkt(const QString &wkt)
Creates a CRS from a WKT spatial ref sys definition string.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
bool setAttribute(int field, const QVariant &attr)
Set an attribute's value by field index.
Definition: qgsfeature.cpp:236
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
Definition: qgsfeature.cpp:209
void setFields(const QgsFields &fields, bool initAttributes=false)
Assign a field map with the feature to allow attribute access by attribute name.
Definition: qgsfeature.cpp:169
void setId(QgsFeatureId id)
Sets the feature ID for this feature.
Definition: qgsfeature.cpp:114
void clearGeometry()
Removes any geometry associated with the feature.
Definition: qgsfeature.cpp:158
void setValid(bool validity)
Sets the validity of the feature.
Definition: qgsfeature.cpp:195
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:190
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:144
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:51
QVariant::Type type
Definition: qgsfield.h:58
QVariant::Type subType() const
If the field is a collection, gets its element's type.
Definition: qgsfield.cpp:133
Container of fields for a vector layer.
Definition: qgsfields.h:45
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
Definition: qgsfields.cpp:59
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:163
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
void fromWkb(unsigned char *wkb, int length)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
static QString readShapefileEncoding(const QString &path)
Reads the encoding of the shapefile at the specified path (where path is the location of the "....
static bool readOgrFeatureAttributes(OGRFeatureH ogrFet, const QgsFields &fields, QgsFeature &feature, QTextCodec *encoding)
Reads all attributes from an OGR feature into a QgsFeature.
static QgsGeometry ogrGeometryToQgsGeometry(OGRGeometryH geom)
Converts an OGR geometry representation to a QgsGeometry object.
static QString OGRSpatialReferenceToWkt(OGRSpatialReferenceH srs)
Returns a WKT string corresponding to the specified OGR srs object.
static QgsFeature readOgrFeature(OGRFeatureH ogrFet, const QgsFields &fields, QTextCodec *encoding)
Reads an OGR feature and converts it to a QgsFeature.
Definition: qgsogrutils.cpp:96
static QStringList cStringListToQStringList(char **stringList)
Converts a c string list to a QStringList.
static QgsFields readOgrFields(OGRFeatureH ogrFet, QTextCodec *encoding)
Reads an OGR feature and returns a corresponding fields collection.
static QgsWkbTypes::Type ogrGeometryTypeToQgsWkbType(OGRwkbGeometryType ogrGeomType)
Converts a OGRwkbGeometryType to QgsWkbTypes::Type.
static QgsCoordinateReferenceSystem OGRSpatialReferenceToCrs(OGRSpatialReferenceH srs)
Returns a QgsCoordinateReferenceSystem corresponding to the specified OGR srs object,...
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
static QString readShapefileEncodingFromCpg(const QString &path)
Reads the encoding of the shapefile at the specified path (where path is the location of the "....
static bool readOgrFeatureGeometry(OGRFeatureH ogrFet, QgsFeature &feature)
Reads the geometry from an OGR feature into a QgsFeature.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR.
static QString readShapefileEncodingFromLdid(const QString &path)
Reads the encoding of the shapefile at the specified path (where path is the location of the "....
static QVariant getOgrFeatureAttribute(OGRFeatureH ogrFet, const QgsFields &fields, int attIndex, QTextCodec *encoding, bool *ok=nullptr)
Retrieves an attribute value from an OGR feature.
static bool hasM(Type type) SIP_HOLDGIL
Tests whether a WKB type contains m values.
Definition: qgswkbtypes.h:1100
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:70
static Type zmType(Type type, bool hasZ, bool hasM) SIP_HOLDGIL
Returns the modified input geometry type according to hasZ / hasM.
Definition: qgswkbtypes.h:801
static Type flatType(Type type) SIP_HOLDGIL
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:702
static bool hasZ(Type type) SIP_HOLDGIL
Tests whether a WKB type contains the z-dimension.
Definition: qgswkbtypes.h:1050
void CORE_EXPORT fast_delete_and_close(dataset_unique_ptr &dataset, GDALDriverH driver, const QString &path)
Performs a fast close of an unwanted GDAL dataset handle by deleting the underlying data store.
Definition: qgsogrutils.cpp:71
std::unique_ptr< std::remove_pointer< OGRFeatureH >::type, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
Definition: qgsogrutils.h:129
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
Definition: qgsogrutils.h:134
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
Definition: qgsogrutils.h:114
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
Definition: qgis.h:769
void * GDALDatasetH
void * OGRSpatialReferenceH
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:614
const QgsField & field
Definition: qgsfield.h:472
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
std::unique_ptr< QgsLineString > ogrGeometryToQgsLineString(OGRGeometryH geom)
std::unique_ptr< QgsMultiLineString > ogrGeometryToQgsMultiLineString(OGRGeometryH geom)
#define OGR_F_IsFieldSetAndNotNull
Definition: qgsogrutils.cpp:40
std::unique_ptr< QgsMultiPoint > ogrGeometryToQgsMultiPoint(OGRGeometryH geom)
std::unique_ptr< QgsPoint > ogrGeometryToQgsPoint(OGRGeometryH geom)
void CORE_EXPORT operator()(GDALDatasetH datasource)
Destroys an gdal dataset, using the correct gdal calls.
Definition: qgsogrutils.cpp:66
void CORE_EXPORT operator()(GDALWarpOptions *options)
Destroys GDAL warp options, using the correct gdal calls.
Definition: qgsogrutils.cpp:91
void CORE_EXPORT operator()(OGRDataSourceH source)
Destroys an OGR data source, using the correct gdal calls.
Definition: qgsogrutils.cpp:45
void CORE_EXPORT operator()(OGRFeatureH feature)
Destroys an OGR feature, using the correct gdal calls.
Definition: qgsogrutils.cpp:61
void CORE_EXPORT operator()(OGRFieldDefnH definition)
Destroys an OGR field definition, using the correct gdal calls.
Definition: qgsogrutils.cpp:56
void CORE_EXPORT operator()(OGRGeometryH geometry)
Destroys an OGR geometry, using the correct gdal calls.
Definition: qgsogrutils.cpp:51