QGIS API Documentation  2.99.0-Master (b95d432)
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, QgsVectorFileWriter::OptionType type )
61  : docString( docString )
62  , type( type ) {}
63  virtual ~Option() = default;
64 
65  QString docString;
67  };
68 
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 
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 
102  {
103  public:
104  IntOption( const QString &docString, int defaultValue )
105  : Option( docString, Int )
106  , defaultValue( defaultValue )
107  {}
108 
110  };
111 
115  {
116  public:
117  BoolOption( const QString &docString, bool defaultValue )
118  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
119  {}
120  };
121 
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, QgsVectorFileWriter::Option *> &driverOptions, const QMap<QString, QgsVectorFileWriter::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, QgsVectorFileWriter::Option *> driverOptions;
155  QMap<QString, QgsVectorFileWriter::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 
210  };
211 
215  {
217  CanAddNewLayer = 1 << 0,
218 
220  CanAppendToExistingLayer = 1 << 1,
221 
223  CanAddNewFieldsToExistingLayer = 1 << 2,
224 
226  CanDeleteLayer = 1 << 3
227  };
228 
231  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
232 
233 
237  {
240 
243 
246 
248  AppendToLayerAddFields
249  };
250 
273  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
274  const QString &fileName,
275  const QString &fileEncoding,
277  const QString &driverName = "ESRI Shapefile",
278  bool onlySelected = false,
279  QString *errorMessage = nullptr,
280  const QStringList &datasourceOptions = QStringList(),
281  const QStringList &layerOptions = QStringList(),
282  bool skipAttributeCreation = false,
283  QString *newFilename = nullptr,
285  double symbologyScale = 1.0,
286  const QgsRectangle *filterExtent = nullptr,
287  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
288  bool forceMulti = false,
289  bool includeZ = false,
290  const QgsAttributeList &attributes = QgsAttributeList(),
291  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
292  );
293 
318  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
319  const QString &fileName,
320  const QString &fileEncoding,
321  const QgsCoordinateTransform &ct,
322  const QString &driverName = "ESRI Shapefile",
323  bool onlySelected = false,
324  QString *errorMessage = nullptr,
325  const QStringList &datasourceOptions = QStringList(),
326  const QStringList &layerOptions = QStringList(),
327  bool skipAttributeCreation = false,
328  QString *newFilename = nullptr,
330  double symbologyScale = 1.0,
331  const QgsRectangle *filterExtent = nullptr,
332  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
333  bool forceMulti = false,
334  bool includeZ = false,
335  const QgsAttributeList &attributes = QgsAttributeList(),
336  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
337  );
338 
339 
344  class CORE_EXPORT SaveVectorOptions
345  {
346  public:
349 
350  virtual ~SaveVectorOptions() = default;
351 
353  QString driverName;
354 
356  QString layerName;
357 
360 
362  QString fileEncoding;
363 
367 
370 
372  QStringList datasourceOptions;
373 
375  QStringList layerOptions;
376 
379 
382 
385 
388 
391 
395 
398 
400  bool includeZ;
401 
408  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
409 
411  QgsFeedback *feedback = nullptr;
412  };
413 
422  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
423  const QString &fileName,
425  QString *newFilename = nullptr,
426  QString *errorMessage = nullptr );
427 
429  QgsVectorFileWriter( const QString &vectorFileName,
430  const QString &fileEncoding,
431  const QgsFields &fields,
432  QgsWkbTypes::Type geometryType,
434  const QString &driverName = "ESRI Shapefile",
435  const QStringList &datasourceOptions = QStringList(),
436  const QStringList &layerOptions = QStringList(),
437  QString *newFilename = nullptr,
439  );
440 
457  QgsVectorFileWriter( const QString &vectorFileName,
458  const QString &fileEncoding,
459  const QgsFields &fields,
460  QgsWkbTypes::Type geometryType,
461  const QgsCoordinateReferenceSystem &srs,
462  const QString &driverName,
463  const QStringList &datasourceOptions,
464  const QStringList &layerOptions,
465  QString *newFilename,
466  QgsVectorFileWriter::SymbologyExport symbologyExport,
467  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
468  const QString &layerName,
470  ) SIP_SKIP;
471 
473  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
475  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
476 
481  static QMap< QString, QString> supportedFiltersAndFormats();
482 
488  static QStringList supportedFormatExtensions();
489 
494  static QMap< QString, QString> ogrDriverList();
495 
502  static QString driverForExtension( const QString &extension );
503 
505  static QString fileFilterString();
506 
508  static QString filterForDriver( const QString &driverName );
509 
511  static QString convertCodecNameForEncodingOption( const QString &codecName );
512 
515 
517  QString errorMessage();
518 
519  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = 0 ) override;
520  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = 0 ) override;
521 
526  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
527 
529  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
530 
533 
538  static bool deleteShapeFile( const QString &fileName );
539 
540  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
541  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
542 
549  double symbologyScale() const { return mSymbologyScale; }
550 
557  void setSymbologyScale( double scale );
558 
559  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
560 
566  static QStringList defaultDatasetOptions( const QString &driverName );
567 
573  static QStringList defaultLayerOptions( const QString &driverName );
574 
581  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
582 
587  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
588 
593  static bool targetLayerExists( const QString &datasetName,
594  const QString &layerName );
595 
600  static bool areThereNewFieldsToCreate( const QString &datasetName,
601  const QString &layerName,
602  QgsVectorLayer *layer,
603  const QgsAttributeList &attributes );
604 
605  protected:
607  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
608 
609  OGRDataSourceH mDS;
610  OGRLayerH mLayer;
612 
614 
617  QString mErrorMessage;
618 
619  QTextCodec *mCodec = nullptr;
620 
623 
625  QMap<int, int> mAttrIdxToOgrIdx;
626 
628 
629  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
630 
633 
634  QString mOgrDriverName;
635 
637  FieldValueConverter *mFieldValueConverter = nullptr;
638 
639  private:
640 #ifdef SIP_RUN
642 #endif
643 
644  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
646  const QString &driverName, QStringList datasourceOptions,
647  QStringList layerOptions, QString *newFilename,
648  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
649  const QString &layerName,
651  void resetMap( const QgsAttributeList &attributes );
652 
653  QgsRenderContext mRenderContext;
654 
655  static QMap<QString, MetaData> initMetaData();
656  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
657  OGRFeatureH createFeature( const QgsFeature &feature );
658  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
659 
661  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( QgsVectorLayer *layer, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
662  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
663  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
664 
665  void startRender( QgsVectorLayer *vl );
666  void stopRender( QgsVectorLayer *vl );
667  QgsFeatureRenderer *symbologyRenderer( QgsVectorLayer *vl ) const;
669  void addRendererAttributes( QgsVectorLayer *vl, QgsAttributeList &attList );
670  static QMap<QString, MetaData> sDriverMetadata;
671 
673  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
674 };
675 
676 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
677 
678 
679 #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)
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
A rectangle specified with double values.
Definition: qgsrectangle.h:38
QgsVectorFileWriter::OptionType type
void setSymbologyExport(QgsVectorFileWriter::SymbologyExport symExport)
QMap< int, int > attrIdxToOgrIdx()
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
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
An interface for objects which accept features via addFeature(s) methods.
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
Container of fields for a vector layer.
Definition: qgsfields.h:41
StringOption(const QString &docString, const QString &defaultValue=QString())
MetaData(const QString &longName, const QString &trLongName, const QString &glob, const QString &ext, const QMap< QString, QgsVectorFileWriter::Option *> &driverOptions, const QMap< QString, QgsVectorFileWriter::Option *> &layerOptions, const QString &compulsoryEncoding=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
QgsWkbTypes::Type overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer. ...
QgsVectorFileWriter::SymbologyExport symbologyExport
Symbology to export.
QgsVectorFileWriter::SymbologyExport symbologyExport() const
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:43
bool onlySelectedFeatures
Write only selected features of layer.
IntOption(const QString &docString, int defaultValue)
Options to pass to writeAsVectorFormat()
Option(const QString &docString, QgsVectorFileWriter::OptionType type)
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:66
#define SIP_SKIP
Definition: qgis_sip.h:119
QStringList datasourceOptions
List of OGR data source creation options.
SetOption(const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone=false)
QMap< QString, QgsVectorFileWriter::Option * > layerOptions
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
#define SIP_FACTORY
Definition: qgis_sip.h:69
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:46
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 symbologyScale() const
Returns the reference scale for output.
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.
Contains information about the context of a rendering operation.
bool skipAttributeCreation
Only write geometries.
double symbologyScale
Scale of symbology.
EditionCapability
Edition capability flags.
double mSymbologyScale
Scale for symbology export (e.g. for symbols units in map units)
This class represents a coordinate reference system (CRS).
QMap< QString, QgsVectorFileWriter::Option * > driverOptions
Class for doing transforms between two map coordinate systems.
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:27
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.
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