19#include "moc_qgsgeometrygapcheck.cpp"
32 , mGapThresholdMapUnits( configuration.value( QStringLiteral(
"gapThreshold" ) ).toDouble() )
38 if ( configuration.value( QStringLiteral(
"allowedGapsEnabled" ) ).toBool() )
43 mAllowedGapsLayer = layer;
44 mAllowedGapsSource = std::make_unique<QgsVectorLayerFeatureSource>( layer );
46 mAllowedGapsBuffer = configuration.value( QStringLiteral(
"allowedGapsBuffer" ) ).toDouble();
51 mAllowedGapsSource.reset();
60 std::unique_ptr<QgsAbstractGeometry> allowedGapsGeom;
61 std::unique_ptr<QgsGeometryEngine> allowedGapsGeomEngine;
63 if ( mAllowedGapsSource )
65 QVector<QgsGeometry> allowedGaps;
75 allowedGaps.append( gg );
82 allowedGapsGeom.reset( allowedGapsEngine->combine( allowedGaps, &errMsg ) );
84 allowedGapsGeomEngine->prepareGeometry();
87 QVector<QgsGeometry> geomList;
92 geomList.append( layerFeature.geometry() );
101 if ( geomList.isEmpty() )
110 const std::unique_ptr<QgsAbstractGeometry> unionGeom( geomEngine->combine( geomList, &errMsg ) );
113 messages.append( tr(
"Gap check: %1" ).arg( errMsg ) );
119 geomEngine->prepareGeometry();
120 std::unique_ptr<QgsAbstractGeometry> envelope( geomEngine->envelope( &errMsg ) );
123 messages.append( tr(
"Gap check: %1" ).arg( errMsg ) );
129 geomEngine->prepareGeometry();
131 envelope.reset( bufEnvelope );
135 geomEngine->prepareGeometry();
136 std::unique_ptr<QgsAbstractGeometry> diffGeom( geomEngine->difference( unionGeom.get(), &errMsg ) );
139 messages.append( tr(
"Gap check: %1" ).arg( errMsg ) );
164 QMap<QString, QgsFeatureIds> neighboringIds;
167 gapGeomEngine->prepareGeometry();
173 neighboringIds[layerFeature.layer()->id()].insert( layerFeature.feature().id() );
178 if ( neighboringIds.isEmpty() )
183 if ( allowedGapsGeomEngine && allowedGapsGeomEngine->contains( gapGeom ) )
189 const double area = gapGeom->
area();
197 const QMetaEnum metaEnum = QMetaEnum::fromType<QgsGeometryGapCheck::ResolutionMethod>();
198 if ( !metaEnum.isValid() || !metaEnum.valueToKey( method ) )
205 switch ( methodValue )
214 if ( mergeWithNeighbor( featurePools,
static_cast<QgsGeometryGapCheckError *
>( error ), changes, errMsg, LongestSharedEdge ) )
220 error->
setFixFailed( tr(
"Failed to merge with neighbor: %1" ).arg( errMsg ) );
227 QgsVectorLayer *layer = qobject_cast<QgsVectorLayer *>( mAllowedGapsLayer.data() );
232 error->
setFixFailed( tr(
"Could not start editing layer %1" ).arg( layer->
name() ) );
240 error->
setFixFailed( tr(
"Could not add feature to layer %1" ).arg( layer->
name() ) );
250 error->
setFixFailed( tr(
"Allowed gaps layer could not be resolved" ) );
276 error->
setFixFailed( tr(
"Could not resolve target layer %1 to add feature" ).arg( error->
layerId() ) );
284 if ( mergeWithNeighbor( featurePools,
static_cast<QgsGeometryGapCheckError *
>( error ), changes, errMsg, LargestArea ) )
290 error->
setFixFailed( tr(
"Failed to merge with neighbor: %1" ).arg( errMsg ) );
298bool QgsGeometryGapCheck::mergeWithNeighbor(
const QMap<QString, QgsFeaturePool *> &featurePools,
QgsGeometryGapCheckError *err, Changes &changes, QString &errMsg, Condition condition )
const
301 QString mergeLayerId;
303 int mergePartIdx = -1;
308 const auto layerIds = err->
neighbors().keys();
309 QList<QgsFeature> neighbours;
312 for (
const QString &layerId : layerIds )
315 std::unique_ptr<QgsAbstractGeometry> errLayerGeom( errGeometry->
clone() );
319 const auto featureIds = err->
neighbors().value( layerId );
324 if ( !featurePool->
getFeature( testId, feature ) )
332 neighbours.append( feature );
335 for (
const QgsFeature &testFeature : neighbours )
337 const QgsGeometry featureGeom = testFeature.geometry();
339 for (
int iPart = 0, nParts = testGeom->
partCount(); iPart < nParts; ++iPart )
344 case LongestSharedEdge:
358 mergeFeature = testFeature;
359 mergePartIdx = iPart;
360 mergeLayerId = layerId;
374 for (
const QgsFeature &neighbour : neighbours )
383 neighbourVerticesIndex.addFeature( f );
394 const QgsGeometry closestGeom = neighbourVerticesIndex.geometry( neighbourVerticesIndex.nearestNeighbor(
QgsPointXY( pt ) ).first() );
401 std::unique_ptr<QgsPolygon> snappedErrGeom = std::make_unique<QgsPolygon>();
402 snappedErrGeom->setExteriorRing(
new QgsLineString( snappedRing ) );
406 std::unique_ptr<QgsAbstractGeometry> errLayerGeom( snappedErrGeom->clone() );
427 QStringList methods = QStringList()
428 << tr(
"Add gap area to neighboring polygon with longest shared edge" )
429 << tr(
"No action" );
430 if ( mAllowedGapsSource )
431 methods << tr(
"Add gap to allowed exceptions" );
438 QList<QgsGeometryCheckResolutionMethod> fixes
445 if ( mAllowedGapsSource )
455 return factoryDescription();
465 return factoryFlags();
469QString QgsGeometryGapCheck::factoryDescription()
474QString QgsGeometryGapCheck::factoryId()
476 return QStringLiteral(
"QgsGeometryGapCheck" );
484QList<Qgis::GeometryType> QgsGeometryGapCheck::factoryCompatibleGeometryTypes()
491 return factoryCompatibleGeometryTypes().contains( layer->geometryType() );
502 return mContextBoundingBox;
522 mNeighbors = err->mNeighbors;
523 mGapAreaBBox = err->mGapAreaBBox;
@ Miter
Use mitered joins.
@ Square
Square cap (extends past start/end of line by buffer distance)
@ Reverse
Reverse/inverse transform (from destination to source)
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.
This class 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...
void setId(QgsFeatureId id)
Sets the feature id for this feature.
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.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
double progress() const
Returns the current progress reported by the feedback object.
Base configuration for geometry checks.
const QgsProject * project() const
The project can be used to resolve additional layers.
const double reducedTolerance
The tolerance to allow for in geometry checks.
const QgsCoordinateTransformContext transformContext
The coordinate transform context with which transformations will be done.
const QgsCoordinateReferenceSystem mapCrs
The coordinate system in which calculations should be done.
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
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.
This class implements a resolution for problems detected in geometry checks.
This class implements a geometry check.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
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.
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.
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...
void collectErrors(const QMap< QString, QgsFeaturePool * > &featurePools, QList< QgsGeometryCheckError * > &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
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.
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...
Line string geometry type, with support for z-dimension and m-values.
A class to represent a 2D point.
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.
Point geometry type, with support for z-dimension and m-values.
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
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...
A spatial index for QgsFeature objects.
@ 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 data sets.
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 isEditable() const FINAL
Returns true if the provider is in editing mode.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) FINAL
Adds a single feature to the sink.
Java-style iterator for traversal of vertices of a geometry.
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 bool isSingleType(Qgis::WkbType type)
Returns true if the WKB type is a single type.
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
QgsPointSequence QgsPolyline
Polyline as represented as a vector of points.
A list of layers and feature ids for each of these layers.
QMap< QString, QgsFeatureIds > toMap() const