QGIS API Documentation  2.99.0-Master (d55fa22)
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 "qgis_core.h"
23 #include "qgis_sip.h"
24 #include "qgsfields.h"
25 #include "qgsfeedback.h"
26 #include "qgssymbol.h"
27 #include "qgstaskmanager.h"
28 #include "qgsvectorlayer.h"
29 #include <ogr_api.h>
30 
31 #include <QPair>
32 
33 
34 class QgsSymbolLayer;
35 class QTextCodec;
36 class QgsFeatureIterator;
37 
44 class CORE_EXPORT QgsVectorFileWriter : public QgsFeatureSink
45 {
46  public:
48  {
49  Set,
51  Int,
52  Hidden
53  };
54 
57  class Option
58  {
59  public:
60  Option( const QString &docString, OptionType type )
61  : docString( docString )
62  , type( type ) {}
63  virtual ~Option() = default;
64 
65  QString docString;
67  };
68 
71  class SetOption : public Option
72  {
73  public:
74  SetOption( const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone = false )
75  : Option( docString, Set )
76  , values( values.toSet() )
77  , defaultValue( defaultValue )
78  , allowNone( allowNone )
79  {}
80 
81  QSet<QString> values;
82  QString defaultValue;
83  bool allowNone;
84  };
85 
88  class StringOption: public Option
89  {
90  public:
91  StringOption( const QString &docString, const QString &defaultValue = QString() )
92  : Option( docString, String )
93  , defaultValue( defaultValue )
94  {}
95 
96  QString defaultValue;
97  };
98 
101  class IntOption: public Option
102  {
103  public:
104  IntOption( const QString &docString, int defaultValue )
105  : Option( docString, Int )
106  , defaultValue( defaultValue )
107  {}
108 
110  };
111 
114  class BoolOption : public SetOption
115  {
116  public:
117  BoolOption( const QString &docString, bool defaultValue )
118  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
119  {}
120  };
121 
124  class HiddenOption : public Option
125  {
126  public:
127  explicit HiddenOption( const QString &value )
128  : Option( QLatin1String( "" ), Hidden )
129  , mValue( value )
130  {}
131 
132  QString mValue;
133  };
134 
135  struct MetaData
136  {
138  {}
139 
140  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() )
141  : longName( longName )
142  , trLongName( trLongName )
143  , glob( glob )
144  , ext( ext )
145  , driverOptions( driverOptions )
146  , layerOptions( layerOptions )
147  , compulsoryEncoding( compulsoryEncoding )
148  {}
149 
150  QString longName;
151  QString trLongName;
152  QString glob;
153  QString ext;
154  QMap<QString, Option *> driverOptions;
155  QMap<QString, Option *> layerOptions;
158  };
159 
161  {
162  NoError = 0,
172  };
173 
175  {
176  NoSymbology = 0, //export only data
177  FeatureSymbology, //Keeps the number of features and export symbology per feature
178  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
179  };
180 
185  class CORE_EXPORT FieldValueConverter
186  {
187  public:
190 
191  virtual ~FieldValueConverter() = default;
192 
197  virtual QgsField fieldDefinition( const QgsField &field );
198 
204  virtual QVariant convert( int fieldIdxInLayer, const QVariant &value );
205  };
206 
210  {
212  CanAddNewLayer = 1 << 0,
213 
215  CanAppendToExistingLayer = 1 << 1,
216 
218  CanAddNewFieldsToExistingLayer = 1 << 2,
219 
221  CanDeleteLayer = 1 << 3
222  };
223 
226  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
227 
228 
231  typedef enum
232  {
235 
238 
241 
243  AppendToLayerAddFields
245 
268  static WriterError writeAsVectorFormat( QgsVectorLayer *layer,
269  const QString &fileName,
270  const QString &fileEncoding,
272  const QString &driverName = "ESRI Shapefile",
273  bool onlySelected = false,
274  QString *errorMessage = nullptr,
275  const QStringList &datasourceOptions = QStringList(),
276  const QStringList &layerOptions = QStringList(),
277  bool skipAttributeCreation = false,
278  QString *newFilename = nullptr,
279  SymbologyExport symbologyExport = NoSymbology,
280  double symbologyScale = 1.0,
281  const QgsRectangle *filterExtent = nullptr,
282  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
283  bool forceMulti = false,
284  bool includeZ = false,
285  const QgsAttributeList &attributes = QgsAttributeList(),
286  FieldValueConverter *fieldValueConverter = nullptr
287  );
288 
313  static WriterError writeAsVectorFormat( QgsVectorLayer *layer,
314  const QString &fileName,
315  const QString &fileEncoding,
316  const QgsCoordinateTransform &ct,
317  const QString &driverName = "ESRI Shapefile",
318  bool onlySelected = false,
319  QString *errorMessage = nullptr,
320  const QStringList &datasourceOptions = QStringList(),
321  const QStringList &layerOptions = QStringList(),
322  bool skipAttributeCreation = false,
323  QString *newFilename = nullptr,
324  SymbologyExport symbologyExport = NoSymbology,
325  double symbologyScale = 1.0,
326  const QgsRectangle *filterExtent = nullptr,
327  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
328  bool forceMulti = false,
329  bool includeZ = false,
330  const QgsAttributeList &attributes = QgsAttributeList(),
331  FieldValueConverter *fieldValueConverter = nullptr
332  );
333 
334 
339  class CORE_EXPORT SaveVectorOptions
340  {
341  public:
344 
345  virtual ~SaveVectorOptions() = default;
346 
348  QString driverName;
349 
351  QString layerName;
352 
354  ActionOnExistingFile actionOnExistingFile;
355 
357  QString fileEncoding;
358 
362 
365 
367  QStringList datasourceOptions;
368 
370  QStringList layerOptions;
371 
374 
377 
380 
383 
386 
390 
393 
395  bool includeZ;
396 
398  FieldValueConverter *fieldValueConverter = nullptr;
399 
401  QgsFeedback *feedback = nullptr;
402  };
403 
412  static WriterError writeAsVectorFormat( QgsVectorLayer *layer,
413  const QString &fileName,
414  const SaveVectorOptions &options,
415  QString *newFilename = nullptr,
416  QString *errorMessage = nullptr );
417 
419  QgsVectorFileWriter( const QString &vectorFileName,
420  const QString &fileEncoding,
421  const QgsFields &fields,
422  QgsWkbTypes::Type geometryType,
424  const QString &driverName = "ESRI Shapefile",
425  const QStringList &datasourceOptions = QStringList(),
426  const QStringList &layerOptions = QStringList(),
427  QString *newFilename = nullptr,
428  SymbologyExport symbologyExport = NoSymbology
429  );
430 
447  QgsVectorFileWriter( const QString &vectorFileName,
448  const QString &fileEncoding,
449  const QgsFields &fields,
450  QgsWkbTypes::Type geometryType,
451  const QgsCoordinateReferenceSystem &srs,
452  const QString &driverName,
453  const QStringList &datasourceOptions,
454  const QStringList &layerOptions,
455  QString *newFilename,
456  SymbologyExport symbologyExport,
457  FieldValueConverter *fieldValueConverter,
458  const QString &layerName,
459  ActionOnExistingFile action
460  ) SIP_SKIP;
461 
463  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
465  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
466 
471  static QMap< QString, QString> supportedFiltersAndFormats();
472 
478  static QStringList supportedFormatExtensions();
479 
484  static QMap< QString, QString> ogrDriverList();
485 
492  static QString driverForExtension( const QString &extension );
493 
495  static QString fileFilterString();
496 
498  static QString filterForDriver( const QString &driverName );
499 
501  static QString convertCodecNameForEncodingOption( const QString &codecName );
502 
504  WriterError hasError();
505 
507  QString errorMessage();
508 
509  bool addFeature( QgsFeature &feature ) override;
510  bool addFeatures( QgsFeatureList &features ) override;
511 
513  bool addFeature( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
514 
516  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
517 
520 
525  static bool deleteShapeFile( const QString &fileName );
526 
527  SymbologyExport symbologyExport() const { return mSymbologyExport; }
528  void setSymbologyExport( SymbologyExport symExport ) { mSymbologyExport = symExport; }
529 
530  double symbologyScaleDenominator() const { return mSymbologyScaleDenominator; }
531  void setSymbologyScaleDenominator( double d );
532 
533  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
534 
540  static QStringList defaultDatasetOptions( const QString &driverName );
541 
547  static QStringList defaultLayerOptions( const QString &driverName );
548 
555  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
556 
561  static EditionCapabilities editionCapabilities( const QString &datasetName );
562 
567  static bool targetLayerExists( const QString &datasetName,
568  const QString &layerName );
569 
574  static bool areThereNewFieldsToCreate( const QString &datasetName,
575  const QString &layerName,
576  QgsVectorLayer *layer,
577  const QgsAttributeList &attributes );
578 
579  protected:
581  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
582 
583  OGRDataSourceH mDS;
584  OGRLayerH mLayer;
586 
588 
591  QString mErrorMessage;
592 
593  QTextCodec *mCodec = nullptr;
594 
597 
599  QMap<int, int> mAttrIdxToOgrIdx;
600 
602 
603  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
604 
607 
608  QString mOgrDriverName;
609 
611  FieldValueConverter *mFieldValueConverter = nullptr;
612 
613  private:
614 
615  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
617  const QString &driverName, QStringList datasourceOptions,
618  QStringList layerOptions, QString *newFilename,
619  FieldValueConverter *fieldValueConverter,
620  const QString &layerName,
621  ActionOnExistingFile action );
622  void resetMap( const QgsAttributeList &attributes );
623 
624  QgsRenderContext mRenderContext;
625 
626  static QMap<QString, MetaData> initMetaData();
627  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
628  OGRFeatureH createFeature( const QgsFeature &feature );
629  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
630 
632  WriterError exportFeaturesSymbolLevels( QgsVectorLayer *layer, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
633  double mmScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
634  double mapUnitScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
635 
636  void startRender( QgsVectorLayer *vl );
637  void stopRender( QgsVectorLayer *vl );
638  QgsFeatureRenderer *symbologyRenderer( QgsVectorLayer *vl ) const;
640  void addRendererAttributes( QgsVectorLayer *vl, QgsAttributeList &attList );
641  static QMap<QString, MetaData> sDriverMetadata;
642 
644  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
645 };
646 
647 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
648 
649 
650 #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:38
QMap< QString, Option * > driverOptions
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.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:524
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)
An interface for objects which accept features via addFeature(s) methods.
double symbologyScaleDenominator() const
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
Container of fields for a vector layer.
Definition: qgsfields.h:41
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:61
QMap< QString, Option * > layerOptions
QgsWkbTypes::Type overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer. ...
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:43
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())
bool onlySelectedFeatures
Write only selected features of layer.
IntOption(const QString &docString, int defaultValue)
Options to pass to writeAsVectorFormat()
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:66
#define SIP_SKIP
Definition: qgis_sip.h:87
QStringList datasourceOptions
List of OGR data source creation options.
SetOption(const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone=false)
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:48
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
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...
QList< int > QgsAttributeList
Definition: qgsfield.h:28
QString layerName
Layer name. If let empty, it will be derived from the filename.
SymbologyExport symbologyExport() const
Represents a vector layer which manages a vector based data sets.
Writing was interrupted by manual cancelation.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:95
void * OGRSpatialReferenceH