QGIS API Documentation  3.2.0-Bonn (bc43194)
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 "qgsogrutils.h"
30 #include "qgsrenderer.h"
31 #include "qgsgeometryengine.h"
32 #include <ogr_api.h>
33 
34 class QgsSymbolLayer;
35 class QTextCodec;
36 class QgsFeatureIterator;
37 
45 class CORE_EXPORT QgsVectorFileWriter : public QgsFeatureSink
46 {
47  public:
49  {
50  Set,
52  Int,
53  Hidden
54  };
55 
59  class Option
60  {
61  public:
62  Option( const QString &docString, QgsVectorFileWriter::OptionType type )
63  : docString( docString )
64  , type( type ) {}
65  virtual ~Option() = default;
66 
67  QString docString;
69  };
70 
75  {
76  public:
77  SetOption( const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone = false )
78  : Option( docString, Set )
79  , values( values.toSet() )
80  , defaultValue( defaultValue )
81  , allowNone( allowNone )
82  {}
83 
84  QSet<QString> values;
85  QString defaultValue;
86  bool allowNone;
87  };
88 
93  {
94  public:
95  StringOption( const QString &docString, const QString &defaultValue = QString() )
96  : Option( docString, String )
97  , defaultValue( defaultValue )
98  {}
99 
100  QString defaultValue;
101  };
102 
107  {
108  public:
109  IntOption( const QString &docString, int defaultValue )
110  : Option( docString, Int )
111  , defaultValue( defaultValue )
112  {}
113 
115  };
116 
121  {
122  public:
123  BoolOption( const QString &docString, bool defaultValue )
124  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
125  {}
126  };
127 
132  {
133  public:
134  explicit HiddenOption( const QString &value )
135  : Option( QLatin1String( "" ), Hidden )
136  , mValue( value )
137  {}
138 
139  QString mValue;
140  };
141 
142  struct MetaData
143  {
145  MetaData() = default;
146 
147  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() )
148  : longName( longName )
149  , trLongName( trLongName )
150  , glob( glob )
151  , ext( ext )
152  , driverOptions( driverOptions )
153  , layerOptions( layerOptions )
154  , compulsoryEncoding( compulsoryEncoding )
155  {}
156 
157  QString longName;
158  QString trLongName;
159  QString glob;
160  QString ext;
161  QMap<QString, QgsVectorFileWriter::Option *> driverOptions;
162  QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
165  };
166 
168  {
169  NoError = 0,
179  };
180 
182  {
183  NoSymbology = 0, //export only data
184  FeatureSymbology, //Keeps the number of features and export symbology per feature
185  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
186  };
187 
188 
194  {
195  SortRecommended = 1 << 1,
196  SkipNonSpatialFormats = 1 << 2,
197  };
198  Q_DECLARE_FLAGS( VectorFormatOptions, VectorFormatOption )
199 
200 
205  class CORE_EXPORT FieldValueConverter
206  {
207  public:
209  FieldValueConverter() = default;
210 
211  virtual ~FieldValueConverter() = default;
212 
218  virtual QgsField fieldDefinition( const QgsField &field );
219 
226  virtual QVariant convert( int fieldIdxInLayer, const QVariant &value );
227 
232  };
233 
238  {
240  CanAddNewLayer = 1 << 0,
241 
243  CanAppendToExistingLayer = 1 << 1,
244 
246  CanAddNewFieldsToExistingLayer = 1 << 2,
247 
249  CanDeleteLayer = 1 << 3
250  };
251 
255  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
256 
257 
262  {
265 
268 
271 
273  AppendToLayerAddFields
274  };
275 
299  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
300  const QString &fileName,
301  const QString &fileEncoding,
303  const QString &driverName = "GPKG",
304  bool onlySelected = false,
305  QString *errorMessage SIP_OUT = nullptr,
306  const QStringList &datasourceOptions = QStringList(),
307  const QStringList &layerOptions = QStringList(),
308  bool skipAttributeCreation = false,
309  QString *newFilename = nullptr,
311  double symbologyScale = 1.0,
312  const QgsRectangle *filterExtent = nullptr,
313  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
314  bool forceMulti = false,
315  bool includeZ = false,
316  const QgsAttributeList &attributes = QgsAttributeList(),
317  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
318  );
319 
345  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
346  const QString &fileName,
347  const QString &fileEncoding,
348  const QgsCoordinateTransform &ct,
349  const QString &driverName = "GPKG",
350  bool onlySelected = false,
351  QString *errorMessage SIP_OUT = nullptr,
352  const QStringList &datasourceOptions = QStringList(),
353  const QStringList &layerOptions = QStringList(),
354  bool skipAttributeCreation = false,
355  QString *newFilename = nullptr,
357  double symbologyScale = 1.0,
358  const QgsRectangle *filterExtent = nullptr,
359  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
360  bool forceMulti = false,
361  bool includeZ = false,
362  const QgsAttributeList &attributes = QgsAttributeList(),
363  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
364  );
365 
366 
372  class CORE_EXPORT SaveVectorOptions
373  {
374  public:
377 
378  virtual ~SaveVectorOptions() = default;
379 
381  QString driverName;
382 
384  QString layerName;
385 
387  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
388 
390  QString fileEncoding;
391 
396 
398  bool onlySelectedFeatures = false;
399 
401  QStringList datasourceOptions;
402 
404  QStringList layerOptions;
405 
407  bool skipAttributeCreation = false;
408 
411 
413  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
414 
416  double symbologyScale = 1.0;
417 
420 
424  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
425 
427  bool forceMulti = false;
428 
430  bool includeZ = false;
431 
438  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
439 
441  QgsFeedback *feedback = nullptr;
442  };
443 
453  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
454  const QString &fileName,
456  QString *newFilename = nullptr,
457  QString *errorMessage SIP_OUT = nullptr );
458 
460  QgsVectorFileWriter( const QString &vectorFileName,
461  const QString &fileEncoding,
462  const QgsFields &fields,
463  QgsWkbTypes::Type geometryType,
465  const QString &driverName = "GPKG",
466  const QStringList &datasourceOptions = QStringList(),
467  const QStringList &layerOptions = QStringList(),
468  QString *newFilename = nullptr,
470  );
471 
489  QgsVectorFileWriter( const QString &vectorFileName,
490  const QString &fileEncoding,
491  const QgsFields &fields,
492  QgsWkbTypes::Type geometryType,
493  const QgsCoordinateReferenceSystem &srs,
494  const QString &driverName,
495  const QStringList &datasourceOptions,
496  const QStringList &layerOptions,
497  QString *newFilename,
498  QgsVectorFileWriter::SymbologyExport symbologyExport,
499  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
500  const QString &layerName,
502  ) SIP_SKIP;
503 
505  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
507  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
508 
514  {
516  QString driverName;
517 
519  QString filterString;
520 
525  QStringList globs;
526  };
527 
536  static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats( VectorFormatOptions options = SortRecommended );
537 
547  static QStringList supportedFormatExtensions( VectorFormatOptions options = SortRecommended );
548 
556  static bool supportsFeatureStyles( const QString &driverName );
557 
563  {
565  QString longName;
566 
568  QString driverName;
569  };
570 
582  static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList( VectorFormatOptions options = SortRecommended );
583 
590  static QString driverForExtension( const QString &extension );
591 
598  static QString fileFilterString( VectorFormatOptions options = SortRecommended );
599 
601  static QString filterForDriver( const QString &driverName );
602 
604  static QString convertCodecNameForEncodingOption( const QString &codecName );
605 
608 
610  QString errorMessage();
611 
612  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = nullptr ) override;
613  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = nullptr ) override;
614 
619  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
620 
622  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
623 
625  ~QgsVectorFileWriter() override;
626 
632  static bool deleteShapeFile( const QString &fileName );
633 
634  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
635  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
636 
643  double symbologyScale() const { return mSymbologyScale; }
644 
651  void setSymbologyScale( double scale );
652 
653  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
654 
661  static QStringList defaultDatasetOptions( const QString &driverName );
662 
669  static QStringList defaultLayerOptions( const QString &driverName );
670 
677  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
678 
683  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
684 
689  static bool targetLayerExists( const QString &datasetName,
690  const QString &layerName );
691 
696  static bool areThereNewFieldsToCreate( const QString &datasetName,
697  const QString &layerName,
698  QgsVectorLayer *layer,
699  const QgsAttributeList &attributes );
700 
701  protected:
703  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
704 
706  OGRLayerH mLayer = nullptr;
707  OGRSpatialReferenceH mOgrRef = nullptr;
708 
710 
713  QString mErrorMessage;
714 
715  QTextCodec *mCodec = nullptr;
716 
719 
721  QMap<int, int> mAttrIdxToOgrIdx;
722 
724 
725  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
726 
729 
730  QString mOgrDriverName;
731 
733  FieldValueConverter *mFieldValueConverter = nullptr;
734 
735  private:
736 #ifdef SIP_RUN
738 #endif
739 
740  struct PreparedWriterDetails
741  {
742  std::unique_ptr< QgsFeatureRenderer > renderer;
744  QgsWkbTypes::Type sourceWkbType = QgsWkbTypes::Unknown;
745  QgsFields sourceFields;
746  QString providerType;
747  long featureCount = 0;
748  QgsFeatureIds selectedFeatureIds;
749  QString dataSourceUri;
750  QString storageType;
751  QgsFeatureIterator geometryTypeScanIterator;
752  QgsExpressionContext expressionContext;
753  QSet< int > fieldsToConvertToInt;
754  QgsRenderContext renderContext;
755  bool shallTransform = false;
758  QgsAttributeList attributes;
759  QgsFields outputFields;
760  QgsFeatureIterator sourceFeatureIterator;
761  QgsGeometry filterRectGeometry;
762  std::unique_ptr< QgsGeometryEngine > filterRectEngine;
763  };
764 
769  static QgsVectorFileWriter::WriterError prepareWriteAsVectorFormat( QgsVectorLayer *layer,
771  PreparedWriterDetails &details );
772 
777  static QgsVectorFileWriter::WriterError writeAsVectorFormat( PreparedWriterDetails &details,
778  const QString &fileName,
780  QString *newFilename = nullptr,
781  QString *errorMessage SIP_OUT = nullptr );
782 
783  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
785  const QString &driverName, QStringList datasourceOptions,
786  QStringList layerOptions, QString *newFilename,
787  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
788  const QString &layerName,
790  void resetMap( const QgsAttributeList &attributes );
791 
792  std::unique_ptr< QgsFeatureRenderer > mRenderer;
793  QgsRenderContext mRenderContext;
794 
795  bool mUsingTransaction = false;
796 
797  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
798  gdal::ogr_feature_unique_ptr createFeature( const QgsFeature &feature );
799  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
800 
802  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
803  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
804  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
805 
806  void startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields );
807  void stopRender();
808  std::unique_ptr< QgsFeatureRenderer > createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const;
810  static void addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList );
811  static QMap<QString, MetaData> sDriverMetadata;
812 
814  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
815 
817 };
818 
819 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
820 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::VectorFormatOptions )
821 
822 // clazy:excludeall=qstring-allocations
823 
824 #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:40
QgsVectorFileWriter::OptionType type
Details of available driver formats.
void setSymbologyExport(QgsVectorFileWriter::SymbologyExport symExport)
QMap< int, int > attrIdxToOgrIdx()
QStringList globs
Matching glob patterns for format, e.g.
WriterError mError
Contains error value if construction was not successful.
Details of available filters and formats.
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeature.h:544
QString filterString
Filter string for file picker dialogs.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:549
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:42
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:104
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:62
gdal::ogr_datasource_unique_ptr mDS
QgsVectorFileWriter::SymbologyExport symbologyExport() const
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:44
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:67
std::unique_ptr< std::remove_pointer< OGRFeatureH >::type, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
Definition: qgsogrutils.h:129
#define SIP_SKIP
Definition: qgis_sip.h:119
QString driverName
Unique driver name.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
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: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.
double symbologyScale() const
Returns the reference scale for output.
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.
Contains information about the context of a rendering operation.
EditionCapability
Edition capability flags.
#define SIP_OUT
Definition: qgis_sip.h:51
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.
VectorFormatOption
Options for sorting and filtering vector formats.
Interface to convert raw field values to their user-friendly value.
QgsTask task which performs a QgsVectorFileWriter layer saving operation as a background task...
QList< int > QgsAttributeList
Definition: qgsfield.h:27
QString layerName
Layer name. If let empty, it will be derived from the filename.
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
Definition: qgsogrutils.h:114
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:100
QString longName
Descriptive, user friendly name for the driver.
void * OGRSpatialReferenceH