QGIS API Documentation  2.99.0-Master (9ed189e)
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 "qgsfeedback.h"
25 #include "qgssymbol.h"
26 #include "qgstaskmanager.h"
27 #include "qgsvectorlayer.h"
28 #include <ogr_api.h>
29 
30 #include <QPair>
31 
32 
33 class QgsSymbolLayer;
34 class QTextCodec;
35 class QgsFeatureIterator;
36 
43 class CORE_EXPORT QgsVectorFileWriter
44 {
45  public:
47  {
48  Set,
50  Int,
51  Hidden
52  };
53 
56  class Option
57  {
58  public:
59  Option( const QString& docString, OptionType type )
60  : docString( docString )
61  , type( type ) {}
62  virtual ~Option() = default;
63 
64  QString docString;
66  };
67 
70  class SetOption : public Option
71  {
72  public:
73  SetOption( const QString& docString, const QStringList& values, const QString& defaultValue, bool allowNone = false )
74  : Option( docString, Set )
75  , values( values.toSet() )
76  , defaultValue( defaultValue )
77  , allowNone( allowNone )
78  {}
79 
80  QSet<QString> values;
81  QString defaultValue;
82  bool allowNone;
83  };
84 
87  class StringOption: public Option
88  {
89  public:
90  StringOption( const QString& docString, const QString& defaultValue = QString() )
91  : Option( docString, String )
92  , defaultValue( defaultValue )
93  {}
94 
95  QString defaultValue;
96  };
97 
100  class IntOption: public Option
101  {
102  public:
103  IntOption( const QString& docString, int defaultValue )
104  : Option( docString, Int )
105  , defaultValue( defaultValue )
106  {}
107 
109  };
110 
113  class BoolOption : public SetOption
114  {
115  public:
116  BoolOption( const QString& docString, bool defaultValue )
117  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
118  {}
119  };
120 
123  class HiddenOption : public Option
124  {
125  public:
126  explicit HiddenOption( const QString& value )
127  : Option( QLatin1String( "" ), Hidden )
128  , mValue( value )
129  {}
130 
131  QString mValue;
132  };
133 
134  struct MetaData
135  {
137  {}
138 
139  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() )
140  : longName( longName )
141  , trLongName( trLongName )
142  , glob( glob )
143  , ext( ext )
144  , driverOptions( driverOptions )
145  , layerOptions( layerOptions )
146  , compulsoryEncoding( compulsoryEncoding )
147  {}
148 
149  QString longName;
150  QString trLongName;
151  QString glob;
152  QString ext;
153  QMap<QString, Option*> driverOptions;
154  QMap<QString, Option*> layerOptions;
157  };
158 
160  {
161  NoError = 0,
171  };
172 
174  {
175  NoSymbology = 0, //export only data
176  FeatureSymbology, //Keeps the number of features and export symbology per feature
177  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
178  };
179 
184  class CORE_EXPORT FieldValueConverter
185  {
186  public:
189 
190  virtual ~FieldValueConverter() = default;
191 
196  virtual QgsField fieldDefinition( const QgsField& field );
197 
203  virtual QVariant convert( int fieldIdxInLayer, const QVariant& value );
204  };
205 
209  {
211  CanAddNewLayer = 1 << 0,
212 
214  CanAppendToExistingLayer = 1 << 1,
215 
217  CanAddNewFieldsToExistingLayer = 1 << 2,
218 
220  CanDeleteLayer = 1 << 3
221  };
222 
225  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
226 
227 
230  typedef enum
231  {
234 
237 
240 
242  AppendToLayerAddFields
244 
267  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
268  const QString& fileName,
269  const QString& fileEncoding,
271  const QString& driverName = "ESRI Shapefile",
272  bool onlySelected = false,
273  QString *errorMessage = nullptr,
274  const QStringList &datasourceOptions = QStringList(),
275  const QStringList &layerOptions = QStringList(),
276  bool skipAttributeCreation = false,
277  QString *newFilename = nullptr,
278  SymbologyExport symbologyExport = NoSymbology,
279  double symbologyScale = 1.0,
280  const QgsRectangle* filterExtent = nullptr,
281  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
282  bool forceMulti = false,
283  bool includeZ = false,
284  const QgsAttributeList &attributes = QgsAttributeList(),
285  FieldValueConverter* fieldValueConverter = nullptr
286  );
287 
312  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
313  const QString& fileName,
314  const QString& fileEncoding,
315  const QgsCoordinateTransform& ct,
316  const QString& driverName = "ESRI Shapefile",
317  bool onlySelected = false,
318  QString *errorMessage = nullptr,
319  const QStringList &datasourceOptions = QStringList(),
320  const QStringList &layerOptions = QStringList(),
321  bool skipAttributeCreation = false,
322  QString *newFilename = nullptr,
323  SymbologyExport symbologyExport = NoSymbology,
324  double symbologyScale = 1.0,
325  const QgsRectangle* filterExtent = nullptr,
326  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
327  bool forceMulti = false,
328  bool includeZ = false,
329  const QgsAttributeList &attributes = QgsAttributeList(),
330  FieldValueConverter* fieldValueConverter = nullptr
331  );
332 
333 
338  class CORE_EXPORT SaveVectorOptions
339  {
340  public:
343 
344  virtual ~SaveVectorOptions() = default;
345 
347  QString driverName;
348 
350  QString layerName;
351 
353  ActionOnExistingFile actionOnExistingFile;
354 
356  QString fileEncoding;
357 
361 
364 
366  QStringList datasourceOptions;
367 
369  QStringList layerOptions;
370 
373 
376 
379 
382 
385 
389 
392 
394  bool includeZ;
395 
397  FieldValueConverter* fieldValueConverter = nullptr;
398 
400  QgsFeedback* feedback = nullptr;
401  };
402 
411  static WriterError writeAsVectorFormat( QgsVectorLayer* layer,
412  const QString& fileName,
413  const SaveVectorOptions& options,
414  QString *newFilename = nullptr,
415  QString *errorMessage = nullptr );
416 
418  QgsVectorFileWriter( const QString& vectorFileName,
419  const QString& fileEncoding,
420  const QgsFields& fields,
421  QgsWkbTypes::Type geometryType,
423  const QString& driverName = "ESRI Shapefile",
424  const QStringList &datasourceOptions = QStringList(),
425  const QStringList &layerOptions = QStringList(),
426  QString *newFilename = nullptr,
427  SymbologyExport symbologyExport = NoSymbology
428  );
429 
431  QgsVectorFileWriter( const QgsVectorFileWriter& rh ) = delete;
433  QgsVectorFileWriter& operator=( const QgsVectorFileWriter& rh ) = delete;
434 
436  static QMap< QString, QString> supportedFiltersAndFormats();
437 
442  static QMap< QString, QString> ogrDriverList();
443 
445  static QString fileFilterString();
446 
448  static QString filterForDriver( const QString& driverName );
449 
451  static QString convertCodecNameForEncodingOption( const QString &codecName );
452 
454  WriterError hasError();
455 
457  QString errorMessage();
458 
460  bool addFeature( QgsFeature& feature, QgsFeatureRenderer* renderer = nullptr, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
461 
463  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; }
464 
467 
472  static bool deleteShapeFile( const QString& theFileName );
473 
474  SymbologyExport symbologyExport() const { return mSymbologyExport; }
475  void setSymbologyExport( SymbologyExport symExport ) { mSymbologyExport = symExport; }
476 
477  double symbologyScaleDenominator() const { return mSymbologyScaleDenominator; }
478  void setSymbologyScaleDenominator( double d );
479 
480  static bool driverMetadata( const QString& driverName, MetaData& driverMetadata );
481 
487  static QStringList defaultDatasetOptions( const QString& driverName );
488 
494  static QStringList defaultLayerOptions( const QString& driverName );
495 
502  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type );
503 
508  static EditionCapabilities editionCapabilities( const QString& datasetName );
509 
514  static bool targetLayerExists( const QString& datasetName,
515  const QString& layerName );
516 
521  static bool areThereNewFieldsToCreate( const QString& datasetName,
522  const QString& layerName,
523  QgsVectorLayer* layer,
524  const QgsAttributeList& attributes );
525 
526  protected:
528  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType );
529 
530  OGRDataSourceH mDS;
531  OGRLayerH mLayer;
533 
535 
538  QString mErrorMessage;
539 
540  QTextCodec *mCodec = nullptr;
541 
544 
546  QMap<int, int> mAttrIdxToOgrIdx;
547 
549 
550  QMap< QgsSymbolLayer*, QString > mSymbolLayerTable;
551 
554 
555  QString mOgrDriverName;
556 
558  FieldValueConverter* mFieldValueConverter = nullptr;
559 
560  private:
561 
577  QgsVectorFileWriter( const QString& vectorFileName,
578  const QString& fileEncoding,
579  const QgsFields& fields,
580  QgsWkbTypes::Type geometryType,
581  const QgsCoordinateReferenceSystem& srs,
582  const QString& driverName,
583  const QStringList &datasourceOptions,
584  const QStringList &layerOptions,
585  QString *newFilename,
586  SymbologyExport symbologyExport,
587  FieldValueConverter* fieldValueConverter,
588  const QString& layerName,
589  ActionOnExistingFile action
590  );
591 
592  void init( QString vectorFileName, QString fileEncoding, const QgsFields& fields,
594  const QString& driverName, QStringList datasourceOptions,
595  QStringList layerOptions, QString* newFilename,
596  FieldValueConverter* fieldValueConverter,
597  const QString& layerName,
598  ActionOnExistingFile action );
599  void resetMap( const QgsAttributeList &attributes );
600 
601  QgsRenderContext mRenderContext;
602 
603  static QMap<QString, MetaData> initMetaData();
604  void createSymbolLayerTable( QgsVectorLayer* vl, const QgsCoordinateTransform& ct, OGRDataSourceH ds );
605  OGRFeatureH createFeature( const QgsFeature& feature );
606  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
607 
609  WriterError exportFeaturesSymbolLevels( QgsVectorLayer* layer, QgsFeatureIterator& fit, const QgsCoordinateTransform& ct, QString* errorMessage = nullptr );
610  double mmScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
611  double mapUnitScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
612 
613  void startRender( QgsVectorLayer* vl );
614  void stopRender( QgsVectorLayer* vl );
615  QgsFeatureRenderer* symbologyRenderer( QgsVectorLayer* vl ) const;
617  void addRendererAttributes( QgsVectorLayer* vl, QgsAttributeList& attList );
618  static QMap<QString, MetaData> sDriverMetadata;
619 
621  static QStringList concatenateOptions( const QMap<QString, Option*>& options );
622 };
623 
624 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
625 
626 
627 #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. ...
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:42
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)
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
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.
Writing was interrupted by manual cancelation.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:92
void * OGRSpatialReferenceH