QGIS API Documentation  2.99.0-Master (c558d51)
qgsvectorfilewriter.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorfilewriter.h
3  generic vector file writer
4  -------------------
5  begin : Jun 6 2004
6  copyright : (C) 2004 by Tim Sutton
7  email : tim at linfiniti.com
8  ***************************************************************************/
9 
10 /***************************************************************************
11  * *
12  * This program is free software; you can redistribute it and/or modify *
13  * it under the terms of the GNU General Public License as published by *
14  * the Free Software Foundation; either version 2 of the License, or *
15  * (at your option) any later version. *
16  * *
17  ***************************************************************************/
18 
19 #ifndef QGSVECTORFILEWRITER_H
20 #define QGSVECTORFILEWRITER_H
21 
22 #include "qgsfields.h"
23 #include "qgssymbol.h"
24 #include <ogr_api.h>
25 
26 #include <QPair>
27 
28 
29 class QgsSymbolLayer;
30 class QTextCodec;
31 class QgsFeatureIterator;
32 
39 class CORE_EXPORT QgsVectorFileWriter
40 {
41  public:
43  {
44  Set,
46  Int,
47  Hidden
48  };
49 
52  class Option
53  {
54  public:
55  Option( const QString& docString, OptionType type )
56  : docString( docString )
57  , type( type ) {}
58  virtual ~Option() {}
59 
60  QString docString;
62  };
63 
66  class SetOption : public Option
67  {
68  public:
69  SetOption( const QString& docString, const QStringList& values, const QString& defaultValue, bool allowNone = false )
70  : Option( docString, Set )
71  , values( values.toSet() )
72  , defaultValue( defaultValue )
73  , allowNone( allowNone )
74  {}
75 
76  QSet<QString> values;
77  QString defaultValue;
78  bool allowNone;
79  };
80 
83  class StringOption: public Option
84  {
85  public:
86  StringOption( const QString& docString, const QString& defaultValue = QString() )
87  : Option( docString, String )
88  , defaultValue( defaultValue )
89  {}
90 
91  QString defaultValue;
92  };
93 
96  class IntOption: public Option
97  {
98  public:
99  IntOption( const QString& docString, int defaultValue )
100  : Option( docString, Int )
101  , defaultValue( defaultValue )
102  {}
103 
105  };
106 
109  class BoolOption : public SetOption
110  {
111  public:
112  BoolOption( const QString& docString, bool defaultValue )
113  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
114  {}
115  };
116 
119  class HiddenOption : public Option
120  {
121  public:
122  explicit HiddenOption( const QString& value )
123  : Option( QLatin1String( "" ), Hidden )
124  , mValue( value )
125  {}
126 
127  QString mValue;
128  };
129 
130  struct MetaData
131  {
133  {}
134 
135  MetaData( const QString& longName, const QString& trLongName, const QString& glob, const QString& ext, const QMap<QString, Option*>& driverOptions, const QMap<QString, Option*>& layerOptions, const QString& compulsoryEncoding = QString() )
136  : longName( longName )
137  , trLongName( trLongName )
138  , glob( glob )
139  , ext( ext )
140  , driverOptions( driverOptions )
141  , layerOptions( layerOptions )
142  , compulsoryEncoding( compulsoryEncoding )
143  {}
144 
145  QString longName;
146  QString trLongName;
147  QString glob;
148  QString ext;
149  QMap<QString, Option*> driverOptions;
150  QMap<QString, Option*> layerOptions;
153  };
154 
156  {
157  NoError = 0,
166  };
167 
169  {
170  NoSymbology = 0, //export only data
171  FeatureSymbology, //Keeps the number of features and export symbology per feature
172  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
173  };
174 
179  class CORE_EXPORT FieldValueConverter
180  {
181  public:
184 
186  virtual ~FieldValueConverter();
187 
192  virtual QgsField fieldDefinition( const QgsField& field );
193 
199  virtual QVariant convert( int fieldIdxInLayer, const QVariant& value );
200  };
201 
205  {
207  CanAddNewLayer = 1 << 0,
208 
210  CanAppendToExistingLayer = 1 << 1,
211 
213  CanAddNewFieldsToExistingLayer = 1 << 2,
214 
216  CanDeleteLayer = 1 << 3
217  };
218 
221  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
222 
223 
226  typedef enum
227  {
230 
233 
236 
238  AppendToLayerAddFields
240 
263  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
264  const QString& fileName,
265  const QString& fileEncoding,
267  const QString& driverName = "ESRI Shapefile",
268  bool onlySelected = false,
269  QString *errorMessage = nullptr,
270  const QStringList &datasourceOptions = QStringList(),
271  const QStringList &layerOptions = QStringList(),
272  bool skipAttributeCreation = false,
273  QString *newFilename = nullptr,
274  SymbologyExport symbologyExport = NoSymbology,
275  double symbologyScale = 1.0,
276  const QgsRectangle* filterExtent = nullptr,
277  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
278  bool forceMulti = false,
279  bool includeZ = false,
280  const QgsAttributeList &attributes = QgsAttributeList(),
281  FieldValueConverter* fieldValueConverter = nullptr
282  );
283 
308  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
309  const QString& fileName,
310  const QString& fileEncoding,
311  const QgsCoordinateTransform& ct,
312  const QString& driverName = "ESRI Shapefile",
313  bool onlySelected = false,
314  QString *errorMessage = nullptr,
315  const QStringList &datasourceOptions = QStringList(),
316  const QStringList &layerOptions = QStringList(),
317  bool skipAttributeCreation = false,
318  QString *newFilename = nullptr,
319  SymbologyExport symbologyExport = NoSymbology,
320  double symbologyScale = 1.0,
321  const QgsRectangle* filterExtent = nullptr,
322  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
323  bool forceMulti = false,
324  bool includeZ = false,
325  const QgsAttributeList &attributes = QgsAttributeList(),
326  FieldValueConverter* fieldValueConverter = nullptr
327  );
328 
329 
334  class CORE_EXPORT SaveVectorOptions
335  {
336  public:
339 
341  virtual ~SaveVectorOptions();
342 
344  QString driverName;
345 
347  QString layerName;
348 
350  ActionOnExistingFile actionOnExistingFile;
351 
353  QString fileEncoding;
354 
358 
361 
363  QStringList datasourceOptions;
364 
366  QStringList layerOptions;
367 
370 
373 
376 
379 
382 
386 
389 
391  bool includeZ;
392 
395  };
396 
405  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
406  const QString& fileName,
407  const SaveVectorOptions& options,
408  QString *newFilename = nullptr,
409  QString *errorMessage = nullptr );
410 
412  QgsVectorFileWriter( const QString& vectorFileName,
413  const QString& fileEncoding,
414  const QgsFields& fields,
415  QgsWkbTypes::Type geometryType,
417  const QString& driverName = "ESRI Shapefile",
418  const QStringList &datasourceOptions = QStringList(),
419  const QStringList &layerOptions = QStringList(),
420  QString *newFilename = nullptr,
421  SymbologyExport symbologyExport = NoSymbology
422  );
423 
425  static QMap< QString, QString> supportedFiltersAndFormats();
426 
431  static QMap< QString, QString> ogrDriverList();
432 
434  static QString fileFilterString();
435 
437  static QString filterForDriver( const QString& driverName );
438 
440  static QString convertCodecNameForEncodingOption( const QString &codecName );
441 
443  WriterError hasError();
444 
446  QString errorMessage();
447 
449  bool addFeature( QgsFeature& feature, QgsFeatureRenderer* renderer = nullptr, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
450 
452  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; }
453 
456 
461  static bool deleteShapeFile( const QString& theFileName );
462 
463  SymbologyExport symbologyExport() const { return mSymbologyExport; }
464  void setSymbologyExport( SymbologyExport symExport ) { mSymbologyExport = symExport; }
465 
466  double symbologyScaleDenominator() const { return mSymbologyScaleDenominator; }
467  void setSymbologyScaleDenominator( double d );
468 
469  static bool driverMetadata( const QString& driverName, MetaData& driverMetadata );
470 
476  static QStringList defaultDatasetOptions( const QString& driverName );
477 
483  static QStringList defaultLayerOptions( const QString& driverName );
484 
491  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type );
492 
497  static EditionCapabilities editionCapabilities( const QString& datasetName );
498 
503  static bool targetLayerExists( const QString& datasetName,
504  const QString& layerName );
505 
510  static bool areThereNewFieldsToCreate( const QString& datasetName,
511  const QString& layerName,
512  QgsVectorLayer* layer,
513  const QgsAttributeList& attributes );
514 
515  protected:
517  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType );
518 
519  OGRDataSourceH mDS;
520  OGRLayerH mLayer;
522  OGRGeometryH mGeom;
523 
525 
528  QString mErrorMessage;
529 
530  QTextCodec *mCodec;
531 
534 
536  QMap<int, int> mAttrIdxToOgrIdx;
537 
539 
540 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1700
541  QMap< QgsSymbolLayer*, QString > mSymbolLayerTable;
542 #endif
543 
546 
547  QString mOgrDriverName;
548 
551 
552  private:
553 
569  QgsVectorFileWriter( const QString& vectorFileName,
570  const QString& fileEncoding,
571  const QgsFields& fields,
572  QgsWkbTypes::Type geometryType,
573  const QgsCoordinateReferenceSystem& srs,
574  const QString& driverName,
575  const QStringList &datasourceOptions,
576  const QStringList &layerOptions,
577  QString *newFilename,
578  SymbologyExport symbologyExport,
579  FieldValueConverter* fieldValueConverter,
580  const QString& layerName,
581  ActionOnExistingFile action
582  );
583 
584  void init( QString vectorFileName, QString fileEncoding, const QgsFields& fields,
586  const QString& driverName, QStringList datasourceOptions,
587  QStringList layerOptions, QString* newFilename,
588  FieldValueConverter* fieldValueConverter,
589  const QString& layerName,
590  ActionOnExistingFile action );
591  void resetMap( const QgsAttributeList &attributes );
592 
593  QgsRenderContext mRenderContext;
594 
595  static QMap<QString, MetaData> initMetaData();
596  void createSymbolLayerTable( QgsVectorLayer* vl, const QgsCoordinateTransform& ct, OGRDataSourceH ds );
597  OGRFeatureH createFeature( const QgsFeature& feature );
598  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
599 
601  WriterError exportFeaturesSymbolLevels( QgsVectorLayer* layer, QgsFeatureIterator& fit, const QgsCoordinateTransform& ct, QString* errorMessage = nullptr );
602  double mmScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
603  double mapUnitScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
604 
605  void startRender( QgsVectorLayer* vl );
606  void stopRender( QgsVectorLayer* vl );
607  QgsFeatureRenderer* symbologyRenderer( QgsVectorLayer* vl ) const;
609  void addRendererAttributes( QgsVectorLayer* vl, QgsAttributeList& attList );
610  static QMap<QString, MetaData> sDriverMetadata;
611 
613  QgsVectorFileWriter& operator=( const QgsVectorFileWriter& rh );
614 
616  static QStringList concatenateOptions( const QMap<QString, Option*>& options );
617 };
618 
619 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
620 
621 #endif
Append features to existing layer, but do not create new fields.
Wrapper for iterator of features from vector data provider or vector layer.
BoolOption(const QString &docString, bool defaultValue)
A rectangle specified with double values.
Definition: qgsrectangle.h:35
SymbologyExport symbologyExport() const
QMap< int, int > attrIdxToOgrIdx()
SymbologyExport symbologyExport
Symbology to export.
WriterError mError
Contains error value if construction was not successful.
bool forceMulti
Set to true to force creation of multi* geometries.
SymbologyExport mSymbologyExport
double mSymbologyScaleDenominator
Scale for symbology export (e.g. for symbols units in map units)
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
QMap< QString, Option * > driverOptions
Container of fields for a vector layer.
Definition: qgsfields.h:36
MetaData(const QString &longName, const QString &trLongName, const QString &glob, const QString &ext, const QMap< QString, Option * > &driverOptions, const QMap< QString, Option * > &layerOptions, const QString &compulsoryEncoding=QString())
StringOption(const QString &docString, const QString &defaultValue=QString())
QStringList layerOptions
List of OGR layer creation options.
A convenience class for writing vector files to disk.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:135
QgsWkbTypes::Type overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer. ...
bool onlySelectedFeatures
Write only selected features of layer.
IntOption(const QString &docString, int defaultValue)
Options to pass to writeAsVectorFormat()
QStringList datasourceOptions
List of OGR data source creation options.
SetOption(const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone=false)
FieldValueConverter * mFieldValueConverter
Field value converter.
QList< int > QgsAttributeList
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:47
FieldValueConverter * fieldValueConverter
Field value converter.
QMap< int, int > mAttrIdxToOgrIdx
Map attribute indizes to OGR field indexes.
QgsRectangle filterExtent
If not empty, only features intersecting the extent will be saved.
OGRSpatialReferenceH mOgrRef
double symbologyScaleDenominator() const
QMap< QString, Option * > layerOptions
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:42
QString compulsoryEncoding
Some formats require a compulsory encoding, typically UTF-8. If no compulsory encoding, empty string.
void setSymbologyExport(SymbologyExport symExport)
Contains information about the context of a rendering operation.
bool skipAttributeCreation
Only write geometries.
double symbologyScale
Scale of symbology.
EditionCapability
Edition capability flags.
This class represents a coordinate reference system (CRS).
Option(const QString &docString, OptionType type)
Class for doing transforms between two map coordinate systems.
ActionOnExistingFile actionOnExistingFile
Action on existing file.
QgsCoordinateTransform ct
Transform to reproject exported geometries with, or invalid transform for no transformation.
Interface to convert raw field values to their user-friendly value.
bool includeZ
Set to true to include z dimension in output. This option is only valid if overrideGeometryType is se...
QString layerName
Layer name. If let empty, it will be derived from the filename.
Represents a vector layer which manages a vector based data sets.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:91
void * OGRSpatialReferenceH