QGIS API Documentation 4.3.0-Master (16eddb2670e)
Loading...
Searching...
No Matches
qgsprofileexporter.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprofileexporter.cpp
3 ---------------
4 begin : May 2023
5 copyright : (C) 2023 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17#include "qgsprofileexporter.h"
18
21#include "qgsdxfexport.h"
23#include "qgsprofilerenderer.h"
24#include "qgsvectorfilewriter.h"
25#include "qgsvectorlayer.h"
26
27#include <QFileInfo>
28#include <QString>
29#include <QThread>
30
31#include "moc_qgsprofileexporter.cpp"
32
33using namespace Qt::StringLiterals;
34
35QgsProfileExporter::QgsProfileExporter( const QList<QgsAbstractProfileSource *> &sources, const QgsProfileRequest &request, Qgis::ProfileExportType type )
36 : mType( type )
37 , mRequest( request )
38{
39 for ( QgsAbstractProfileSource *source : sources )
40 {
41 if ( source )
42 {
43 if ( std::unique_ptr< QgsAbstractProfileGenerator > generator { source->createProfileGenerator( mRequest ) } )
44 mGenerators.emplace_back( std::move( generator ) );
45 }
46 }
47}
48
50
52{
53 if ( mGenerators.empty() )
54 return;
55
56 QgsProfilePlotRenderer renderer( std::move( mGenerators ), mRequest );
57 renderer.startGeneration();
58 renderer.waitForFinished();
59
60 mFeatures = renderer.asFeatures( mType, feedback );
61}
62
63QList< QgsVectorLayer *> QgsProfileExporter::toLayers()
64{
65 if ( mFeatures.empty() )
66 return {};
67
68 // collect all features with the same geometry types together
69 QHash< quint32, QVector< QgsAbstractProfileResults::Feature > > featuresByGeometryType;
70 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( mFeatures ) )
71 {
72 featuresByGeometryType[static_cast< quint32 >( feature.geometry.wkbType() )].append( feature );
73 }
74
75 // generate a new memory provider layer for each geometry type
76 QList< QgsVectorLayer * > res;
77 for ( auto wkbTypeIt = featuresByGeometryType.constBegin(); wkbTypeIt != featuresByGeometryType.constEnd(); ++wkbTypeIt )
78 {
79 // first collate a master list of fields for this geometry type
80 QgsFields outputFields;
81 outputFields.append( QgsField( u"layer"_s, QMetaType::Type::QString ) );
82
83 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( wkbTypeIt.value() ) )
84 {
85 for ( auto attributeIt = feature.attributes.constBegin(); attributeIt != feature.attributes.constEnd(); ++attributeIt )
86 {
87 const int existingFieldIndex = outputFields.lookupField( attributeIt.key() );
88 if ( existingFieldIndex < 0 )
89 {
90 outputFields.append( QgsField( attributeIt.key(), static_cast<QMetaType::Type>( attributeIt.value().userType() ) ) );
91 }
92 else
93 {
94 if ( outputFields.at( existingFieldIndex ).type() != QMetaType::Type::QString && outputFields.at( existingFieldIndex ).type() != attributeIt.value().userType() )
95 {
96 // attribute type mismatch across fields, just promote to string types to be flexible
97 outputFields[existingFieldIndex].setType( QMetaType::Type::QString );
98 }
99 }
100 }
101 }
102
103 // note -- 2d profiles have no CRS associated, the coordinate values are not location based!
104 std::unique_ptr< QgsVectorLayer > outputLayer(
106 createMemoryLayer( u"profile"_s, outputFields, static_cast< Qgis::WkbType >( wkbTypeIt.key() ), mType == Qgis::ProfileExportType::Profile2D ? QgsCoordinateReferenceSystem() : mRequest.crs(), false )
107 );
108
109 QList< QgsFeature > featuresToAdd;
110 featuresToAdd.reserve( wkbTypeIt.value().size() );
111 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( wkbTypeIt.value() ) )
112 {
113 QgsFeature out( outputFields );
114 out.setAttribute( 0, feature.layerIdentifier );
115 out.setGeometry( feature.geometry );
116 for ( auto attributeIt = feature.attributes.constBegin(); attributeIt != feature.attributes.constEnd(); ++attributeIt )
117 {
118 const int outputFieldIndex = outputFields.lookupField( attributeIt.key() );
119 const QgsField &targetField = outputFields.at( outputFieldIndex );
120 QVariant value = attributeIt.value();
121 targetField.convertCompatible( value );
122 out.setAttribute( outputFieldIndex, value );
123 }
124 featuresToAdd << out;
125 }
126
127 if ( !outputLayer->dataProvider()->addFeatures( featuresToAdd, QgsFeatureSink::FastInsert ) )
128 {
129 QgsDebugError( u"Error exporting feature: %1"_s.arg( outputLayer->dataProvider()->lastError() ) );
130 }
131 res << outputLayer.release();
132 }
133 return res;
134}
135
136//
137// QgsProfileExporterTask
138//
139
141 const QList<QgsAbstractProfileSource *> &sources, const QgsProfileRequest &request, Qgis::ProfileExportType type, const QString &destination, const QgsCoordinateTransformContext &transformContext
142)
143 : QgsTask( tr( "Exporting elevation profile" ), QgsTask::CanCancel )
144 , mDestination( destination )
145 , mTransformContext( transformContext )
146{
147 mExporter = std::make_unique< QgsProfileExporter >( sources, request, type );
148}
149
151{
152 mFeedback = std::make_unique< QgsFeedback >();
153
154 mExporter->run( mFeedback.get() );
155
156 mLayers = mExporter->toLayers();
157
158 if ( mFeedback->isCanceled() )
159 {
160 mResult = ExportResult::Canceled;
161 return true;
162 }
163
164 if ( !mDestination.isEmpty() && !mLayers.empty() )
165 {
166 const QFileInfo destinationFileInfo( mDestination );
167 const QString fileExtension = destinationFileInfo.completeSuffix();
168 const QString driverName = QgsVectorFileWriter::driverForExtension( fileExtension );
169
170 if ( driverName == "DXF"_L1 )
171 {
172 // DXF gets special handling -- we use the inbuilt QgsDxfExport class
173 QgsDxfExport dxf;
174 QList< QgsDxfExport::DxfLayer > dxfLayers;
175 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
176 {
177 QgsDxfExport::DxfLayer dxfLayer( layer );
178 dxfLayers.append( dxfLayer );
179 if ( layer->crs().isValid() )
180 dxf.setDestinationCrs( layer->crs() );
181 }
182 dxf.addLayers( dxfLayers );
183 QFile dxfFile( mDestination );
184 switch ( dxf.writeToFile( &dxfFile, u"UTF-8"_s ) )
185 {
187 mResult = ExportResult::Success;
188 mCreatedFiles.append( mDestination );
189 break;
190
194 break;
195
199 break;
200 }
201 }
202 else
203 {
204 // use vector file writer
205 const bool outputFormatIsMultiLayer = QgsVectorFileWriter::supportedFormatExtensions( QgsVectorFileWriter::SupportsMultipleLayers ).contains( fileExtension );
206
207 int layerCount = 1;
208 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
209 {
210 QString thisLayerFilename;
212 if ( outputFormatIsMultiLayer )
213 {
214 thisLayerFilename = mDestination;
216 if ( mLayers.size() > 1 )
217 options.layerName = u"profile_%1"_s.arg( layerCount );
218 }
219 else
220 {
222 if ( mLayers.size() > 1 )
223 {
224 thisLayerFilename = u"%1/%2_%3.%4"_s.arg( destinationFileInfo.path(), destinationFileInfo.baseName() ).arg( layerCount ).arg( fileExtension );
225 }
226 else
227 {
228 thisLayerFilename = mDestination;
229 }
230 }
231 options.driverName = driverName;
232 options.feedback = mFeedback.get();
233 options.fileEncoding = u"UTF-8"_s;
234 QString newFileName;
235 QgsVectorFileWriter::WriterError result = QgsVectorFileWriter::writeAsVectorFormatV3( layer, thisLayerFilename, mTransformContext, options, &mError, &newFileName );
236 switch ( result )
237 {
239 mResult = ExportResult::Success;
240 if ( !mCreatedFiles.contains( newFileName ) )
241 mCreatedFiles.append( newFileName );
242 break;
243
248 break;
249
257 break;
258
259
261 mResult = ExportResult::Canceled;
262 break;
263 }
264
265 if ( mResult != ExportResult::Success )
266 break;
267 layerCount += 1;
268 }
269 }
270 }
271 else if ( mLayers.empty() )
272 {
273 mResult = ExportResult::Empty;
274 }
275
276 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
277 {
278 layer->moveToThread( nullptr );
279 }
280
281 mExporter.reset();
282 return true;
283}
284
286{
287 if ( mFeedback )
288 mFeedback->cancel();
289
291}
292
293QList<QgsVectorLayer *> QgsProfileExporterTask::takeLayers()
294{
295 QList<QgsVectorLayer *> res;
296 res.reserve( mLayers.size() );
297 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
298 {
299 layer->moveToThread( QThread::currentThread() );
300 res.append( layer );
301 }
302 mLayers.clear();
303 return res;
304}
305
ProfileExportType
Types of export for elevation profiles.
Definition qgis.h:4702
@ Profile2D
Export profiles as 2D profile lines, with elevation stored in exported geometry Y dimension and dista...
Definition qgis.h:4704
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:314
Interface for classes which can generate elevation profiles.
Represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
Exports QGIS layers to the DXF format.
@ InvalidEncodingError
The requested text encoding is not supported.
@ DeviceNotWritableError
Device not writable error.
@ Success
Successful export.
@ EmptyExtentError
Empty extent, no extent given and no extent could be derived from layers.
@ InvalidDeviceError
Invalid device error.
ExportResult writeToFile(QIODevice *d, const QString &codec)
Export to a dxf file in the given encoding.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Set destination CRS.
void addLayers(const QList< QgsDxfExport::DxfLayer > &layers)
Add layers to export.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
QMetaType::Type type
Definition qgsfield.h:63
bool convertCompatible(QVariant &v, QString *errorMessage=nullptr) const
Converts the provided variant to a compatible format.
Definition qgsfield.cpp:485
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Utility functions for use with the memory vector data provider.
ExportResult
Results of exporting the profile.
@ LayerExportFailed
Generic error when outputting to files.
@ DxfExportFailed
Generic error when outputting to DXF.
@ DeviceError
Could not open output file device.
QgsProfileExporterTask(const QList< QgsAbstractProfileSource * > &sources, const QgsProfileRequest &request, Qgis::ProfileExportType type, const QString &destination, const QgsCoordinateTransformContext &transformContext)
Constructor for QgsProfileExporterTask, saving results to the specified destination file.
bool run() override
Performs the task's operation.
QgsProfileExporterTask::ExportResult result() const
Returns the result of the export operation.
void cancel() override
Notifies the task that it should terminate.
QList< QgsVectorLayer * > takeLayers()
Returns a list of vector layer containing the exported profile results.
void run(QgsFeedback *feedback=nullptr)
Runs the profile generation.
QgsProfileExporter(const QList< QgsAbstractProfileSource * > &sources, const QgsProfileRequest &request, Qgis::ProfileExportType type)
Constructor for QgsProfileExporter, using the provided list of profile sources to generate the result...
QList< QgsVectorLayer * > toLayers()
Returns a list of vector layer containing the exported profile results.
Generates and renders elevation profile plots.
QVector< QgsAbstractProfileResults::Feature > asFeatures(Qgis::ProfileExportType type, QgsFeedback *feedback=nullptr)
Exports the profile results as a set of features.
void startGeneration()
Start the generation job and immediately return.
void waitForFinished()
Block until the current job has finished.
Encapsulates properties and constraints relating to fetching elevation profiles from different source...
virtual void cancel()
Notifies the task that it should terminate.
QgsTask(const QString &description=QString(), QgsTask::Flags flags=AllFlags)
Constructor for QgsTask.
@ CanCancel
Task can be canceled.
Options to pass to QgsVectorFileWriter::writeAsVectorFormat().
QString layerName
Layer name. If let empty, it will be derived from the filename.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QgsFeedback * feedback
Optional feedback object allowing cancellation of layer save.
static QgsVectorFileWriter::WriterError writeAsVectorFormatV3(QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *errorMessage=nullptr, QString *newFilename=nullptr, QString *newLayer=nullptr)
Writes a layer out to a vector file.
@ Canceled
Writing was interrupted by manual cancellation.
@ ErrSavingMetadata
Metadata saving failed.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
@ SupportsMultipleLayers
Filter to only formats which support multiple layers.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
@ CreateOrOverwriteLayer
Create or overwrite layer.
@ CreateOrOverwriteFile
Create or overwrite file.
Represents a vector layer which manages a vector based dataset.
#define QgsDebugError(str)
Definition qgslogger.h:71
Encapsulates information about a feature exported from the profile results.
Encapsulates the properties of a vector layer containing features that will be exported to the DXF fi...