QGIS API Documentation 3.99.0-Master (26c88405ac0)
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 <QThread>
29
30#include "moc_qgsprofileexporter.cpp"
31
32QgsProfileExporter::QgsProfileExporter( const QList<QgsAbstractProfileSource *> &sources, const QgsProfileRequest &request, Qgis::ProfileExportType type )
33 : mType( type )
34 , mRequest( request )
35{
36 for ( QgsAbstractProfileSource *source : sources )
37 {
38 if ( source )
39 {
40 if ( std::unique_ptr< QgsAbstractProfileGenerator > generator{ source->createProfileGenerator( mRequest ) } )
41 mGenerators.emplace_back( std::move( generator ) );
42 }
43 }
44}
45
47
49{
50 if ( mGenerators.empty() )
51 return;
52
53 QgsProfilePlotRenderer renderer( std::move( mGenerators ), mRequest );
54 renderer.startGeneration();
55 renderer.waitForFinished();
56
57 mFeatures = renderer.asFeatures( mType, feedback );
58}
59
60QList< QgsVectorLayer *> QgsProfileExporter::toLayers()
61{
62 if ( mFeatures.empty() )
63 return {};
64
65 // collect all features with the same geometry types together
66 QHash< quint32, QVector< QgsAbstractProfileResults::Feature > > featuresByGeometryType;
67 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( mFeatures ) )
68 {
69 featuresByGeometryType[static_cast< quint32 >( feature.geometry.wkbType() )].append( feature );
70 }
71
72 // generate a new memory provider layer for each geometry type
73 QList< QgsVectorLayer * > res;
74 for ( auto wkbTypeIt = featuresByGeometryType.constBegin(); wkbTypeIt != featuresByGeometryType.constEnd(); ++wkbTypeIt )
75 {
76 // first collate a master list of fields for this geometry type
77 QgsFields outputFields;
78 outputFields.append( QgsField( QStringLiteral( "layer" ), QMetaType::Type::QString ) );
79
80 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( wkbTypeIt.value() ) )
81 {
82 for ( auto attributeIt = feature.attributes.constBegin(); attributeIt != feature.attributes.constEnd(); ++attributeIt )
83 {
84 const int existingFieldIndex = outputFields.lookupField( attributeIt.key() );
85 if ( existingFieldIndex < 0 )
86 {
87 outputFields.append( QgsField( attributeIt.key(), static_cast<QMetaType::Type>( attributeIt.value().userType() ) ) );
88 }
89 else
90 {
91 if ( outputFields.at( existingFieldIndex ).type() != QMetaType::Type::QString && outputFields.at( existingFieldIndex ).type() != attributeIt.value().userType() )
92 {
93 // attribute type mismatch across fields, just promote to string types to be flexible
94 outputFields[ existingFieldIndex ].setType( QMetaType::Type::QString );
95 }
96 }
97 }
98 }
99
100 // note -- 2d profiles have no CRS associated, the coordinate values are not location based!
101 std::unique_ptr< QgsVectorLayer > outputLayer( QgsMemoryProviderUtils::createMemoryLayer(
102 QStringLiteral( "profile" ),
103 outputFields,
104 static_cast< Qgis::WkbType >( wkbTypeIt.key() ),
106 false ) );
107
108 QList< QgsFeature > featuresToAdd;
109 featuresToAdd.reserve( wkbTypeIt.value().size() );
110 for ( const QgsAbstractProfileResults::Feature &feature : std::as_const( wkbTypeIt.value() ) )
111 {
112 QgsFeature out( outputFields );
113 out.setAttribute( 0, feature.layerIdentifier );
114 out.setGeometry( feature.geometry );
115 for ( auto attributeIt = feature.attributes.constBegin(); attributeIt != feature.attributes.constEnd(); ++attributeIt )
116 {
117 const int outputFieldIndex = outputFields.lookupField( attributeIt.key() );
118 const QgsField &targetField = outputFields.at( outputFieldIndex );
119 QVariant value = attributeIt.value();
120 targetField.convertCompatible( value );
121 out.setAttribute( outputFieldIndex, value );
122 }
123 featuresToAdd << out;
124 }
125
126 outputLayer->dataProvider()->addFeatures( featuresToAdd, QgsFeatureSink::FastInsert );
127 res << outputLayer.release();
128 }
129 return res;
130}
131
132//
133// QgsProfileExporterTask
134//
135
136QgsProfileExporterTask::QgsProfileExporterTask( const QList<QgsAbstractProfileSource *> &sources,
137 const QgsProfileRequest &request,
139 const QString &destination,
140 const QgsCoordinateTransformContext &transformContext
141 )
142 : QgsTask( tr( "Exporting elevation profile" ), QgsTask::CanCancel )
143 , mDestination( destination )
144 , mTransformContext( transformContext )
145{
146 mExporter = std::make_unique< QgsProfileExporter >( sources, request, type );
147}
148
150{
151 mFeedback = std::make_unique< QgsFeedback >();
152
153 mExporter->run( mFeedback.get() );
154
155 mLayers = mExporter->toLayers();
156
157 if ( mFeedback->isCanceled() )
158 {
159 mResult = ExportResult::Canceled;
160 return true;
161 }
162
163 if ( !mDestination.isEmpty() && !mLayers.empty() )
164 {
165 const QFileInfo destinationFileInfo( mDestination );
166 const QString fileExtension = destinationFileInfo.completeSuffix();
167 const QString driverName = QgsVectorFileWriter::driverForExtension( fileExtension );
168
169 if ( driverName == QLatin1String( "DXF" ) )
170 {
171 // DXF gets special handling -- we use the inbuilt QgsDxfExport class
172 QgsDxfExport dxf;
173 QList< QgsDxfExport::DxfLayer > dxfLayers;
174 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
175 {
176 QgsDxfExport::DxfLayer dxfLayer( layer );
177 dxfLayers.append( dxfLayer );
178 if ( layer->crs().isValid() )
179 dxf.setDestinationCrs( layer->crs() );
180 }
181 dxf.addLayers( dxfLayers );
182 QFile dxfFile( mDestination );
183 switch ( dxf.writeToFile( &dxfFile, QStringLiteral( "UTF-8" ) ) )
184 {
186 mResult = ExportResult::Success;
187 mCreatedFiles.append( mDestination );
188 break;
189
193 break;
194
197 break;
198 }
199 }
200 else
201 {
202 // use vector file writer
203 const bool outputFormatIsMultiLayer = QgsVectorFileWriter::supportedFormatExtensions( QgsVectorFileWriter::SupportsMultipleLayers ).contains( fileExtension );
204
205 int layerCount = 1;
206 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
207 {
208 QString thisLayerFilename;
210 if ( outputFormatIsMultiLayer )
211 {
212 thisLayerFilename = mDestination;
215 if ( mLayers.size() > 1 )
216 options.layerName = QStringLiteral( "profile_%1" ).arg( layerCount );
217 }
218 else
219 {
221 if ( mLayers.size() > 1 )
222 {
223 thisLayerFilename = QStringLiteral( "%1/%2_%3.%4" ).arg( destinationFileInfo.path(), destinationFileInfo.baseName() ).arg( layerCount ).arg( fileExtension );
224 }
225 else
226 {
227 thisLayerFilename = mDestination;
228 }
229 }
230 options.driverName = driverName;
231 options.feedback = mFeedback.get();
232 options.fileEncoding = QStringLiteral( "UTF-8" );
233 QString newFileName;
235 layer,
236 thisLayerFilename,
237 mTransformContext,
238 options,
239 &mError,
240 &newFileName
241 );
242 switch ( result )
243 {
245 mResult = ExportResult::Success;
246 if ( !mCreatedFiles.contains( newFileName ) )
247 mCreatedFiles.append( newFileName );
248 break;
249
254 break;
255
263 break;
264
265
267 mResult = ExportResult::Canceled;
268 break;
269 }
270
271 if ( mResult != ExportResult::Success )
272 break;
273 layerCount += 1;
274 }
275 }
276 }
277 else if ( mLayers.empty() )
278 {
279 mResult = ExportResult::Empty;
280 }
281
282 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
283 {
284 layer->moveToThread( nullptr );
285 }
286
287 mExporter.reset();
288 return true;
289}
290
292{
293 if ( mFeedback )
294 mFeedback->cancel();
295
297}
298
299QList<QgsVectorLayer *> QgsProfileExporterTask::takeLayers()
300{
301 QList<QgsVectorLayer *> res;
302 res.reserve( mLayers.size() );
303 for ( QgsVectorLayer *layer : std::as_const( mLayers ) )
304 {
305 layer->moveToThread( QThread::currentThread() );
306 res.append( layer );
307 }
308 mLayers.clear();
309 return res;
310}
311
ProfileExportType
Types of export for elevation profiles.
Definition qgis.h:4233
@ Profile2D
Export profiles as 2D profile lines, with elevation stored in exported geometry Y dimension and dista...
Definition qgis.h:4235
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
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.
@ 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:58
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:54
QMetaType::Type type
Definition qgsfield.h:61
bool convertCompatible(QVariant &v, QString *errorMessage=nullptr) const
Converts the provided variant to a compatible format.
Definition qgsfield.cpp:475
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
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.
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, Qgis::WkbType geometryType=Qgis::WkbType::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), bool loadDefaultStyle=true) SIP_FACTORY
Creates a new memory layer using the specified parameters.
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.
Encapsulates information about a feature exported from the profile results.
Layers and optional attribute index to split into multiple layers using attribute value as layer name...