QGIS API Documentation 3.99.0-Master (21b3aa880ba)
Loading...
Searching...
No Matches
qgsgeometrygapcheck.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeometrygapcheck.cpp
3 ---------------------
4 begin : September 2015
5 copyright : (C) 2014 by Sandro Mani / Sourcepole AG
6 email : smani at sourcepole dot ch
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsgeometrygapcheck.h"
17
18#include "qgsapplication.h"
19#include "qgscurve.h"
21#include "qgsfeaturepool.h"
22#include "qgsfeedback.h"
24#include "qgsgeometryengine.h"
25#include "qgspolygon.h"
26#include "qgsproject.h"
27#include "qgsvectorlayer.h"
28#include "qgsvectorlayerutils.h"
29
30#include "moc_qgsgeometrygapcheck.cpp"
31
33 : QgsGeometryCheck( context, configuration )
34 , mGapThresholdMapUnits( configuration.value( QStringLiteral( "gapThreshold" ) ).toDouble() )
35{
36}
37
38void QgsGeometryGapCheck::prepare( const QgsGeometryCheckContext *context, const QVariantMap &configuration )
39{
40 if ( configuration.value( QStringLiteral( "allowedGapsEnabled" ) ).toBool() )
41 {
42 QgsVectorLayer *layer = context->project()->mapLayer<QgsVectorLayer *>( configuration.value( "allowedGapsLayer" ).toString() );
43 if ( layer )
44 {
45 mAllowedGapsLayer = layer;
46 mAllowedGapsSource = std::make_unique<QgsVectorLayerFeatureSource>( layer );
47
48 mAllowedGapsBuffer = configuration.value( QStringLiteral( "allowedGapsBuffer" ) ).toDouble();
49 }
50 }
51 else
52 {
53 mAllowedGapsSource.reset();
54 }
55}
56
57QgsGeometryCheck::Result QgsGeometryGapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
58{
59 if ( feedback )
60 feedback->setProgress( feedback->progress() + 1.0 );
61
62 std::unique_ptr<QgsAbstractGeometry> allowedGapsGeom;
63 std::unique_ptr<QgsGeometryEngine> allowedGapsGeomEngine;
64
65 if ( mAllowedGapsSource )
66 {
67 QVector<QgsGeometry> allowedGaps;
68 QgsFeatureRequest request;
70 QgsFeatureIterator iterator = mAllowedGapsSource->getFeatures( request );
71 QgsFeature feature;
72
73 while ( iterator.nextFeature( feature ) )
74 {
75 if ( feedback && feedback->isCanceled() )
76 {
78 }
79
80 const QgsGeometry geom = feature.geometry();
81 const QgsGeometry gg = geom.buffer( mAllowedGapsBuffer, 20 );
82 allowedGaps.append( gg );
83 }
84
85 std::unique_ptr<QgsGeometryEngine> allowedGapsEngine( QgsGeometry::createGeometryEngine( nullptr, mContext->tolerance ) );
86
87 // Create union of allowed gaps
88 QString errMsg;
89 allowedGapsGeom.reset( allowedGapsEngine->combine( allowedGaps, &errMsg ) );
90 allowedGapsGeomEngine.reset( QgsGeometry::createGeometryEngine( allowedGapsGeom.get(), mContext->tolerance ) );
91 allowedGapsGeomEngine->prepareGeometry();
92 }
93
94 QVector<QgsGeometry> geomList;
95 QMap<QString, QSet<QVariant>> uniqueIds;
96 const QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
97 const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), nullptr, mContext, true );
98 for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
99 {
100 if ( feedback && feedback->isCanceled() )
101 {
103 }
104
105 if ( context()->uniqueIdFieldIndex != -1 )
106 {
107 QgsGeometryCheck::Result result = checkUniqueId( layerFeature, uniqueIds );
108 if ( result != QgsGeometryCheck::Result::Success )
109 {
110 return result;
111 }
112 }
113
114 geomList.append( layerFeature.geometry() );
115 }
116
117 std::unique_ptr<QgsGeometryEngine> geomEngine( QgsGeometry::createGeometryEngine( nullptr, mContext->tolerance ) );
118
119 // Create union of geometry
120 QString errMsg;
121 const std::unique_ptr<QgsAbstractGeometry> unionGeom( geomEngine->combine( geomList, &errMsg ) );
122 if ( !unionGeom )
123 {
124 messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
126 }
127
128 // Get envelope of union
129 geomEngine.reset( QgsGeometry::createGeometryEngine( unionGeom.get(), mContext->tolerance ) );
130 geomEngine->prepareGeometry();
131 std::unique_ptr<QgsAbstractGeometry> envelope( geomEngine->envelope( &errMsg ) );
132 if ( !envelope )
133 {
134 messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
136 }
137
138 // Buffer envelope
139 geomEngine.reset( QgsGeometry::createGeometryEngine( envelope.get(), mContext->tolerance ) );
140 geomEngine->prepareGeometry();
141 QgsAbstractGeometry *bufEnvelope = geomEngine->buffer( 2, 0, Qgis::EndCapStyle::Square, Qgis::JoinStyle::Miter, 4. ); //#spellok //#spellok
142 envelope.reset( bufEnvelope );
143
144 // Compute difference between envelope and union to obtain gap polygons
145 geomEngine.reset( QgsGeometry::createGeometryEngine( envelope.get(), mContext->tolerance ) );
146 geomEngine->prepareGeometry();
147 std::unique_ptr<QgsAbstractGeometry> diffGeom( geomEngine->difference( unionGeom.get(), &errMsg ) );
148 if ( !diffGeom )
149 {
150 messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
152 }
153
154 // For each gap polygon which does not lie on the boundary, get neighboring polygons and add error
155 QgsGeometryPartIterator parts = diffGeom->parts();
156 while ( parts.hasNext() )
157 {
158 if ( feedback && feedback->isCanceled() )
159 {
161 }
162
163 const QgsAbstractGeometry *gapGeom = parts.next();
164 // Skip the gap between features and boundingbox
165 const double spacing = context()->tolerance;
166 if ( gapGeom->boundingBox().snappedToGrid( spacing ) == envelope->boundingBox().snappedToGrid( spacing ) )
167 {
168 continue;
169 }
170
171 // Skip gaps above threshold
172 if ( ( mGapThresholdMapUnits > 0 && gapGeom->area() > mGapThresholdMapUnits ) || gapGeom->area() < mContext->reducedTolerance )
173 {
174 continue;
175 }
176
177 QgsRectangle gapAreaBBox = gapGeom->boundingBox();
178
179 // Get neighboring polygons
180 QMap<QString, QgsFeatureIds> neighboringIds;
181 const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds.keys(), gapAreaBBox, compatibleGeometryTypes(), mContext );
182 std::unique_ptr<QgsGeometryEngine> gapGeomEngine( QgsGeometry::createGeometryEngine( gapGeom, mContext->tolerance ) );
183 gapGeomEngine->prepareGeometry();
184 for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
185 {
186 if ( feedback && feedback->isCanceled() )
187 {
189 }
190
191 const QgsGeometry geom = layerFeature.geometry();
192 if ( gapGeomEngine->distance( geom.constGet() ) < mContext->tolerance )
193 {
194 neighboringIds[layerFeature.layer()->id()].insert( layerFeature.feature().id() );
195 gapAreaBBox.combineExtentWith( geom.boundingBox() );
196 }
197 }
198
199 if ( neighboringIds.isEmpty() )
200 {
201 continue;
202 }
203
204 if ( allowedGapsGeomEngine && allowedGapsGeomEngine->contains( gapGeom ) )
205 {
206 continue;
207 }
208
209 // Add error
210 const double area = gapGeom->area();
211 const QgsRectangle gapBbox = gapGeom->boundingBox();
212 errors.append( new QgsGeometryGapCheckError( this, QString(), QgsGeometry( gapGeom->clone() ), neighboringIds, area, gapBbox, gapAreaBBox ) );
213 }
215}
216
217void QgsGeometryGapCheck::fixError( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap<QString, int> & /*mergeAttributeIndices*/, Changes &changes ) const
218{
219 const QMetaEnum metaEnum = QMetaEnum::fromType<QgsGeometryGapCheck::ResolutionMethod>();
220 if ( !metaEnum.isValid() || !metaEnum.valueToKey( method ) )
221 {
222 error->setFixFailed( tr( "Unknown method" ) );
223 }
224 else
225 {
226 const ResolutionMethod methodValue = static_cast<ResolutionMethod>( method );
227 switch ( methodValue )
228 {
229 case NoChange:
230 error->setFixed( method );
231 break;
232
233 case MergeLongestEdge:
234 {
235 QString errMsg;
236 if ( mergeWithNeighbor( featurePools, static_cast<QgsGeometryGapCheckError *>( error ), changes, errMsg, LongestSharedEdge ) )
237 {
238 error->setFixed( method );
239 }
240 else
241 {
242 error->setFixFailed( tr( "Failed to merge with neighbor: %1" ).arg( errMsg ) );
243 }
244 break;
245 }
246
247 case AddToAllowedGaps:
248 {
249 QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( mAllowedGapsLayer.data() );
250 if ( layer )
251 {
252 if ( !layer->isEditable() && !layer->startEditing() )
253 {
254 error->setFixFailed( tr( "Could not start editing layer %1" ).arg( layer->name() ) );
255 }
256 else
257 {
258 const QgsFeature feature = QgsVectorLayerUtils::createFeature( layer, error->geometry() );
260 if ( !layer->addFeatures( features ) )
261 {
262 error->setFixFailed( tr( "Could not add feature to layer %1" ).arg( layer->name() ) );
263 }
264 else
265 {
266 error->setFixed( method );
267 }
268 }
269 }
270 else
271 {
272 error->setFixFailed( tr( "Allowed gaps layer could not be resolved" ) );
273 }
274 break;
275 }
276
277 case CreateNewFeature:
278 {
279 QgsGeometryGapCheckError *gapCheckError = static_cast<QgsGeometryGapCheckError *>( error );
280 QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( context()->project()->mapLayer( gapCheckError->neighbors().keys().first() ) );
281 if ( layer )
282 {
283 const QgsGeometry geometry = error->geometry();
286 if ( !layer->addFeature( feature ) )
287 {
288 error->setFixFailed( tr( "Could not add feature" ) );
289 }
290 else
291 {
292 error->setFixed( method );
293 }
294 }
295 else
296 {
297 error->setFixFailed( tr( "Could not resolve target layer %1 to add feature" ).arg( error->layerId() ) );
298 }
299 break;
300 }
301
302 case MergeLargestArea:
303 {
304 QString errMsg;
305 if ( mergeWithNeighbor( featurePools, static_cast<QgsGeometryGapCheckError *>( error ), changes, errMsg, LargestArea ) )
306 {
307 error->setFixed( method );
308 }
309 else
310 {
311 error->setFixFailed( tr( "Failed to merge with neighbor: %1" ).arg( errMsg ) );
312 }
313 break;
314 }
315 }
316 }
317}
318
319bool QgsGeometryGapCheck::mergeWithNeighbor( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryGapCheckError *err, Changes &changes, QString &errMsg, Condition condition ) const
320{
321 double maxVal = 0.;
322 QString mergeLayerId;
323 QgsFeature mergeFeature;
324 int mergePartIdx = -1;
325
326 const QgsGeometry geometry = err->geometry();
327 const QgsAbstractGeometry *errGeometry = QgsGeometryCheckerUtils::getGeomPart( geometry.constGet(), 0 );
328
329 const auto layerIds = err->neighbors().keys();
330 QList<QgsFeature> neighbours;
331
332 // Search for touching neighboring geometries
333 for ( const QString &layerId : layerIds )
334 {
335 QgsFeaturePool *featurePool = featurePools.value( layerId );
336 if ( !featurePool )
337 {
338 return false;
339 }
340 std::unique_ptr<QgsAbstractGeometry> errLayerGeom( errGeometry->clone() );
341 const QgsCoordinateTransform ct( featurePool->crs(), mContext->mapCrs, mContext->transformContext );
342 errLayerGeom->transform( ct, Qgis::TransformDirection::Reverse );
343
344 const auto featureIds = err->neighbors().value( layerId );
345
346 for ( const QgsFeatureId testId : featureIds )
347 {
348 QgsFeature feature;
349 if ( !featurePool->getFeature( testId, feature ) )
350 {
351 continue;
352 }
353
354 QgsGeometry transformedGeometry = feature.geometry();
355 transformedGeometry.transform( ct );
356 feature.setGeometry( transformedGeometry );
357 neighbours.append( feature );
358 }
359
360 for ( const QgsFeature &testFeature : neighbours )
361 {
362 const QgsGeometry featureGeom = testFeature.geometry();
363 const QgsAbstractGeometry *testGeom = featureGeom.constGet();
364 for ( int iPart = 0, nParts = testGeom->partCount(); iPart < nParts; ++iPart )
365 {
366 double val = 0;
367 switch ( condition )
368 {
369 case LongestSharedEdge:
370 val = QgsGeometryCheckerUtils::sharedEdgeLength( errLayerGeom.get(), QgsGeometryCheckerUtils::getGeomPart( testGeom, iPart ), mContext->reducedTolerance );
371 break;
372
373 case LargestArea:
374 // We might get a neighbour where we touch only a corner
375 if ( QgsGeometryCheckerUtils::sharedEdgeLength( errLayerGeom.get(), QgsGeometryCheckerUtils::getGeomPart( testGeom, iPart ), mContext->reducedTolerance ) > 0 )
376 val = QgsGeometryCheckerUtils::getGeomPart( testGeom, iPart )->area();
377 break;
378 }
379
380 if ( val > maxVal )
381 {
382 maxVal = val;
383 mergeFeature = testFeature;
384 mergePartIdx = iPart;
385 mergeLayerId = layerId;
386 }
387 }
388 }
389 }
390
391 if ( maxVal == 0. )
392 {
393 return false;
394 }
395
396 // Create an index of all neighbouring vertices
397 QgsSpatialIndex neighbourVerticesIndex( QgsSpatialIndex::Flag::FlagStoreFeatureGeometries );
398 int id = 0;
399 for ( const QgsFeature &neighbour : neighbours )
400 {
401 QgsVertexIterator vit = neighbour.geometry().vertices();
402 while ( vit.hasNext() )
403 {
404 const QgsPoint pt = vit.next();
405 QgsFeature f;
406 f.setId( id ); // required for SpatialIndex to return the correct result
407 f.setGeometry( QgsGeometry( pt.clone() ) );
408 neighbourVerticesIndex.addFeature( f );
409 id++;
410 }
411 }
412
413 // Snap to the closest vertex
414 QgsPolyline snappedRing;
415 QgsVertexIterator iterator = errGeometry->vertices();
416 while ( iterator.hasNext() )
417 {
418 const QgsPoint pt = iterator.next();
419 const QgsGeometry closestGeom = neighbourVerticesIndex.geometry( neighbourVerticesIndex.nearestNeighbor( QgsPointXY( pt ) ).first() );
420 if ( !closestGeom.isEmpty() )
421 {
422 snappedRing.append( QgsPoint( closestGeom.vertexAt( 0 ) ) );
423 }
424 }
425
426 auto snappedErrGeom = std::make_unique<QgsPolygon>();
427 snappedErrGeom->setExteriorRing( new QgsLineString( snappedRing ) );
428
429 // Merge geometries
430 QgsFeaturePool *featurePool = featurePools[mergeLayerId];
431 std::unique_ptr<QgsAbstractGeometry> errLayerGeom( snappedErrGeom->clone() );
432 const QgsCoordinateTransform ct( featurePool->crs(), mContext->mapCrs, mContext->transformContext );
433 errLayerGeom->transform( ct, Qgis::TransformDirection::Reverse );
434 const QgsGeometry mergeFeatureGeom = mergeFeature.geometry();
435 const QgsAbstractGeometry *mergeGeom = mergeFeatureGeom.constGet();
436 std::unique_ptr<QgsGeometryEngine> geomEngine( QgsGeometry::createGeometryEngine( errLayerGeom.get(), 0 ) );
437 std::unique_ptr<QgsAbstractGeometry> combinedGeom( geomEngine->combine( QgsGeometryCheckerUtils::getGeomPart( mergeGeom, mergePartIdx ), &errMsg ) );
438 if ( !combinedGeom || combinedGeom->isEmpty() || !QgsWkbTypes::isSingleType( combinedGeom->wkbType() ) )
439 {
440 return false;
441 }
442
443 // Add merged polygon to destination geometry
444 replaceFeatureGeometryPart( featurePools, mergeLayerId, mergeFeature, mergePartIdx, combinedGeom.release(), changes );
445
446 return true;
447}
448
449
451{
452 QStringList methods = QStringList()
453 << tr( "Add gap area to neighboring polygon with longest shared edge" )
454 << tr( "No action" );
455 if ( mAllowedGapsSource )
456 methods << tr( "Add gap to allowed exceptions" );
457
458 return methods;
459}
460
461QList<QgsGeometryCheckResolutionMethod> QgsGeometryGapCheck::availableResolutionMethods() const
462{
463 QList<QgsGeometryCheckResolutionMethod> fixes {
464 QgsGeometryCheckResolutionMethod( MergeLongestEdge, tr( "Add to longest shared edge" ), tr( "Add the gap area to the neighbouring polygon with the longest shared edge." ), false ),
465 QgsGeometryCheckResolutionMethod( CreateNewFeature, tr( "Create new feature" ), tr( "Create a new feature from the gap area." ), false ),
466 QgsGeometryCheckResolutionMethod( MergeLargestArea, tr( "Add to largest neighbouring area" ), tr( "Add the gap area to the neighbouring polygon with the largest area." ), false )
467 };
468
469 if ( mAllowedGapsSource )
470 fixes << QgsGeometryCheckResolutionMethod( AddToAllowedGaps, tr( "Add Gap to Allowed Exceptions" ), tr( "Create a new feature from the gap geometry on the allowed exceptions layer." ), true );
471
472 fixes << QgsGeometryCheckResolutionMethod( NoChange, tr( "No action" ), tr( "Do not perform any action and mark this error as fixed." ), false );
473
474 return fixes;
475}
476
478{
479 return factoryDescription();
480}
481
483{
484 return factoryId();
485}
486
488{
489 return factoryFlags();
490}
491
493QString QgsGeometryGapCheck::factoryDescription()
494{
495 return tr( "Gap" );
496}
497
498QString QgsGeometryGapCheck::factoryId()
499{
500 return QStringLiteral( "QgsGeometryGapCheck" );
501}
502
503QgsGeometryCheck::Flags QgsGeometryGapCheck::factoryFlags()
504{
506}
507
508QList<Qgis::GeometryType> QgsGeometryGapCheck::factoryCompatibleGeometryTypes()
509{
511}
512
513bool QgsGeometryGapCheck::factoryIsCompatible( QgsVectorLayer *layer ) SIP_SKIP
514{
515 return factoryCompatibleGeometryTypes().contains( layer->geometryType() );
516}
517
518QgsGeometryCheck::CheckType QgsGeometryGapCheck::factoryCheckType()
519{
521}
523
525{
526 return mContextBoundingBox;
527}
528
530{
531 QgsGeometryGapCheckError *err = dynamic_cast<QgsGeometryGapCheckError *>( other );
532 return err && err->location().distanceCompare( location(), mCheck->context()->reducedTolerance ) && err->neighbors() == neighbors();
533}
534
536{
537 QgsGeometryGapCheckError *err = dynamic_cast<QgsGeometryGapCheckError *>( other );
538 return err && err->layerId() == layerId() && err->neighbors() == neighbors();
539}
540
542{
544 // Static cast since this should only get called if isEqual == true
545 const QgsGeometryGapCheckError *err = static_cast<const QgsGeometryGapCheckError *>( other );
546 mNeighbors = err->mNeighbors;
547 mGapAreaBBox = err->mGapAreaBBox;
548}
549
554
556{
557 return mGapAreaBBox;
558}
559
560QMap<QString, QgsFeatureIds> QgsGeometryGapCheckError::involvedFeatures() const
561{
562 return mNeighbors;
563}
564
566{
568 return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmCheckGeometry.svg" ) );
569 else
570 return QgsApplication::getThemeIcon( QStringLiteral( "/checks/SliverOrGap.svg" ) );
571}
@ Polygon
Polygons.
Definition qgis.h:361
@ Miter
Use mitered joins.
Definition qgis.h:2123
@ Square
Square cap (extends past start/end of line by buffer distance).
Definition qgis.h:2111
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2673
Abstract base class for all geometries.
QgsVertexIterator vertices() const
Returns a read-only, Java-style iterator for traversal of vertices of all the geometry,...
virtual QgsRectangle boundingBox() const
Returns the minimal bounding box for the geometry.
virtual int partCount() const =0
Returns count of parts contained in the geometry.
virtual double area() const
Returns the planar, 2-dimensional area of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
A feature pool is based on a vector layer and caches features.
QgsCoordinateReferenceSystem crs() const
The coordinate reference system of this layer.
bool getFeature(QgsFeatureId id, QgsFeature &feature)
Retrieves the feature with the specified id into feature.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
void setId(QgsFeatureId id)
Sets the feature id for this feature.
QgsGeometry geometry
Definition qgsfeature.h:69
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
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
double progress() const
Returns the current progress reported by the feedback object.
Definition qgsfeedback.h:77
Base configuration for geometry checks.
const double tolerance
The tolerance to allow for in geometry checks.
This represents an error reported by a geometry check.
@ StatusFixed
The error is fixed.
Status status() const
The status of the error.
virtual void update(const QgsGeometryCheckError *other)
Update this error with the information from other.
const QgsGeometryCheck * mCheck
QgsGeometryCheckError(const QgsGeometryCheck *check, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, const QgsPointXY &errorLocation, QgsVertexId vidx=QgsVertexId(), const QVariant &value=QVariant(), ValueType valueType=ValueOther)
Create a new geometry check error with the parent check and for the layerFeature pair at the errorLoc...
void setFixed(int method)
Set the status to fixed and specify the method that has been used to fix the error.
void setFixFailed(const QString &reason)
Set the error status to failed and specify the reason for failure.
QgsGeometry geometry() const
The geometry of the error in map units.
const QString & layerId() const
The id of the layer on which this error has been detected.
const QgsPointXY & location() const
The location of the error in map units.
Implements a resolution for problems detected in geometry checks.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
QFlags< Flag > Flags
void replaceFeatureGeometryPart(const QMap< QString, QgsFeaturePool * > &featurePools, const QString &layerId, QgsFeature &feature, int partIdx, QgsAbstractGeometry *newPartGeom, Changes &changes) const
Replaces a part in a feature geometry.
const QgsGeometryCheckContext * mContext
@ AvailableInValidation
This geometry check should be available in layer validation on the vector layer peroperties.
CheckType
The type of a check.
@ LayerCheck
The check controls a whole layer (topology checks).
QMap< QString, QgsFeatureIds > allLayerFeatureIds(const QMap< QString, QgsFeaturePool * > &featurePools) const
Returns all layers and feature ids.
Result checkUniqueId(const QgsGeometryCheckerUtils::LayerFeature layerFeature, QMap< QString, QSet< QVariant > > &uniqueIds) const
Checks that there are no duplicated unique IDs.
Result
Result of the geometry checker operation.
@ Canceled
User canceled calculation.
@ GeometryOverlayError
Error performing geometry overlay operation.
@ Success
Operation completed successfully.
QgsGeometryCheck(const QgsGeometryCheckContext *context, const QVariantMap &configuration)
Create a new geometry check.
const QgsGeometryCheckContext * context() const
Returns the context.
A layer feature combination to uniquely identify and access a feature in a set of layers.
Contains a set of layers and feature ids in those layers to pass to a geometry check.
static QgsAbstractGeometry * getGeomPart(QgsAbstractGeometry *geom, int partIdx)
static double sharedEdgeLength(const QgsAbstractGeometry *geom1, const QgsAbstractGeometry *geom2, double tol)
An error produced by a QgsGeometryGapCheck.
QgsRectangle contextBoundingBox() const override
The context of the error.
void update(const QgsGeometryCheckError *other) override
Update this error with the information from other.
QMap< QString, QgsFeatureIds > involvedFeatures() const override
Returns a list of involved features.
bool closeMatch(QgsGeometryCheckError *other) const override
Check if this error is almost equal to other.
QIcon icon() const override
Returns an icon that should be shown for this kind of error.
QgsRectangle affectedAreaBBox() const override
The bounding box of the affected area of the error.
QgsGeometryGapCheckError(const QgsGeometryCheck *check, const QString &layerId, const QgsGeometry &geometry, const QMap< QString, QgsFeatureIds > &neighbors, double area, const QgsRectangle &gapAreaBBox, const QgsRectangle &contextArea)
Create a new gap check error produced by check on the layer layerId.
bool isEqual(QgsGeometryCheckError *other) const override
Check if this error is equal to other.
bool handleChanges(const QgsGeometryCheck::Changes &) override
Apply a list of changes.
const QMap< QString, QgsFeatureIds > & neighbors() const
A map of layers and feature ids of the neighbors of the gap.
QgsGeometryGapCheck(const QgsGeometryCheckContext *context, const QVariantMap &configuration)
The configuration accepts a "gapThreshold" key which specifies the maximum gap size in squared map un...
Q_DECL_DEPRECATED QStringList resolutionMethods() const override
Returns a list of descriptions for available resolutions for errors.
QString description() const override
Returns a human readable description for this check.
void fixError(const QMap< QString, QgsFeaturePool * > &featurePools, QgsGeometryCheckError *error, int method, const QMap< QString, int > &mergeAttributeIndices, Changes &changes) const override
Fixes the error error with the specified method.
void prepare(const QgsGeometryCheckContext *context, const QVariantMap &configuration) override
Will be run in the main thread before collectErrors() is called (which may be run from a background t...
QList< QgsGeometryCheckResolutionMethod > availableResolutionMethods() const override
Returns a list of available resolution methods.
QString id() const override
Returns an id for this check.
QgsGeometryCheck::Result collectErrors(const QMap< QString, QgsFeaturePool * > &featurePools, QList< QgsGeometryCheckError * > &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
ResolutionMethod
Resolution methods for geometry gap checks.
@ CreateNewFeature
Create a new feature with the gap geometry.
@ AddToAllowedGaps
Add gap geometry to allowed gaps layer.
@ MergeLongestEdge
Merge the gap with the polygon with the longest shared edge.
@ NoChange
Do not handle the error.
@ MergeLargestArea
Merge with neighbouring polygon with largest area.
QList< Qgis::GeometryType > compatibleGeometryTypes() const override
A list of geometry types for which this check can be performed.
QgsGeometryCheck::Flags flags() const override
Flags for this geometry check.
Java-style iterator for traversal of parts of a geometry.
bool hasNext() const
Find out whether there are more parts.
QgsAbstractGeometry * next()
Returns next part of the geometry (undefined behavior if hasNext() returns false before calling next(...
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsPoint vertexAt(int atVertex) const
Returns coordinates of a vertex.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
QString name
Definition qgsmaplayer.h:84
bool distanceCompare(const QgsPointXY &other, double epsilon=4 *std::numeric_limits< double >::epsilon()) const
Compares this point with another point with a fuzzy tolerance using distance comparison.
Definition qgspointxy.h:268
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:108
A rectangle specified with double values.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QgsRectangle snappedToGrid(double spacing) const
Returns a copy of this rectangle that is snapped to a grid with the specified spacing between the gri...
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
static QgsFeatureList makeFeatureCompatible(const QgsFeature &feature, const QgsVectorLayer *layer, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags())
Converts input feature to be compatible with the given layer.
static QgsFeature createFeature(const QgsVectorLayer *layer, const QgsGeometry &geometry=QgsGeometry(), const QgsAttributeMap &attributes=QgsAttributeMap(), QgsExpressionContext *context=nullptr)
Creates a new feature ready for insertion into a layer.
Represents a vector layer which manages a vector based dataset.
bool isEditable() const final
Returns true if the provider is in editing mode.
Q_INVOKABLE bool startEditing()
Makes the layer editable.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) final
Adds a list of features to the sink.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) final
Adds a single feature to the sink.
bool hasNext() const
Find out whether there are more vertices.
QgsPoint next()
Returns next vertex of the geometry (undefined behavior if hasNext() returns false before calling nex...
static Q_INVOKABLE bool isSingleType(Qgis::WkbType type)
Returns true if the WKB type is a single type.
#define SIP_SKIP
Definition qgis_sip.h:134
QMap< int, QVariant > QgsAttributeMap
QList< QgsFeature > QgsFeatureList
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList
Definition qgsfield.h:28
QgsPointSequence QgsPolyline
Polyline as represented as a vector of points.
Definition qgsgeometry.h:70
A list of layers and feature ids for each of these layers.
QMap< QString, QgsFeatureIds > toMap() const