QGIS API Documentation  2.99.0-Master (5753576)
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 "qgsfields.h"
24 #include "qgssymbol.h"
25 #include <ogr_api.h>
26 
27 #include <QPair>
28 
29 
30 class QgsSymbolLayer;
31 class QTextCodec;
32 class QgsFeatureIterator;
33 
40 class CORE_EXPORT QgsVectorFileWriter
41 {
42  public:
44  {
45  Set,
47  Int,
48  Hidden
49  };
50 
53  class Option
54  {
55  public:
56  Option( const QString& docString, OptionType type )
57  : docString( docString )
58  , type( type ) {}
59  virtual ~Option() = default;
60 
61  QString docString;
63  };
64 
67  class SetOption : public Option
68  {
69  public:
70  SetOption( const QString& docString, const QStringList& values, const QString& defaultValue, bool allowNone = false )
71  : Option( docString, Set )
72  , values( values.toSet() )
73  , defaultValue( defaultValue )
74  , allowNone( allowNone )
75  {}
76 
77  QSet<QString> values;
78  QString defaultValue;
79  bool allowNone;
80  };
81 
84  class StringOption: public Option
85  {
86  public:
87  StringOption( const QString& docString, const QString& defaultValue = QString() )
88  : Option( docString, String )
89  , defaultValue( defaultValue )
90  {}
91 
92  QString defaultValue;
93  };
94 
97  class IntOption: public Option
98  {
99  public:
100  IntOption( const QString& docString, int defaultValue )
101  : Option( docString, Int )
102  , defaultValue( defaultValue )
103  {}
104 
106  };
107 
110  class BoolOption : public SetOption
111  {
112  public:
113  BoolOption( const QString& docString, bool defaultValue )
114  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
115  {}
116  };
117 
120  class HiddenOption : public Option
121  {
122  public:
123  explicit HiddenOption( const QString& value )
124  : Option( QLatin1String( "" ), Hidden )
125  , mValue( value )
126  {}
127 
128  QString mValue;
129  };
130 
131  struct MetaData
132  {
134  {}
135 
136  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() )
137  : longName( longName )
138  , trLongName( trLongName )
139  , glob( glob )
140  , ext( ext )
141  , driverOptions( driverOptions )
142  , layerOptions( layerOptions )
143  , compulsoryEncoding( compulsoryEncoding )
144  {}
145 
146  QString longName;
147  QString trLongName;
148  QString glob;
149  QString ext;
150  QMap<QString, Option*> driverOptions;
151  QMap<QString, Option*> layerOptions;
154  };
155 
157  {
158  NoError = 0,
167  };
168 
170  {
171  NoSymbology = 0, //export only data
172  FeatureSymbology, //Keeps the number of features and export symbology per feature
173  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
174  };
175 
180  class CORE_EXPORT FieldValueConverter
181  {
182  public:
185 
186  virtual ~FieldValueConverter() = default;
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 
340  virtual ~SaveVectorOptions() = default;
341 
343  QString driverName;
344 
346  QString layerName;
347 
349  ActionOnExistingFile actionOnExistingFile;
350 
352  QString fileEncoding;
353 
357 
360 
362  QStringList datasourceOptions;
363 
365  QStringList layerOptions;
366 
369 
372 
375 
378 
381 
385 
388 
390  bool includeZ;
391 
394  };
395 
404  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
405  const QString& fileName,
406  const SaveVectorOptions& options,
407  QString *newFilename = nullptr,
408  QString *errorMessage = nullptr );
409 
411  QgsVectorFileWriter( const QString& vectorFileName,
412  const QString& fileEncoding,
413  const QgsFields& fields,
414  QgsWkbTypes::Type geometryType,
416  const QString& driverName = "ESRI Shapefile",
417  const QStringList &datasourceOptions = QStringList(),
418  const QStringList &layerOptions = QStringList(),
419  QString *newFilename = nullptr,
420  SymbologyExport symbologyExport = NoSymbology
421  );
422 
424  QgsVectorFileWriter( const QgsVectorFileWriter& rh ) = delete;
426  QgsVectorFileWriter& operator=( const QgsVectorFileWriter& rh ) = delete;
427 
429  static QMap< QString, QString> supportedFiltersAndFormats();
430 
435  static QMap< QString, QString> ogrDriverList();
436 
438  static QString fileFilterString();
439 
441  static QString filterForDriver( const QString& driverName );
442 
444  static QString convertCodecNameForEncodingOption( const QString &codecName );
445 
447  WriterError hasError();
448 
450  QString errorMessage();
451 
453  bool addFeature( QgsFeature& feature, QgsFeatureRenderer* renderer = nullptr, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
454 
456  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; }
457 
460 
465  static bool deleteShapeFile( const QString& theFileName );
466 
467  SymbologyExport symbologyExport() const { return mSymbologyExport; }
468  void setSymbologyExport( SymbologyExport symExport ) { mSymbologyExport = symExport; }
469 
470  double symbologyScaleDenominator() const { return mSymbologyScaleDenominator; }
471  void setSymbologyScaleDenominator( double d );
472 
473  static bool driverMetadata( const QString& driverName, MetaData& driverMetadata );
474 
480  static QStringList defaultDatasetOptions( const QString& driverName );
481 
487  static QStringList defaultLayerOptions( const QString& driverName );
488 
495  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type );
496 
501  static EditionCapabilities editionCapabilities( const QString& datasetName );
502 
507  static bool targetLayerExists( const QString& datasetName,
508  const QString& layerName );
509 
514  static bool areThereNewFieldsToCreate( const QString& datasetName,
515  const QString& layerName,
516  QgsVectorLayer* layer,
517  const QgsAttributeList& attributes );
518 
519  protected:
521  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType );
522 
523  OGRDataSourceH mDS;
524  OGRLayerH mLayer;
526  OGRGeometryH mGeom;
527 
529 
532  QString mErrorMessage;
533 
534  QTextCodec *mCodec;
535 
538 
540  QMap<int, int> mAttrIdxToOgrIdx;
541 
543 
544  QMap< QgsSymbolLayer*, QString > mSymbolLayerTable;
545 
548 
549  QString mOgrDriverName;
550 
553 
554  private:
555 
571  QgsVectorFileWriter( const QString& vectorFileName,
572  const QString& fileEncoding,
573  const QgsFields& fields,
574  QgsWkbTypes::Type geometryType,
575  const QgsCoordinateReferenceSystem& srs,
576  const QString& driverName,
577  const QStringList &datasourceOptions,
578  const QStringList &layerOptions,
579  QString *newFilename,
580  SymbologyExport symbologyExport,
581  FieldValueConverter* fieldValueConverter,
582  const QString& layerName,
583  ActionOnExistingFile action
584  );
585 
586  void init( QString vectorFileName, QString fileEncoding, const QgsFields& fields,
588  const QString& driverName, QStringList datasourceOptions,
589  QStringList layerOptions, QString* newFilename,
590  FieldValueConverter* fieldValueConverter,
591  const QString& layerName,
592  ActionOnExistingFile action );
593  void resetMap( const QgsAttributeList &attributes );
594 
595  QgsRenderContext mRenderContext;
596 
597  static QMap<QString, MetaData> initMetaData();
598  void createSymbolLayerTable( QgsVectorLayer* vl, const QgsCoordinateTransform& ct, OGRDataSourceH ds );
599  OGRFeatureH createFeature( const QgsFeature& feature );
600  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
601 
603  WriterError exportFeaturesSymbolLevels( QgsVectorLayer* layer, QgsFeatureIterator& fit, const QgsCoordinateTransform& ct, QString* errorMessage = nullptr );
604  double mmScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
605  double mapUnitScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
606 
607  void startRender( QgsVectorLayer* vl );
608  void stopRender( QgsVectorLayer* vl );
609  QgsFeatureRenderer* symbologyRenderer( QgsVectorLayer* vl ) const;
611  void addRendererAttributes( QgsVectorLayer* vl, QgsAttributeList& attList );
612  static QMap<QString, MetaData> sDriverMetadata;
613 
615  static QStringList concatenateOptions( const QMap<QString, Option*>& options );
616 };
617 
618 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
619 
620 #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:36
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
double symbologyScaleDenominator() const
Container of fields for a vector layer.
Definition: qgsfields.h:39
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:136
QgsWkbTypes::Type overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer. ...
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:65
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:45
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
QMap< QString, Option * > layerOptions
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:43
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...
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
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.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:92
void * OGRSpatialReferenceH