QGIS API Documentation  3.20.0-Odense (decaadbb31)
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 "qgslinesymbollayer.h"
26 #include "qgspolygon.h"
27 #include "qgsmultipolygon.h"
29 #include "qgsfillsymbollayer.h"
30 #include "qgsmarkersymbollayer.h"
31 #include "qgssymbollayerutils.h"
32 #include "qgsfontutils.h"
33 #include "qgsmessagelog.h"
34 #include "qgssymbol.h"
35 #include "qgsfillsymbol.h"
36 #include "qgslinesymbol.h"
37 #include "qgsmarkersymbol.h"
38 
39 #include <QTextCodec>
40 #include <QUuid>
41 #include <cpl_error.h>
42 #include <QJsonDocument>
43 #include <QFileInfo>
44 #include <QDir>
45 #include <QTextStream>
46 #include <QDataStream>
47 #include <QRegularExpression>
48 
49 #include "ogr_srs_api.h"
50 
51 
52 void gdal::OGRDataSourceDeleter::operator()( OGRDataSourceH source )
53 {
54  OGR_DS_Destroy( source );
55 }
56 
57 
58 void gdal::OGRGeometryDeleter::operator()( OGRGeometryH geometry )
59 {
60  OGR_G_DestroyGeometry( geometry );
61 }
62 
63 void gdal::OGRFldDeleter::operator()( OGRFieldDefnH definition )
64 {
65  OGR_Fld_Destroy( definition );
66 }
67 
68 void gdal::OGRFeatureDeleter::operator()( OGRFeatureH feature )
69 {
70  OGR_F_Destroy( feature );
71 }
72 
74 {
75  GDALClose( dataset );
76 }
77 
78 void gdal::fast_delete_and_close( gdal::dataset_unique_ptr &dataset, GDALDriverH driver, const QString &path )
79 {
80  // see https://github.com/qgis/QGIS/commit/d024910490a39e65e671f2055c5b6543e06c7042#commitcomment-25194282
81  // faster if we close the handle AFTER delete, but doesn't work for windows
82 #ifdef Q_OS_WIN
83  // close dataset handle
84  dataset.reset();
85 #endif
86 
87  CPLPushErrorHandler( CPLQuietErrorHandler );
88  GDALDeleteDataset( driver, path.toUtf8().constData() );
89  CPLPopErrorHandler();
90 
91 #ifndef Q_OS_WIN
92  // close dataset handle
93  dataset.reset();
94 #endif
95 }
96 
97 
98 void gdal::GDALWarpOptionsDeleter::operator()( GDALWarpOptions *options )
99 {
100  GDALDestroyWarpOptions( options );
101 }
102 
103 QVariant QgsOgrUtils::OGRFieldtoVariant( const OGRField *value, OGRFieldType type )
104 {
105  if ( !value || OGR_RawField_IsUnset( value ) || OGR_RawField_IsNull( value ) )
106  return QVariant();
107 
108  switch ( type )
109  {
110  case OFTInteger:
111  return value->Integer;
112 
113  case OFTInteger64:
114  return value->Integer64;
115 
116  case OFTReal:
117  return value->Real;
118 
119  case OFTString:
120  case OFTWideString:
121  return QString::fromUtf8( value->String );
122 
123  case OFTDate:
124  return QDate( value->Date.Year, value->Date.Month, value->Date.Day );
125 
126  case OFTTime:
127  {
128  float secondsPart = 0;
129  float millisecondPart = std::modf( value->Date.Second, &secondsPart );
130  return QTime( value->Date.Hour, value->Date.Minute, static_cast< int >( secondsPart ), static_cast< int >( 1000 * millisecondPart ) );
131  }
132 
133  case OFTDateTime:
134  {
135  float secondsPart = 0;
136  float millisecondPart = std::modf( value->Date.Second, &secondsPart );
137  return QDateTime( QDate( value->Date.Year, value->Date.Month, value->Date.Day ),
138  QTime( value->Date.Hour, value->Date.Minute, static_cast< int >( secondsPart ), static_cast< int >( 1000 * millisecondPart ) ) );
139  }
140 
141  case OFTBinary:
142  // not supported!
143  Q_ASSERT_X( false, "QgsOgrUtils::OGRFieldtoVariant", "OFTBinary type not supported" );
144  return QVariant();
145 
146  case OFTIntegerList:
147  {
148  QVariantList res;
149  res.reserve( value->IntegerList.nCount );
150  for ( int i = 0; i < value->IntegerList.nCount; ++i )
151  res << value->IntegerList.paList[ i ];
152  return res;
153  }
154 
155  case OFTInteger64List:
156  {
157  QVariantList res;
158  res.reserve( value->Integer64List.nCount );
159  for ( int i = 0; i < value->Integer64List.nCount; ++i )
160  res << value->Integer64List.paList[ i ];
161  return res;
162  }
163 
164  case OFTRealList:
165  {
166  QVariantList res;
167  res.reserve( value->RealList.nCount );
168  for ( int i = 0; i < value->RealList.nCount; ++i )
169  res << value->RealList.paList[ i ];
170  return res;
171  }
172 
173  case OFTStringList:
174  case OFTWideStringList:
175  {
176  QVariantList res;
177  res.reserve( value->StringList.nCount );
178  for ( int i = 0; i < value->StringList.nCount; ++i )
179  res << QString::fromUtf8( value->StringList.paList[ i ] );
180  return res;
181  }
182  }
183  return QVariant();
184 }
185 
186 QgsFeature QgsOgrUtils::readOgrFeature( OGRFeatureH ogrFet, const QgsFields &fields, QTextCodec *encoding )
187 {
188  QgsFeature feature;
189  if ( !ogrFet )
190  {
191  feature.setValid( false );
192  return feature;
193  }
194 
195  feature.setId( OGR_F_GetFID( ogrFet ) );
196  feature.setValid( true );
197 
198  if ( !readOgrFeatureGeometry( ogrFet, feature ) )
199  {
200  feature.setValid( false );
201  }
202 
203  if ( !readOgrFeatureAttributes( ogrFet, fields, feature, encoding ) )
204  {
205  feature.setValid( false );
206  }
207 
208  return feature;
209 }
210 
211 QgsFields QgsOgrUtils::readOgrFields( OGRFeatureH ogrFet, QTextCodec *encoding )
212 {
213  QgsFields fields;
214 
215  if ( !ogrFet )
216  return fields;
217 
218  int fieldCount = OGR_F_GetFieldCount( ogrFet );
219  for ( int i = 0; i < fieldCount; ++i )
220  {
221  OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, i );
222  if ( !fldDef )
223  {
224  fields.append( QgsField() );
225  continue;
226  }
227 
228  QString name = encoding ? encoding->toUnicode( OGR_Fld_GetNameRef( fldDef ) ) : QString::fromUtf8( OGR_Fld_GetNameRef( fldDef ) );
229  QVariant::Type varType;
230  switch ( OGR_Fld_GetType( fldDef ) )
231  {
232  case OFTInteger:
233  if ( OGR_Fld_GetSubType( fldDef ) == OFSTBoolean )
234  varType = QVariant::Bool;
235  else
236  varType = QVariant::Int;
237  break;
238  case OFTInteger64:
239  varType = QVariant::LongLong;
240  break;
241  case OFTReal:
242  varType = QVariant::Double;
243  break;
244  case OFTDate:
245  varType = QVariant::Date;
246  break;
247  case OFTTime:
248  varType = QVariant::Time;
249  break;
250  case OFTDateTime:
251  varType = QVariant::DateTime;
252  break;
253  case OFTString:
254  if ( OGR_Fld_GetSubType( fldDef ) == OFSTJSON )
255  varType = QVariant::Map;
256  else
257  varType = QVariant::String;
258  break;
259  default:
260  varType = QVariant::String; // other unsupported, leave it as a string
261  }
262  fields.append( QgsField( name, varType ) );
263  }
264  return fields;
265 }
266 
267 
268 QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsFields &fields, int attIndex, QTextCodec *encoding, bool *ok )
269 {
270  if ( attIndex < 0 || attIndex >= fields.count() )
271  {
272  if ( ok )
273  *ok = false;
274  return QVariant();
275  }
276 
277  const QgsField field = fields.at( attIndex );
278  return getOgrFeatureAttribute( ogrFet, field, attIndex, encoding, ok );
279 }
280 
281 QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsField &field, int attIndex, QTextCodec *encoding, bool *ok )
282 {
283  if ( !ogrFet || attIndex < 0 )
284  {
285  if ( ok )
286  *ok = false;
287  return QVariant();
288  }
289 
290  OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attIndex );
291 
292  if ( ! fldDef )
293  {
294  if ( ok )
295  *ok = false;
296 
297  QgsDebugMsg( QStringLiteral( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ) );
298  return QVariant();
299  }
300 
301  QVariant value;
302 
303  if ( ok )
304  *ok = true;
305 
306  if ( OGR_F_IsFieldSetAndNotNull( ogrFet, attIndex ) )
307  {
308  switch ( field.type() )
309  {
310  case QVariant::String:
311  {
312  if ( encoding )
313  value = QVariant( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) );
314  else
315  value = QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) );
316 
317 #ifdef Q_OS_WIN
318  // Fixes GH #41076 (empty strings shown as NULL), because we have checked before that it was NOT NULL
319  // Note: QVariant( QString( ) ).isNull( ) is still true on windows so we really need string literal :(
320  if ( value.isNull() )
321  value = QVariant( QStringLiteral( "" ) ); // skip-keyword-check
322 #endif
323 
324  break;
325  }
326  case QVariant::Int:
327  value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) );
328  break;
329  case QVariant::Bool:
330  value = QVariant( bool( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) ) );
331  break;
332  case QVariant::LongLong:
333  value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attIndex ) );
334  break;
335  case QVariant::Double:
336  value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attIndex ) );
337  break;
338  case QVariant::Date:
339  case QVariant::DateTime:
340  case QVariant::Time:
341  {
342  int year, month, day, hour, minute, second, tzf;
343 
344  OGR_F_GetFieldAsDateTime( ogrFet, attIndex, &year, &month, &day, &hour, &minute, &second, &tzf );
345  if ( field.type() == QVariant::Date )
346  value = QDate( year, month, day );
347  else if ( field.type() == QVariant::Time )
348  value = QTime( hour, minute, second );
349  else
350  value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) );
351  }
352  break;
353 
354  case QVariant::ByteArray:
355  {
356  int size = 0;
357  const GByte *b = OGR_F_GetFieldAsBinary( ogrFet, attIndex, &size );
358 
359  // QByteArray::fromRawData is funny. It doesn't take ownership of the data, so we have to explicitly call
360  // detach on it to force a copy which owns the data
361  QByteArray ba = QByteArray::fromRawData( reinterpret_cast<const char *>( b ), size );
362  ba.detach();
363 
364  value = ba;
365  break;
366  }
367 
368  case QVariant::StringList:
369  {
370  QStringList list;
371  char **lst = OGR_F_GetFieldAsStringList( ogrFet, attIndex );
372  const int count = CSLCount( lst );
373  if ( count > 0 )
374  {
375  list.reserve( count );
376  for ( int i = 0; i < count; i++ )
377  {
378  if ( encoding )
379  list << encoding->toUnicode( lst[i] );
380  else
381  list << QString::fromUtf8( lst[i] );
382  }
383  }
384  value = list;
385  break;
386  }
387 
388  case QVariant::List:
389  {
390  switch ( field.subType() )
391  {
392  case QVariant::String:
393  {
394  QStringList list;
395  char **lst = OGR_F_GetFieldAsStringList( ogrFet, attIndex );
396  const int count = CSLCount( lst );
397  if ( count > 0 )
398  {
399  list.reserve( count );
400  for ( int i = 0; i < count; i++ )
401  {
402  if ( encoding )
403  list << encoding->toUnicode( lst[i] );
404  else
405  list << QString::fromUtf8( lst[i] );
406  }
407  }
408  value = list;
409  break;
410  }
411 
412  case QVariant::Int:
413  {
414  QVariantList list;
415  int count = 0;
416  const int *lst = OGR_F_GetFieldAsIntegerList( ogrFet, attIndex, &count );
417  if ( count > 0 )
418  {
419  list.reserve( count );
420  for ( int i = 0; i < count; i++ )
421  {
422  list << lst[i];
423  }
424  }
425  value = list;
426  break;
427  }
428 
429  case QVariant::Double:
430  {
431  QVariantList list;
432  int count = 0;
433  const double *lst = OGR_F_GetFieldAsDoubleList( ogrFet, attIndex, &count );
434  if ( count > 0 )
435  {
436  list.reserve( count );
437  for ( int i = 0; i < count; i++ )
438  {
439  list << lst[i];
440  }
441  }
442  value = list;
443  break;
444  }
445 
446  case QVariant::LongLong:
447  {
448  QVariantList list;
449  int count = 0;
450  const long long *lst = OGR_F_GetFieldAsInteger64List( ogrFet, attIndex, &count );
451  if ( count > 0 )
452  {
453  list.reserve( count );
454  for ( int i = 0; i < count; i++ )
455  {
456  list << lst[i];
457  }
458  }
459  value = list;
460  break;
461  }
462 
463  default:
464  {
465  Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" );
466  if ( ok )
467  *ok = false;
468  break;
469  }
470  }
471  break;
472  }
473 
474  case QVariant::Map:
475  {
476  //it has to be JSON
477  //it's null if no json format
478  if ( encoding )
479  value = QJsonDocument::fromJson( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ).toUtf8() ).toVariant();
480  else
481  value = QJsonDocument::fromJson( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ).toUtf8() ).toVariant();
482  break;
483  }
484  default:
485  Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" );
486  if ( ok )
487  *ok = false;
488  }
489  }
490  else
491  {
492  value = QVariant( field.type() );
493  }
494 
495  return value;
496 }
497 
498 bool QgsOgrUtils::readOgrFeatureAttributes( OGRFeatureH ogrFet, const QgsFields &fields, QgsFeature &feature, QTextCodec *encoding )
499 {
500  // read all attributes
501  feature.initAttributes( fields.count() );
502  feature.setFields( fields );
503 
504  if ( !ogrFet )
505  return false;
506 
507  bool ok = false;
508  for ( int idx = 0; idx < fields.count(); ++idx )
509  {
510  QVariant value = getOgrFeatureAttribute( ogrFet, fields, idx, encoding, &ok );
511  if ( ok )
512  {
513  feature.setAttribute( idx, value );
514  }
515  }
516  return true;
517 }
518 
519 bool QgsOgrUtils::readOgrFeatureGeometry( OGRFeatureH ogrFet, QgsFeature &feature )
520 {
521  if ( !ogrFet )
522  return false;
523 
524  OGRGeometryH geom = OGR_F_GetGeometryRef( ogrFet );
525  if ( !geom )
526  feature.clearGeometry();
527  else
528  feature.setGeometry( ogrGeometryToQgsGeometry( geom ) );
529 
530  return true;
531 }
532 
533 std::unique_ptr< QgsPoint > ogrGeometryToQgsPoint( OGRGeometryH geom )
534 {
535  QgsWkbTypes::Type wkbType = static_cast<QgsWkbTypes::Type>( OGR_G_GetGeometryType( geom ) );
536 
537  double x, y, z, m;
538  OGR_G_GetPointZM( geom, 0, &x, &y, &z, &m );
539  return std::make_unique< QgsPoint >( wkbType, x, y, z, m );
540 }
541 
542 std::unique_ptr< QgsMultiPoint > ogrGeometryToQgsMultiPoint( OGRGeometryH geom )
543 {
544  std::unique_ptr< QgsMultiPoint > mp = std::make_unique< QgsMultiPoint >();
545 
546  const int count = OGR_G_GetGeometryCount( geom );
547  mp->reserve( count );
548  for ( int i = 0; i < count; ++i )
549  {
550  mp->addGeometry( ogrGeometryToQgsPoint( OGR_G_GetGeometryRef( geom, i ) ).release() );
551  }
552 
553  return mp;
554 }
555 
556 std::unique_ptr< QgsLineString > ogrGeometryToQgsLineString( OGRGeometryH geom )
557 {
558  QgsWkbTypes::Type wkbType = static_cast<QgsWkbTypes::Type>( OGR_G_GetGeometryType( geom ) );
559 
560  int count = OGR_G_GetPointCount( geom );
561  QVector< double > x( count );
562  QVector< double > y( count );
563  QVector< double > z;
564  double *pz = nullptr;
565  if ( QgsWkbTypes::hasZ( wkbType ) )
566  {
567  z.resize( count );
568  pz = z.data();
569  }
570  double *pm = nullptr;
571  QVector< double > m;
572  if ( QgsWkbTypes::hasM( wkbType ) )
573  {
574  m.resize( count );
575  pm = m.data();
576  }
577  OGR_G_GetPointsZM( geom, x.data(), sizeof( double ), y.data(), sizeof( double ), pz, sizeof( double ), pm, sizeof( double ) );
578 
579  return std::make_unique< QgsLineString>( x, y, z, m, wkbType == QgsWkbTypes::LineString25D );
580 }
581 
582 std::unique_ptr< QgsMultiLineString > ogrGeometryToQgsMultiLineString( OGRGeometryH geom )
583 {
584  std::unique_ptr< QgsMultiLineString > mp = std::make_unique< QgsMultiLineString >();
585 
586  const int count = OGR_G_GetGeometryCount( geom );
587  mp->reserve( count );
588  for ( int i = 0; i < count; ++i )
589  {
590  mp->addGeometry( ogrGeometryToQgsLineString( OGR_G_GetGeometryRef( geom, i ) ).release() );
591  }
592 
593  return mp;
594 }
595 
596 std::unique_ptr< QgsPolygon > ogrGeometryToQgsPolygon( OGRGeometryH geom )
597 {
598  std::unique_ptr< QgsPolygon > polygon = std::make_unique< QgsPolygon >();
599 
600  const int count = OGR_G_GetGeometryCount( geom );
601  if ( count >= 1 )
602  {
603  polygon->setExteriorRing( ogrGeometryToQgsLineString( OGR_G_GetGeometryRef( geom, 0 ) ).release() );
604  }
605 
606  for ( int i = 1; i < count; ++i )
607  {
608  polygon->addInteriorRing( ogrGeometryToQgsLineString( OGR_G_GetGeometryRef( geom, i ) ).release() );
609  }
610 
611  return polygon;
612 }
613 
614 std::unique_ptr< QgsMultiPolygon > ogrGeometryToQgsMultiPolygon( OGRGeometryH geom )
615 {
616  std::unique_ptr< QgsMultiPolygon > polygon = std::make_unique< QgsMultiPolygon >();
617 
618  const int count = OGR_G_GetGeometryCount( geom );
619  polygon->reserve( count );
620  for ( int i = 0; i < count; ++i )
621  {
622  polygon->addGeometry( ogrGeometryToQgsPolygon( OGR_G_GetGeometryRef( geom, i ) ).release() );
623  }
624 
625  return polygon;
626 }
627 
629 {
630  switch ( ogrGeomType )
631  {
632  case wkbUnknown: return QgsWkbTypes::Type::Unknown;
633  case wkbPoint: return QgsWkbTypes::Type::Point;
634  case wkbLineString: return QgsWkbTypes::Type::LineString;
635  case wkbPolygon: return QgsWkbTypes::Type::Polygon;
636  case wkbMultiPoint: return QgsWkbTypes::Type::MultiPoint;
637  case wkbMultiLineString: return QgsWkbTypes::Type::MultiLineString;
638  case wkbMultiPolygon: return QgsWkbTypes::Type::MultiPolygon;
639  case wkbGeometryCollection: return QgsWkbTypes::Type::GeometryCollection;
640  case wkbCircularString: return QgsWkbTypes::Type::CircularString;
641  case wkbCompoundCurve: return QgsWkbTypes::Type::CompoundCurve;
642  case wkbCurvePolygon: return QgsWkbTypes::Type::CurvePolygon;
643  case wkbMultiCurve: return QgsWkbTypes::Type::MultiCurve;
644  case wkbMultiSurface: return QgsWkbTypes::Type::MultiSurface;
645  case wkbCurve: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
646  case wkbSurface: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
647  case wkbPolyhedralSurface: return QgsWkbTypes::Type::Unknown; // no actual matching
648  case wkbTIN: return QgsWkbTypes::Type::Unknown; // no actual matching
649  case wkbTriangle: return QgsWkbTypes::Type::Triangle;
650 
651  case wkbNone: return QgsWkbTypes::Type::NoGeometry;
652  case wkbLinearRing: return QgsWkbTypes::Type::LineString; // approximate match
653 
654  case wkbCircularStringZ: return QgsWkbTypes::Type::CircularStringZ;
655  case wkbCompoundCurveZ: return QgsWkbTypes::Type::CompoundCurveZ;
656  case wkbCurvePolygonZ: return QgsWkbTypes::Type::CurvePolygonZ;
657  case wkbMultiCurveZ: return QgsWkbTypes::Type::MultiCurveZ;
658  case wkbMultiSurfaceZ: return QgsWkbTypes::Type::MultiSurfaceZ;
659  case wkbCurveZ: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
660  case wkbSurfaceZ: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
661  case wkbPolyhedralSurfaceZ: return QgsWkbTypes::Type::Unknown; // no actual matching
662  case wkbTINZ: return QgsWkbTypes::Type::Unknown; // no actual matching
663  case wkbTriangleZ: return QgsWkbTypes::Type::TriangleZ;
664 
665  case wkbPointM: return QgsWkbTypes::Type::PointM;
666  case wkbLineStringM: return QgsWkbTypes::Type::LineStringM;
667  case wkbPolygonM: return QgsWkbTypes::Type::PolygonM;
668  case wkbMultiPointM: return QgsWkbTypes::Type::MultiPointM;
669  case wkbMultiLineStringM: return QgsWkbTypes::Type::MultiLineStringM;
670  case wkbMultiPolygonM: return QgsWkbTypes::Type::MultiPolygonM;
671  case wkbGeometryCollectionM: return QgsWkbTypes::Type::GeometryCollectionM;
672  case wkbCircularStringM: return QgsWkbTypes::Type::CircularStringM;
673  case wkbCompoundCurveM: return QgsWkbTypes::Type::CompoundCurveM;
674  case wkbCurvePolygonM: return QgsWkbTypes::Type::CurvePolygonM;
675  case wkbMultiCurveM: return QgsWkbTypes::Type::MultiCurveM;
676  case wkbMultiSurfaceM: return QgsWkbTypes::Type::MultiSurfaceM;
677  case wkbCurveM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
678  case wkbSurfaceM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
679  case wkbPolyhedralSurfaceM: return QgsWkbTypes::Type::Unknown; // no actual matching
680  case wkbTINM: return QgsWkbTypes::Type::Unknown; // no actual matching
681  case wkbTriangleM: return QgsWkbTypes::Type::TriangleM;
682 
683  case wkbPointZM: return QgsWkbTypes::Type::PointZM;
684  case wkbLineStringZM: return QgsWkbTypes::Type::LineStringZM;
685  case wkbPolygonZM: return QgsWkbTypes::Type::PolygonZM;
686  case wkbMultiPointZM: return QgsWkbTypes::Type::MultiPointZM;
687  case wkbMultiLineStringZM: return QgsWkbTypes::Type::MultiLineStringZM;
688  case wkbMultiPolygonZM: return QgsWkbTypes::Type::MultiPolygonZM;
689  case wkbGeometryCollectionZM: return QgsWkbTypes::Type::GeometryCollectionZM;
690  case wkbCircularStringZM: return QgsWkbTypes::Type::CircularStringZM;
691  case wkbCompoundCurveZM: return QgsWkbTypes::Type::CompoundCurveZM;
692  case wkbCurvePolygonZM: return QgsWkbTypes::Type::CurvePolygonZM;
693  case wkbMultiCurveZM: return QgsWkbTypes::Type::MultiCurveZM;
694  case wkbMultiSurfaceZM: return QgsWkbTypes::Type::MultiSurfaceZM;
695  case wkbCurveZM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
696  case wkbSurfaceZM: return QgsWkbTypes::Type::Unknown; // not an actual concrete type
697  case wkbPolyhedralSurfaceZM: return QgsWkbTypes::Type::Unknown; // no actual matching
698  case wkbTINZM: return QgsWkbTypes::Type::Unknown; // no actual matching
699  case wkbTriangleZM: return QgsWkbTypes::Type::TriangleZM;
700 
701  case wkbPoint25D: return QgsWkbTypes::Type::PointZ;
702  case wkbLineString25D: return QgsWkbTypes::Type::LineStringZ;
703  case wkbPolygon25D: return QgsWkbTypes::Type::PolygonZ;
704  case wkbMultiPoint25D: return QgsWkbTypes::Type::MultiPointZ;
705  case wkbMultiLineString25D: return QgsWkbTypes::Type::MultiLineStringZ;
706  case wkbMultiPolygon25D: return QgsWkbTypes::Type::MultiPolygonZ;
707  case wkbGeometryCollection25D: return QgsWkbTypes::Type::GeometryCollectionZ;
708  }
709 
710  // should not reach that point normally
711  return QgsWkbTypes::Type::Unknown;
712 }
713 
715 {
716  if ( !geom )
717  return QgsGeometry();
718 
719  const auto ogrGeomType = OGR_G_GetGeometryType( geom );
720  QgsWkbTypes::Type wkbType = ogrGeometryTypeToQgsWkbType( ogrGeomType );
721 
722  // optimised case for some geometry classes, avoiding wkb conversion on OGR/QGIS sides
723  // TODO - extend to other classes!
724  switch ( QgsWkbTypes::flatType( wkbType ) )
725  {
726  case QgsWkbTypes::Point:
727  {
728  return QgsGeometry( ogrGeometryToQgsPoint( geom ) );
729  }
730 
732  {
733  return QgsGeometry( ogrGeometryToQgsMultiPoint( geom ) );
734  }
735 
737  {
738  return QgsGeometry( ogrGeometryToQgsLineString( geom ) );
739  }
740 
742  {
744  }
745 
747  {
748  return QgsGeometry( ogrGeometryToQgsPolygon( geom ) );
749  }
750 
752  {
753  return QgsGeometry( ogrGeometryToQgsMultiPolygon( geom ) );
754  }
755 
756  default:
757  break;
758  }
759 
760  // Fallback to inefficient WKB conversions
761 
762  if ( wkbFlatten( wkbType ) == wkbGeometryCollection )
763  {
764  // Shapefile MultiPatch can be reported as GeometryCollectionZ of TINZ
765  if ( OGR_G_GetGeometryCount( geom ) >= 1 &&
766  wkbFlatten( OGR_G_GetGeometryType( OGR_G_GetGeometryRef( geom, 0 ) ) ) == wkbTIN )
767  {
768  auto newGeom = OGR_G_ForceToMultiPolygon( OGR_G_Clone( geom ) );
769  auto ret = ogrGeometryToQgsGeometry( newGeom );
770  OGR_G_DestroyGeometry( newGeom );
771  return ret;
772  }
773  }
774 
775  // get the wkb representation
776  int memorySize = OGR_G_WkbSize( geom );
777  unsigned char *wkb = new unsigned char[memorySize];
778  OGR_G_ExportToWkb( geom, static_cast<OGRwkbByteOrder>( QgsApplication::endian() ), wkb );
779 
780  // Read original geometry type
781  uint32_t origGeomType;
782  memcpy( &origGeomType, wkb + 1, sizeof( uint32_t ) );
783  bool hasZ = ( origGeomType >= 1000 && origGeomType < 2000 ) || ( origGeomType >= 3000 && origGeomType < 4000 );
784  bool hasM = ( origGeomType >= 2000 && origGeomType < 3000 ) || ( origGeomType >= 3000 && origGeomType < 4000 );
785 
786  // PolyhedralSurface and TINs are not supported, map them to multipolygons...
787  if ( origGeomType % 1000 == 16 ) // is TIN, TINZ, TINM or TINZM
788  {
789  // TIN has the same wkb layout as a multipolygon, just need to overwrite the geom types...
790  int nDims = 2 + hasZ + hasM;
791  uint32_t newMultiType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::MultiPolygon, hasZ, hasM ) );
792  uint32_t newSingleType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::Polygon, hasZ, hasM ) );
793  unsigned char *wkbptr = wkb;
794 
795  // Endianness
796  wkbptr += 1;
797 
798  // Overwrite geom type
799  memcpy( wkbptr, &newMultiType, sizeof( uint32_t ) );
800  wkbptr += 4;
801 
802  // Geom count
803  uint32_t numGeoms;
804  memcpy( &numGeoms, wkb + 5, sizeof( uint32_t ) );
805  wkbptr += 4;
806 
807  // For each part, overwrite the geometry type to polygon (Z|M)
808  for ( uint32_t i = 0; i < numGeoms; ++i )
809  {
810  // Endianness
811  wkbptr += 1;
812 
813  // Overwrite geom type
814  memcpy( wkbptr, &newSingleType, sizeof( uint32_t ) );
815  wkbptr += sizeof( uint32_t );
816 
817  // skip coordinates
818  uint32_t nRings;
819  memcpy( &nRings, wkbptr, sizeof( uint32_t ) );
820  wkbptr += sizeof( uint32_t );
821 
822  for ( uint32_t j = 0; j < nRings; ++j )
823  {
824  uint32_t nPoints;
825  memcpy( &nPoints, wkbptr, sizeof( uint32_t ) );
826  wkbptr += sizeof( uint32_t ) + sizeof( double ) * nDims * nPoints;
827  }
828  }
829  }
830  else if ( origGeomType % 1000 == 15 ) // PolyhedralSurface, PolyhedralSurfaceZ, PolyhedralSurfaceM or PolyhedralSurfaceZM
831  {
832  // PolyhedralSurface has the same wkb layout as a MultiPolygon, just need to overwrite the geom type...
833  uint32_t newType = static_cast<uint32_t>( QgsWkbTypes::zmType( QgsWkbTypes::MultiPolygon, hasZ, hasM ) );
834  // Overwrite geom type
835  memcpy( wkb + 1, &newType, sizeof( uint32_t ) );
836  }
837 
838  QgsGeometry g;
839  g.fromWkb( wkb, memorySize );
840  return g;
841 }
842 
843 QgsFeatureList QgsOgrUtils::stringToFeatureList( const QString &string, const QgsFields &fields, QTextCodec *encoding )
844 {
845  QgsFeatureList features;
846  if ( string.isEmpty() )
847  return features;
848 
849  QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() );
850 
851  // create memory file system object from string buffer
852  QByteArray ba = string.toUtf8();
853  VSIFCloseL( VSIFileFromMemBuffer( randomFileName.toUtf8().constData(), reinterpret_cast< GByte * >( ba.data() ),
854  static_cast< vsi_l_offset >( ba.size() ), FALSE ) );
855 
856  gdal::ogr_datasource_unique_ptr hDS( OGROpen( randomFileName.toUtf8().constData(), false, nullptr ) );
857  if ( !hDS )
858  {
859  VSIUnlink( randomFileName.toUtf8().constData() );
860  return features;
861  }
862 
863  OGRLayerH ogrLayer = OGR_DS_GetLayer( hDS.get(), 0 );
864  if ( !ogrLayer )
865  {
866  hDS.reset();
867  VSIUnlink( randomFileName.toUtf8().constData() );
868  return features;
869  }
870 
872  while ( oFeat.reset( OGR_L_GetNextFeature( ogrLayer ) ), oFeat )
873  {
874  QgsFeature feat = readOgrFeature( oFeat.get(), fields, encoding );
875  if ( feat.isValid() )
876  features << feat;
877  }
878 
879  hDS.reset();
880  VSIUnlink( randomFileName.toUtf8().constData() );
881 
882  return features;
883 }
884 
885 QgsFields QgsOgrUtils::stringToFields( const QString &string, QTextCodec *encoding )
886 {
887  QgsFields fields;
888  if ( string.isEmpty() )
889  return fields;
890 
891  QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() );
892 
893  // create memory file system object from buffer
894  QByteArray ba = string.toUtf8();
895  VSIFCloseL( VSIFileFromMemBuffer( randomFileName.toUtf8().constData(), reinterpret_cast< GByte * >( ba.data() ),
896  static_cast< vsi_l_offset >( ba.size() ), FALSE ) );
897 
898  gdal::ogr_datasource_unique_ptr hDS( OGROpen( randomFileName.toUtf8().constData(), false, nullptr ) );
899  if ( !hDS )
900  {
901  VSIUnlink( randomFileName.toUtf8().constData() );
902  return fields;
903  }
904 
905  OGRLayerH ogrLayer = OGR_DS_GetLayer( hDS.get(), 0 );
906  if ( !ogrLayer )
907  {
908  hDS.reset();
909  VSIUnlink( randomFileName.toUtf8().constData() );
910  return fields;
911  }
912 
914  //read in the first feature only
915  if ( oFeat.reset( OGR_L_GetNextFeature( ogrLayer ) ), oFeat )
916  {
917  fields = readOgrFields( oFeat.get(), encoding );
918  }
919 
920  hDS.reset();
921  VSIUnlink( randomFileName.toUtf8().constData() );
922  return fields;
923 }
924 
925 QStringList QgsOgrUtils::cStringListToQStringList( char **stringList )
926 {
927  QStringList strings;
928 
929  // presume null terminated string list
930  for ( qgssize i = 0; stringList[i]; ++i )
931  {
932  strings.append( QString::fromUtf8( stringList[i] ) );
933  }
934 
935  return strings;
936 }
937 
939 {
940  if ( !srs )
941  return QString();
942 
943  char *pszWkt = nullptr;
944  const QByteArray multiLineOption = QStringLiteral( "MULTILINE=NO" ).toLocal8Bit();
945  const QByteArray formatOption = QStringLiteral( "FORMAT=WKT2" ).toLocal8Bit();
946  const char *const options[] = {multiLineOption.constData(), formatOption.constData(), nullptr};
947  OSRExportToWktEx( srs, &pszWkt, options );
948 
949  const QString res( pszWkt );
950  CPLFree( pszWkt );
951  return res;
952 }
953 
955 {
956  const QString wkt = OGRSpatialReferenceToWkt( srs );
957  if ( wkt.isEmpty() )
959 
961 }
962 
963 QString QgsOgrUtils::readShapefileEncoding( const QString &path )
964 {
965  const QString cpgEncoding = readShapefileEncodingFromCpg( path );
966  if ( !cpgEncoding.isEmpty() )
967  return cpgEncoding;
968 
969  return readShapefileEncodingFromLdid( path );
970 }
971 
972 QString QgsOgrUtils::readShapefileEncodingFromCpg( const QString &path )
973 {
974 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,1,0)
975  QString errCause;
976  QgsOgrLayerUniquePtr layer = QgsOgrProviderUtils::getLayer( path, false, QStringList(), 0, errCause, false );
977  return layer ? layer->GetMetadataItem( QStringLiteral( "ENCODING_FROM_CPG" ), QStringLiteral( "SHAPEFILE" ) ) : QString();
978 #else
979  if ( !QFileInfo::exists( path ) )
980  return QString();
981 
982  // first try to read cpg file, if present
983  const QFileInfo fi( path );
984  const QString baseName = fi.completeBaseName();
985  const QString cpgPath = fi.dir().filePath( QStringLiteral( "%1.%2" ).arg( baseName, fi.suffix() == QLatin1String( "SHP" ) ? QStringLiteral( "CPG" ) : QStringLiteral( "cpg" ) ) );
986  if ( QFile::exists( cpgPath ) )
987  {
988  QFile cpgFile( cpgPath );
989  if ( cpgFile.open( QIODevice::ReadOnly ) )
990  {
991  QTextStream cpgStream( &cpgFile );
992  const QString cpgString = cpgStream.readLine();
993  cpgFile.close();
994 
995  if ( !cpgString.isEmpty() )
996  {
997  // from OGRShapeLayer::ConvertCodePage
998  // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp#L342
999  bool ok = false;
1000  int cpgCodePage = cpgString.toInt( &ok );
1001  if ( ok && ( ( cpgCodePage >= 437 && cpgCodePage <= 950 )
1002  || ( cpgCodePage >= 1250 && cpgCodePage <= 1258 ) ) )
1003  {
1004  return QStringLiteral( "CP%1" ).arg( cpgCodePage );
1005  }
1006  else if ( cpgString.startsWith( QLatin1String( "8859" ) ) )
1007  {
1008  if ( cpgString.length() > 4 && cpgString.at( 4 ) == '-' )
1009  return QStringLiteral( "ISO-8859-%1" ).arg( cpgString.mid( 5 ) );
1010  else
1011  return QStringLiteral( "ISO-8859-%1" ).arg( cpgString.mid( 4 ) );
1012  }
1013  else if ( cpgString.startsWith( QLatin1String( "UTF-8" ), Qt::CaseInsensitive ) ||
1014  cpgString.startsWith( QLatin1String( "UTF8" ), Qt::CaseInsensitive ) )
1015  return QStringLiteral( "UTF-8" );
1016  else if ( cpgString.startsWith( QLatin1String( "ANSI 1251" ), Qt::CaseInsensitive ) )
1017  return QStringLiteral( "CP1251" );
1018 
1019  return cpgString;
1020  }
1021  }
1022  }
1023 
1024  return QString();
1025 #endif
1026 }
1027 
1028 QString QgsOgrUtils::readShapefileEncodingFromLdid( const QString &path )
1029 {
1030 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,1,0)
1031  QString errCause;
1032  QgsOgrLayerUniquePtr layer = QgsOgrProviderUtils::getLayer( path, false, QStringList(), 0, errCause, false );
1033  return layer ? layer->GetMetadataItem( QStringLiteral( "ENCODING_FROM_LDID" ), QStringLiteral( "SHAPEFILE" ) ) : QString();
1034 #else
1035  // from OGRShapeLayer::ConvertCodePage
1036  // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrsf_frmts/shape/ogrshapelayer.cpp#L342
1037 
1038  if ( !QFileInfo::exists( path ) )
1039  return QString();
1040 
1041  // first try to read cpg file, if present
1042  const QFileInfo fi( path );
1043  const QString baseName = fi.completeBaseName();
1044 
1045  // fallback to LDID value, read from DBF file
1046  const QString dbfPath = fi.dir().filePath( QStringLiteral( "%1.%2" ).arg( baseName, fi.suffix() == QLatin1String( "SHP" ) ? QStringLiteral( "DBF" ) : QStringLiteral( "dbf" ) ) );
1047  if ( QFile::exists( dbfPath ) )
1048  {
1049  QFile dbfFile( dbfPath );
1050  if ( dbfFile.open( QIODevice::ReadOnly ) )
1051  {
1052  dbfFile.read( 29 );
1053  QDataStream dbfIn( &dbfFile );
1054  dbfIn.setByteOrder( QDataStream::LittleEndian );
1055  quint8 ldid;
1056  dbfIn >> ldid;
1057  dbfFile.close();
1058 
1059  int nCP = -1; // Windows code page.
1060 
1061  // http://www.autopark.ru/ASBProgrammerGuide/DBFSTRUC.HTM
1062  switch ( ldid )
1063  {
1064  case 1: nCP = 437; break;
1065  case 2: nCP = 850; break;
1066  case 3: nCP = 1252; break;
1067  case 4: nCP = 10000; break;
1068  case 8: nCP = 865; break;
1069  case 10: nCP = 850; break;
1070  case 11: nCP = 437; break;
1071  case 13: nCP = 437; break;
1072  case 14: nCP = 850; break;
1073  case 15: nCP = 437; break;
1074  case 16: nCP = 850; break;
1075  case 17: nCP = 437; break;
1076  case 18: nCP = 850; break;
1077  case 19: nCP = 932; break;
1078  case 20: nCP = 850; break;
1079  case 21: nCP = 437; break;
1080  case 22: nCP = 850; break;
1081  case 23: nCP = 865; break;
1082  case 24: nCP = 437; break;
1083  case 25: nCP = 437; break;
1084  case 26: nCP = 850; break;
1085  case 27: nCP = 437; break;
1086  case 28: nCP = 863; break;
1087  case 29: nCP = 850; break;
1088  case 31: nCP = 852; break;
1089  case 34: nCP = 852; break;
1090  case 35: nCP = 852; break;
1091  case 36: nCP = 860; break;
1092  case 37: nCP = 850; break;
1093  case 38: nCP = 866; break;
1094  case 55: nCP = 850; break;
1095  case 64: nCP = 852; break;
1096  case 77: nCP = 936; break;
1097  case 78: nCP = 949; break;
1098  case 79: nCP = 950; break;
1099  case 80: nCP = 874; break;
1100  case 87: return QStringLiteral( "ISO-8859-1" );
1101  case 88: nCP = 1252; break;
1102  case 89: nCP = 1252; break;
1103  case 100: nCP = 852; break;
1104  case 101: nCP = 866; break;
1105  case 102: nCP = 865; break;
1106  case 103: nCP = 861; break;
1107  case 104: nCP = 895; break;
1108  case 105: nCP = 620; break;
1109  case 106: nCP = 737; break;
1110  case 107: nCP = 857; break;
1111  case 108: nCP = 863; break;
1112  case 120: nCP = 950; break;
1113  case 121: nCP = 949; break;
1114  case 122: nCP = 936; break;
1115  case 123: nCP = 932; break;
1116  case 124: nCP = 874; break;
1117  case 134: nCP = 737; break;
1118  case 135: nCP = 852; break;
1119  case 136: nCP = 857; break;
1120  case 150: nCP = 10007; break;
1121  case 151: nCP = 10029; break;
1122  case 200: nCP = 1250; break;
1123  case 201: nCP = 1251; break;
1124  case 202: nCP = 1254; break;
1125  case 203: nCP = 1253; break;
1126  case 204: nCP = 1257; break;
1127  default: break;
1128  }
1129 
1130  if ( nCP != -1 )
1131  {
1132  return QStringLiteral( "CP%1" ).arg( nCP );
1133  }
1134  }
1135  }
1136  return QString();
1137 #endif
1138 }
1139 
1140 QVariantMap QgsOgrUtils::parseStyleString( const QString &string )
1141 {
1142  QVariantMap styles;
1143 
1144  char **papszStyleString = CSLTokenizeString2( string.toUtf8().constData(), ";",
1145  CSLT_HONOURSTRINGS
1146  | CSLT_PRESERVEQUOTES
1147  | CSLT_PRESERVEESCAPES );
1148  for ( int i = 0; papszStyleString[i] != nullptr; ++i )
1149  {
1150  // style string format is:
1151  // <tool_name>([<tool_param>[,<tool_param>[,...]]])
1152 
1153  // first extract tool name
1154  const thread_local QRegularExpression sToolPartRx( QStringLiteral( "^(.*?)\\((.*)\\)$" ) );
1155  const QString stylePart( papszStyleString[i] );
1156  const QRegularExpressionMatch match = sToolPartRx.match( stylePart );
1157  if ( !match.hasMatch() )
1158  continue;
1159 
1160  const QString tool = match.captured( 1 );
1161  const QString params = match.captured( 2 );
1162 
1163  char **papszTokens = CSLTokenizeString2( params.toUtf8().constData(), ",", CSLT_HONOURSTRINGS
1164  | CSLT_PRESERVEESCAPES );
1165 
1166  QVariantMap toolParts;
1167  const thread_local QRegularExpression sToolParamRx( QStringLiteral( "^(.*?):(.*)$" ) );
1168  for ( int j = 0; papszTokens[j] != nullptr; ++j )
1169  {
1170  const QString toolPart( papszTokens[j] );
1171  const QRegularExpressionMatch toolMatch = sToolParamRx.match( toolPart );
1172  if ( !match.hasMatch() )
1173  continue;
1174 
1175  // note we always convert the keys to lowercase, just to be safe...
1176  toolParts.insert( toolMatch.captured( 1 ).toLower(), toolMatch.captured( 2 ) );
1177  }
1178  CSLDestroy( papszTokens );
1179 
1180  // note we always convert the keys to lowercase, just to be safe...
1181  styles.insert( tool.toLower(), toolParts );
1182  }
1183  CSLDestroy( papszStyleString );
1184  return styles;
1185 }
1186 
1187 std::unique_ptr<QgsSymbol> QgsOgrUtils::symbolFromStyleString( const QString &string, Qgis::SymbolType type )
1188 {
1189  const QVariantMap styles = parseStyleString( string );
1190 
1191  auto convertSize = []( const QString & size, double & value, QgsUnitTypes::RenderUnit & unit )->bool
1192  {
1193  const thread_local QRegularExpression sUnitRx = QRegularExpression( QStringLiteral( "^([\\d\\.]+)(g|px|pt|mm|cm|in)$" ) );
1194  const QRegularExpressionMatch match = sUnitRx.match( size );
1195  if ( match.hasMatch() )
1196  {
1197  value = match.captured( 1 ).toDouble();
1198  const QString unitString = match.captured( 2 );
1199  if ( unitString.compare( QLatin1String( "px" ), Qt::CaseInsensitive ) == 0 )
1200  {
1201  // pixels are a poor unit choice for QGIS -- they render badly in hidpi layouts. Convert to points instead, using
1202  // a 96 dpi conversion
1203  static constexpr double PT_TO_INCHES_FACTOR = 1 / 72.0;
1204  static constexpr double PX_TO_PT_FACTOR = 1 / ( 96.0 * PT_TO_INCHES_FACTOR );
1206  value *= PX_TO_PT_FACTOR;
1207  return true;
1208  }
1209  else if ( unitString.compare( QLatin1String( "pt" ), Qt::CaseInsensitive ) == 0 )
1210  {
1212  return true;
1213  }
1214  else if ( unitString.compare( QLatin1String( "mm" ), Qt::CaseInsensitive ) == 0 )
1215  {
1217  return true;
1218  }
1219  else if ( unitString.compare( QLatin1String( "cm" ), Qt::CaseInsensitive ) == 0 )
1220  {
1221  value *= 10;
1223  return true;
1224  }
1225  else if ( unitString.compare( QLatin1String( "in" ), Qt::CaseInsensitive ) == 0 )
1226  {
1228  return true;
1229  }
1230  else if ( unitString.compare( QLatin1String( "g" ), Qt::CaseInsensitive ) == 0 )
1231  {
1233  return true;
1234  }
1235  QgsDebugMsg( QStringLiteral( "Unknown unit %1" ).arg( unitString ) );
1236  }
1237  else
1238  {
1239  QgsDebugMsg( QStringLiteral( "Could not parse style size %1" ).arg( size ) );
1240  }
1241  return false;
1242  };
1243 
1244  auto convertColor = []( const QString & string ) -> QColor
1245  {
1246  if ( string.isEmpty() )
1247  return QColor();
1248 
1249  const thread_local QRegularExpression sColorWithAlphaRx = QRegularExpression( QStringLiteral( "^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})$" ) );
1250  const QRegularExpressionMatch match = sColorWithAlphaRx.match( string );
1251  if ( match.hasMatch() )
1252  {
1253  // need to convert #RRGGBBAA to #AARRGGBB for QColor
1254  return QColor( QStringLiteral( "#%1%2" ).arg( match.captured( 2 ), match.captured( 1 ) ) );
1255  }
1256  else
1257  {
1258  return QColor( string );
1259  }
1260  };
1261 
1262  auto convertPen = [&convertColor, &convertSize, string]( const QVariantMap & lineStyle ) -> std::unique_ptr< QgsSymbol >
1263  {
1264  QColor color = convertColor( lineStyle.value( QStringLiteral( "c" ), QStringLiteral( "#000000" ) ).toString() );
1265 
1266  double lineWidth = DEFAULT_SIMPLELINE_WIDTH;
1268  convertSize( lineStyle.value( QStringLiteral( "w" ) ).toString(), lineWidth, lineWidthUnit );
1269 
1270  // if the pen is a mapinfo pen, use dedicated converter for more accurate results
1271  const thread_local QRegularExpression sMapInfoId = QRegularExpression( QStringLiteral( "mapinfo-pen-(\\d+)" ) );
1272  const QRegularExpressionMatch match = sMapInfoId.match( string );
1273  if ( match.hasMatch() )
1274  {
1275  const int penId = match.captured( 1 ).toInt();
1277  std::unique_ptr<QgsSymbol> res( QgsMapInfoSymbolConverter::convertLineSymbol( penId, context, color, lineWidth, lineWidthUnit ) );
1278  if ( res )
1279  return res;
1280  }
1281 
1282  std::unique_ptr< QgsSimpleLineSymbolLayer > simpleLine = std::make_unique< QgsSimpleLineSymbolLayer >( color, lineWidth );
1283  simpleLine->setWidthUnit( lineWidthUnit );
1284 
1285  // pattern
1286  const QString pattern = lineStyle.value( QStringLiteral( "p" ) ).toString();
1287  if ( !pattern.isEmpty() )
1288  {
1289  const thread_local QRegularExpression sPatternUnitRx = QRegularExpression( QStringLiteral( "^([\\d\\.\\s]+)(g|px|pt|mm|cm|in)$" ) );
1290  const QRegularExpressionMatch match = sPatternUnitRx.match( pattern );
1291  if ( match.hasMatch() )
1292  {
1293  const QStringList patternValues = match.captured( 1 ).split( ' ' );
1294  QVector< qreal > dashPattern;
1296  for ( const QString &val : patternValues )
1297  {
1298  double length;
1299  convertSize( val + match.captured( 2 ), length, patternUnits );
1300  dashPattern.push_back( length * lineWidth * 2 );
1301  }
1302 
1303  simpleLine->setCustomDashVector( dashPattern );
1304  simpleLine->setCustomDashPatternUnit( patternUnits );
1305  simpleLine->setUseCustomDashPattern( true );
1306  }
1307  }
1308 
1309  Qt::PenCapStyle capStyle = Qt::FlatCap;
1310  Qt::PenJoinStyle joinStyle = Qt::MiterJoin;
1311  // workaround https://github.com/OSGeo/gdal/pull/3509 in older GDAL versions
1312  const QString id = lineStyle.value( QStringLiteral( "id" ) ).toString();
1313  if ( id.contains( QLatin1String( "mapinfo-pen" ), Qt::CaseInsensitive ) )
1314  {
1315  // MapInfo renders all lines using a round pen cap and round pen join
1316  // which are not the default values for OGR pen cap/join styles. So we need to explicitly
1317  // override the OGR default values here on older GDAL versions
1318  capStyle = Qt::RoundCap;
1319  joinStyle = Qt::RoundJoin;
1320  }
1321 
1322  // pen cap
1323  const QString penCap = lineStyle.value( QStringLiteral( "cap" ) ).toString();
1324  if ( penCap.compare( QLatin1String( "b" ), Qt::CaseInsensitive ) == 0 )
1325  {
1326  capStyle = Qt::FlatCap;
1327  }
1328  else if ( penCap.compare( QLatin1String( "r" ), Qt::CaseInsensitive ) == 0 )
1329  {
1330  capStyle = Qt::RoundCap;
1331  }
1332  else if ( penCap.compare( QLatin1String( "p" ), Qt::CaseInsensitive ) == 0 )
1333  {
1334  capStyle = Qt::SquareCap;
1335  }
1336  simpleLine->setPenCapStyle( capStyle );
1337 
1338  // pen join
1339  const QString penJoin = lineStyle.value( QStringLiteral( "j" ) ).toString();
1340  if ( penJoin.compare( QLatin1String( "m" ), Qt::CaseInsensitive ) == 0 )
1341  {
1342  joinStyle = Qt::MiterJoin;
1343  }
1344  else if ( penJoin.compare( QLatin1String( "r" ), Qt::CaseInsensitive ) == 0 )
1345  {
1346  joinStyle = Qt::RoundJoin;
1347  }
1348  else if ( penJoin.compare( QLatin1String( "b" ), Qt::CaseInsensitive ) == 0 )
1349  {
1350  joinStyle = Qt::BevelJoin;
1351  }
1352  simpleLine->setPenJoinStyle( joinStyle );
1353 
1354  const QString priority = lineStyle.value( QStringLiteral( "l" ) ).toString();
1355  if ( !priority.isEmpty() )
1356  {
1357  simpleLine->setRenderingPass( priority.toInt() );
1358  }
1359  return std::make_unique< QgsLineSymbol >( QgsSymbolLayerList() << simpleLine.release() );
1360  };
1361 
1362  auto convertBrush = [&convertColor]( const QVariantMap & brushStyle ) -> std::unique_ptr< QgsSymbol >
1363  {
1364  const QColor foreColor = convertColor( brushStyle.value( QStringLiteral( "fc" ), QStringLiteral( "#000000" ) ).toString() );
1365  const QColor backColor = convertColor( brushStyle.value( QStringLiteral( "bc" ), QString() ).toString() );
1366 
1367  const QString id = brushStyle.value( QStringLiteral( "id" ) ).toString();
1368 
1369  // if the pen is a mapinfo brush, use dedicated converter for more accurate results
1370  const thread_local QRegularExpression sMapInfoId = QRegularExpression( QStringLiteral( "mapinfo-brush-(\\d+)" ) );
1371  const QRegularExpressionMatch match = sMapInfoId.match( id );
1372  if ( match.hasMatch() )
1373  {
1374  const int brushId = match.captured( 1 ).toInt();
1376  std::unique_ptr<QgsSymbol> res( QgsMapInfoSymbolConverter::convertFillSymbol( brushId, context, foreColor, backColor ) );
1377  if ( res )
1378  return res;
1379  }
1380 
1381  const thread_local QRegularExpression sOgrId = QRegularExpression( QStringLiteral( "ogr-brush-(\\d+)" ) );
1382  const QRegularExpressionMatch ogrMatch = sOgrId.match( id );
1383 
1384  Qt::BrushStyle style = Qt::SolidPattern;
1385  if ( ogrMatch.hasMatch() )
1386  {
1387  const int brushId = ogrMatch.captured( 1 ).toInt();
1388  switch ( brushId )
1389  {
1390  case 0:
1391  style = Qt::SolidPattern;
1392  break;
1393 
1394  case 1:
1395  style = Qt::NoBrush;
1396  break;
1397 
1398  case 2:
1399  style = Qt::HorPattern;
1400  break;
1401 
1402  case 3:
1403  style = Qt::VerPattern;
1404  break;
1405 
1406  case 4:
1407  style = Qt::FDiagPattern;
1408  break;
1409 
1410  case 5:
1411  style = Qt::BDiagPattern;
1412  break;
1413 
1414  case 6:
1415  style = Qt::CrossPattern;
1416  break;
1417 
1418  case 7:
1419  style = Qt::DiagCrossPattern;
1420  break;
1421  }
1422  }
1423 
1424  QgsSymbolLayerList layers;
1425  if ( backColor.isValid() && style != Qt::SolidPattern && style != Qt::NoBrush )
1426  {
1427  std::unique_ptr< QgsSimpleFillSymbolLayer > backgroundFill = std::make_unique< QgsSimpleFillSymbolLayer >( backColor );
1428  backgroundFill->setLocked( true );
1429  backgroundFill->setStrokeStyle( Qt::NoPen );
1430  layers << backgroundFill.release();
1431  }
1432 
1433  std::unique_ptr< QgsSimpleFillSymbolLayer > foregroundFill = std::make_unique< QgsSimpleFillSymbolLayer >( foreColor );
1434  foregroundFill->setBrushStyle( style );
1435  foregroundFill->setStrokeStyle( Qt::NoPen );
1436 
1437  const QString priority = brushStyle.value( QStringLiteral( "l" ) ).toString();
1438  if ( !priority.isEmpty() )
1439  {
1440  foregroundFill->setRenderingPass( priority.toInt() );
1441  }
1442  layers << foregroundFill.release();
1443  return std::make_unique< QgsFillSymbol >( layers );
1444  };
1445 
1446  auto convertSymbol = [&convertColor, &convertSize, string]( const QVariantMap & symbolStyle ) -> std::unique_ptr< QgsSymbol >
1447  {
1448  const QColor color = convertColor( symbolStyle.value( QStringLiteral( "c" ), QStringLiteral( "#000000" ) ).toString() );
1449 
1450  double symbolSize = DEFAULT_SIMPLEMARKER_SIZE;
1452  convertSize( symbolStyle.value( QStringLiteral( "s" ) ).toString(), symbolSize, symbolSizeUnit );
1453 
1454  const double angle = symbolStyle.value( QStringLiteral( "a" ), QStringLiteral( "0" ) ).toDouble();
1455 
1456  const QString id = symbolStyle.value( QStringLiteral( "id" ) ).toString();
1457 
1458  // if the symbol is a mapinfo symbol, use dedicated converter for more accurate results
1459  const thread_local QRegularExpression sMapInfoId = QRegularExpression( QStringLiteral( "mapinfo-sym-(\\d+)" ) );
1460  const QRegularExpressionMatch match = sMapInfoId.match( id );
1461  if ( match.hasMatch() )
1462  {
1463  const int symbolId = match.captured( 1 ).toInt();
1465 
1466  // ogr interpretations of mapinfo symbol sizes are too large -- scale these down
1467  symbolSize *= 0.61;
1468 
1469  std::unique_ptr<QgsSymbol> res( QgsMapInfoSymbolConverter::convertMarkerSymbol( symbolId, context, color, symbolSize, symbolSizeUnit ) );
1470  if ( res )
1471  return res;
1472  }
1473 
1474  std::unique_ptr< QgsMarkerSymbolLayer > markerLayer;
1475 
1476  const thread_local QRegularExpression sFontId = QRegularExpression( QStringLiteral( "font-sym-(\\d+)" ) );
1477  const QRegularExpressionMatch fontMatch = sFontId.match( id );
1478  if ( fontMatch.hasMatch() )
1479  {
1480  const int symId = fontMatch.captured( 1 ).toInt();
1481  const QStringList families = symbolStyle.value( QStringLiteral( "f" ), QString() ).toString().split( ',' );
1482 
1483  bool familyFound = false;
1484  QString fontFamily;
1485  for ( const QString &family : std::as_const( families ) )
1486  {
1487  if ( QgsFontUtils::fontFamilyMatchOnSystem( family ) )
1488  {
1489  familyFound = true;
1490  fontFamily = family;
1491  break;
1492  }
1493  }
1494 
1495  if ( familyFound )
1496  {
1497  std::unique_ptr< QgsFontMarkerSymbolLayer > fontMarker = std::make_unique< QgsFontMarkerSymbolLayer >( fontFamily, QChar( symId ), symbolSize );
1498  fontMarker->setSizeUnit( symbolSizeUnit );
1499  fontMarker->setAngle( -angle );
1500 
1501  fontMarker->setColor( color );
1502 
1503  const QColor strokeColor = convertColor( symbolStyle.value( QStringLiteral( "o" ), QString() ).toString() );
1504  if ( strokeColor.isValid() )
1505  {
1506  fontMarker->setStrokeColor( strokeColor );
1507  fontMarker->setStrokeWidth( 1 );
1508  fontMarker->setStrokeWidthUnit( QgsUnitTypes::RenderPoints );
1509  }
1510  else
1511  {
1512  fontMarker->setStrokeWidth( 0 );
1513  }
1514 
1515  markerLayer = std::move( fontMarker );
1516  }
1517  else if ( !families.empty() )
1518  {
1519  // couldn't even find a matching font in the backup list
1520  QgsMessageLog::logMessage( QObject::tr( "Font %1 not found on system" ).arg( families.at( 0 ) ) );
1521  }
1522  }
1523 
1524  if ( !markerLayer )
1525  {
1526  const thread_local QRegularExpression sOgrId = QRegularExpression( QStringLiteral( "ogr-sym-(\\d+)" ) );
1527  const QRegularExpressionMatch ogrMatch = sOgrId.match( id );
1528 
1530  bool isFilled = true;
1531  if ( ogrMatch.hasMatch() )
1532  {
1533  const int symId = ogrMatch.captured( 1 ).toInt();
1534  switch ( symId )
1535  {
1536  case 0:
1537  shape = QgsSimpleMarkerSymbolLayer::Shape::Cross;
1538  break;
1539 
1540  case 1:
1541  shape = QgsSimpleMarkerSymbolLayer::Shape::Cross2;
1542  break;
1543 
1544  case 2:
1545  isFilled = false;
1546  shape = QgsSimpleMarkerSymbolLayer::Shape::Circle;
1547  break;
1548 
1549  case 3:
1550  shape = QgsSimpleMarkerSymbolLayer::Shape::Circle;
1551  break;
1552 
1553  case 4:
1554  isFilled = false;
1555  shape = QgsSimpleMarkerSymbolLayer::Shape::Square;
1556  break;
1557 
1558  case 5:
1559  shape = QgsSimpleMarkerSymbolLayer::Shape::Square;
1560  break;
1561 
1562  case 6:
1563  isFilled = false;
1564  shape = QgsSimpleMarkerSymbolLayer::Shape::Triangle;
1565  break;
1566 
1567  case 7:
1568  shape = QgsSimpleMarkerSymbolLayer::Shape::Triangle;
1569  break;
1570 
1571  case 8:
1572  isFilled = false;
1573  shape = QgsSimpleMarkerSymbolLayer::Shape::Star;
1574  break;
1575 
1576  case 9:
1577  shape = QgsSimpleMarkerSymbolLayer::Shape::Star;
1578  break;
1579 
1580  case 10:
1581  shape = QgsSimpleMarkerSymbolLayer::Shape::Line;
1582  break;
1583 
1584  default:
1585  isFilled = false;
1586  shape = QgsSimpleMarkerSymbolLayer::Shape::Square; // to initialize the variable
1587  break;
1588  }
1589  }
1590  else
1591  {
1592  isFilled = false;
1593  shape = QgsSimpleMarkerSymbolLayer::Shape::Square; // to initialize the variable
1594  }
1595 
1596  std::unique_ptr< QgsSimpleMarkerSymbolLayer > simpleMarker = std::make_unique< QgsSimpleMarkerSymbolLayer >( shape, symbolSize, -angle );
1597  simpleMarker->setSizeUnit( symbolSizeUnit );
1598 
1599  if ( isFilled && QgsSimpleMarkerSymbolLayer::shapeIsFilled( shape ) )
1600  {
1601  simpleMarker->setColor( color );
1602  simpleMarker->setStrokeStyle( Qt::NoPen );
1603  }
1604  else
1605  {
1606  simpleMarker->setFillColor( QColor( 0, 0, 0, 0 ) );
1607  simpleMarker->setStrokeColor( color );
1608  }
1609 
1610  const QColor strokeColor = convertColor( symbolStyle.value( QStringLiteral( "o" ), QString() ).toString() );
1611  if ( strokeColor.isValid() )
1612  {
1613  simpleMarker->setStrokeColor( strokeColor );
1614  simpleMarker->setStrokeStyle( Qt::SolidLine );
1615  }
1616 
1617  markerLayer = std::move( simpleMarker );
1618  }
1619 
1620  return std::make_unique< QgsMarkerSymbol >( QgsSymbolLayerList() << markerLayer.release() );
1621  };
1622 
1623  switch ( type )
1624  {
1626  if ( styles.contains( QStringLiteral( "symbol" ) ) )
1627  {
1628  const QVariantMap symbolStyle = styles.value( QStringLiteral( "symbol" ) ).toMap();
1629  return convertSymbol( symbolStyle );
1630  }
1631  else
1632  {
1633  return nullptr;
1634  }
1635 
1637  if ( styles.contains( QStringLiteral( "pen" ) ) )
1638  {
1639  // line symbol type
1640  const QVariantMap lineStyle = styles.value( QStringLiteral( "pen" ) ).toMap();
1641  return convertPen( lineStyle );
1642  }
1643  else
1644  {
1645  return nullptr;
1646  }
1647 
1649  {
1650  std::unique_ptr< QgsSymbol > fillSymbol = std::make_unique< QgsFillSymbol >();
1651  if ( styles.contains( QStringLiteral( "brush" ) ) )
1652  {
1653  const QVariantMap brushStyle = styles.value( QStringLiteral( "brush" ) ).toMap();
1654  fillSymbol = convertBrush( brushStyle );
1655  }
1656  else
1657  {
1658  std::unique_ptr< QgsSimpleFillSymbolLayer > emptyFill = std::make_unique< QgsSimpleFillSymbolLayer >();
1659  emptyFill->setBrushStyle( Qt::NoBrush );
1660  fillSymbol = std::make_unique< QgsFillSymbol >( QgsSymbolLayerList() << emptyFill.release() );
1661  }
1662 
1663  std::unique_ptr< QgsSymbol > penSymbol;
1664  if ( styles.contains( QStringLiteral( "pen" ) ) )
1665  {
1666  const QVariantMap lineStyle = styles.value( QStringLiteral( "pen" ) ).toMap();
1667  penSymbol = convertPen( lineStyle );
1668  }
1669 
1670  if ( penSymbol )
1671  {
1672  const int count = penSymbol->symbolLayerCount();
1673 
1674  if ( count == 1 )
1675  {
1676  // if only one pen symbol layer, let's try and combine it with the topmost brush layer, so that the resultant QGIS symbol is simpler
1677  if ( QgsSymbolLayerUtils::condenseFillAndOutline( dynamic_cast< QgsFillSymbolLayer * >( fillSymbol->symbolLayer( fillSymbol->symbolLayerCount() - 1 ) ),
1678  dynamic_cast< QgsLineSymbolLayer * >( penSymbol->symbolLayer( 0 ) ) ) )
1679  return fillSymbol;
1680  }
1681 
1682  for ( int i = 0; i < count; ++i )
1683  {
1684  std::unique_ptr< QgsSymbolLayer > layer( penSymbol->takeSymbolLayer( 0 ) );
1685  layer->setLocked( true );
1686  fillSymbol->appendSymbolLayer( layer.release() );
1687  }
1688  }
1689 
1690  return fillSymbol;
1691  }
1692 
1694  break;
1695  }
1696 
1697  return nullptr;
1698 }
SymbolType
Symbol types.
Definition: qgis.h:168
@ Marker
Marker symbol.
@ Line
Line symbol.
@ Fill
Fill symbol.
@ Hybrid
Hybrid symbol.
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 unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
Definition: qgsfeature.cpp:237
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
Definition: qgsfeature.cpp:210
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
Definition: qgsfeature.cpp:170
void setId(QgsFeatureId id)
Sets the feature id for this feature.
Definition: qgsfeature.cpp:115
void clearGeometry()
Removes any geometry associated with the feature.
Definition: qgsfeature.cpp:159
void setValid(bool validity)
Sets the validity of the feature.
Definition: qgsfeature.cpp:196
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:191
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:145
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
Returns the field at particular index (must be in range 0..N-1).
Definition: qgsfields.cpp:163
static bool fontFamilyMatchOnSystem(const QString &family, QString *chosen=nullptr, bool *match=nullptr)
Check whether font family is on system.
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.
Context for a MapInfo symbol conversion operation.
static QgsFillSymbol * convertFillSymbol(int identifier, QgsMapInfoSymbolConversionContext &context, const QColor &foreColor, const QColor &backColor=QColor())
Converts the MapInfo fill symbol with the specified identifier to a QgsFillSymbol.
static QgsLineSymbol * convertLineSymbol(int identifier, QgsMapInfoSymbolConversionContext &context, const QColor &foreColor, double size, QgsUnitTypes::RenderUnit sizeUnit, bool interleaved=false)
Converts the MapInfo line symbol with the specified identifier to a QgsLineSymbol.
static QgsMarkerSymbol * convertMarkerSymbol(int identifier, QgsMapInfoSymbolConversionContext &context, const QColor &color, double size, QgsUnitTypes::RenderUnit sizeUnit)
Converts the MapInfo marker symbol with the specified identifier to a QgsMarkerSymbol.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
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 QVariant OGRFieldtoVariant(const OGRField *value, OGRFieldType type)
Converts an OGRField value of the specified type into a QVariant.
static QgsFeature readOgrFeature(OGRFeatureH ogrFet, const QgsFields &fields, QTextCodec *encoding)
Reads an OGR feature and converts it to a QgsFeature.
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 std::unique_ptr< QgsSymbol > symbolFromStyleString(const QString &string, Qgis::SymbolType type)
Creates a new QgsSymbol matching an OGR style string.
static QVariantMap parseStyleString(const QString &string)
Parses an OGR style string to a variant map containing the style string components.
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 shapeIsFilled(QgsSimpleMarkerSymbolLayerBase::Shape shape)
Returns true if a symbol shape has a fill.
static bool condenseFillAndOutline(QgsFillSymbolLayer *fill, QgsLineSymbolLayer *outline)
Attempts to condense a fill and outline layer, by moving the outline layer to the fill symbol's strok...
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:168
@ RenderPoints
Points (e.g., for font sizes)
Definition: qgsunittypes.h:173
@ RenderInches
Inches.
Definition: qgsunittypes.h:174
@ RenderMillimeters
Millimeters.
Definition: qgsunittypes.h:169
@ RenderMapUnits
Map units.
Definition: qgsunittypes.h:170
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
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
Definition: MathUtils.cpp:786
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:78
std::unique_ptr< std::remove_pointer< OGRFeatureH >::type, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
Definition: qgsogrutils.h:131
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
Definition: qgsogrutils.h:136
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
Definition: qgsogrutils.h:116
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:1051
void * GDALDatasetH
void * OGRSpatialReferenceH
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:736
const QgsField & field
Definition: qgsfield.h:463
#define DEFAULT_SIMPLELINE_WIDTH
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
#define DEFAULT_SIMPLEMARKER_SIZE
std::unique_ptr< QgsLineString > ogrGeometryToQgsLineString(OGRGeometryH geom)
std::unique_ptr< QgsMultiLineString > ogrGeometryToQgsMultiLineString(OGRGeometryH geom)
std::unique_ptr< QgsMultiPoint > ogrGeometryToQgsMultiPoint(OGRGeometryH geom)
std::unique_ptr< QgsPolygon > ogrGeometryToQgsPolygon(OGRGeometryH geom)
std::unique_ptr< QgsPoint > ogrGeometryToQgsPoint(OGRGeometryH geom)
std::unique_ptr< QgsMultiPolygon > ogrGeometryToQgsMultiPolygon(OGRGeometryH geom)
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition: qgssymbol.h:27
void CORE_EXPORT operator()(GDALDatasetH datasource)
Destroys an gdal dataset, using the correct gdal calls.
Definition: qgsogrutils.cpp:73
void CORE_EXPORT operator()(GDALWarpOptions *options)
Destroys GDAL warp options, using the correct gdal calls.
Definition: qgsogrutils.cpp:98
void CORE_EXPORT operator()(OGRDataSourceH source)
Destroys an OGR data source, using the correct gdal calls.
Definition: qgsogrutils.cpp:52
void CORE_EXPORT operator()(OGRFeatureH feature)
Destroys an OGR feature, using the correct gdal calls.
Definition: qgsogrutils.cpp:68
void CORE_EXPORT operator()(OGRFieldDefnH definition)
Destroys an OGR field definition, using the correct gdal calls.
Definition: qgsogrutils.cpp:63
void CORE_EXPORT operator()(OGRGeometryH geometry)
Destroys an OGR geometry, using the correct gdal calls.
Definition: qgsogrutils.cpp:58