Skip to content

Commit

Permalink
Merge pull request #52404 from domi4484/backportMergeFeatureRelocation
Browse files Browse the repository at this point in the history
  • Loading branch information
m-kuhn committed Mar 30, 2023
2 parents e528bd4 + 789a108 commit bc12bf4
Show file tree
Hide file tree
Showing 9 changed files with 335 additions and 62 deletions.
15 changes: 15 additions & 0 deletions python/core/auto_generated/vector/qgsvectorlayereditutils.sip.in
Expand Up @@ -310,6 +310,21 @@ editing.
:return: 2 in case vertex already exists or point does not intersect segment

.. versionadded:: 3.16
%End

bool mergeFeatures( const QgsFeatureId &targetFeatureId, const QgsFeatureIds &mergeFeatureIds, const QgsAttributes &mergeAttributes, const QgsGeometry &unionGeometry, QString &errorMessage /Out/ );
%Docstring
Merge features into a single one.

:param targetFeatureId: id of the target feature (will be updated)
:param mergeFeatureIds: id list of features to merge (will be deleted)
:param mergeAttributes: are the resulting attributes in the merged feature
:param unionGeometry: is the resulting geometry of the merged feature

:return: - ``True`` if the merge was successful, or ``False`` if the operation failed.
- errorMessage: will be set to a descriptive error message if any occurs

.. versionadded:: 3.30
%End

};
Expand Down
87 changes: 26 additions & 61 deletions src/app/qgisapp.cpp
Expand Up @@ -102,6 +102,7 @@
#include "qgsdockablewidgethelper.h"
#include "vertextool/qgsvertexeditor.h"
#include "qgsvectorlayerutils.h"
#include "qgsvectorlayereditutils.h"
#include "qgsadvanceddigitizingdockwidget.h"
#include "qgsabstractdatasourcewidget.h"
#include "qgsmeshlayer.h"
Expand Down Expand Up @@ -9517,9 +9518,8 @@ void QgisApp::mergeSelectedFeatures()
return;
}

//get selected feature ids (as a QSet<int> )
const QgsFeatureIds &featureIdSet = vl->selectedFeatureIds();
if ( featureIdSet.size() < 2 )
// Check at least two features are selected
if ( vl->selectedFeatureIds().size() < 2 )
{
visibleMessageBar()->pushMessage(
tr( "Not enough features selected" ),
Expand Down Expand Up @@ -9593,73 +9593,38 @@ void QgisApp::mergeSelectedFeatures()
}
return;
}
}

QgsAttributes attrs = d.mergedAttributes();
QgsAttributeMap newAttributes;
QString errorMessage;
QgsFeatureId mergeFeatureId = FID_NULL;
for ( int i = 0; i < attrs.count(); ++i )
{
QVariant val = attrs.at( i );
bool isDefaultValue = vl->fields().fieldOrigin( i ) == QgsFields::OriginProvider &&
vl->dataProvider() &&
vl->dataProvider()->defaultValueClause( vl->fields().fieldOriginIndex( i ) ) == val;
bool isPrimaryKey = vl->fields().fieldOrigin( i ) == QgsFields::OriginProvider &&
vl->dataProvider() &&
vl->dataProvider()->pkAttributeIndexes().contains( vl->fields().fieldOriginIndex( i ) );

if ( isPrimaryKey && !isDefaultValue )
mergeFeatureId = val.toLongLong();

// convert to destination data type
if ( !isDefaultValue && !vl->fields().at( i ).convertCompatible( val, &errorMessage ) )
else if ( !QgsWkbTypes::isMultiType( vl->wkbType() ) )
{
visibleMessageBar()->pushMessage(
tr( "Invalid result" ),
tr( "Could not store value '%1' in field of type %2: %3" ).arg( attrs.at( i ).toString(), vl->fields().at( i ).typeName(), errorMessage ),
Qgis::MessageLevel::Warning );
const QgsGeometryCollection *c = qgsgeometry_cast<const QgsGeometryCollection *>( unionGeom.constGet() );
if ( ( c && c->partCount() > 1 ) || !unionGeom.convertToSingleType() )
{
visibleMessageBar()->pushMessage(
tr( "Merge failed" ),
tr( "Resulting geometry type (multipart) is incompatible with layer type (singlepart)." ),
Qgis::MessageLevel::Critical );
return;
}
}
newAttributes[ i ] = val;
}

vl->beginEditCommand( tr( "Merged features" ) );

QgsFeature mergeFeature;
if ( mergeFeatureId == FID_NULL )
{
// Create new feature
mergeFeature = QgsVectorLayerUtils::createFeature( vl, unionGeom, newAttributes );
}
else
{
// Merge into existing feature
featureIdsAfter.remove( mergeFeatureId );
}

// Delete other features
QgsFeatureIds::const_iterator feature_it = featureIdsAfter.constBegin();
for ( ; feature_it != featureIdsAfter.constEnd(); ++feature_it )
{
vl->deleteFeature( *feature_it );
}

QString errorMessage;
QgsVectorLayerEditUtils vectorLayerEditUtils( vl );
bool success = vectorLayerEditUtils.mergeFeatures( d.targetFeatureId(), vl->selectedFeatureIds(), d.mergedAttributes(), unionGeom, errorMessage );

if ( mergeFeatureId == FID_NULL )
if ( !success )
{
// Add the new feature
vl->addFeature( mergeFeature );
visibleMessageBar()->pushMessage(
tr( "Merge failed" ),
errorMessage,
Qgis::MessageLevel::Critical );
}
else
else if ( success && !errorMessage.isEmpty() )
{
// Modify merge feature
vl->changeGeometry( mergeFeatureId, unionGeom );
vl->changeAttributeValues( mergeFeatureId, newAttributes );
visibleMessageBar()->pushMessage(
tr( "Invalid result" ),
errorMessage,
Qgis::MessageLevel::Warning );
}

vl->endEditCommand();

vl->triggerRepaint();
}

void QgisApp::vertexTool()
Expand Down
16 changes: 16 additions & 0 deletions src/app/qgsmergeattributesdialog.cpp
Expand Up @@ -108,6 +108,9 @@ QgsMergeAttributesDialog::QgsMergeAttributesDialog( const QgsFeatureList &featur
break;
}

if ( ! mFeatureList.isEmpty() )
mTargetFeatureId = mFeatureList.first().id();

connect( mSkipAllButton, &QAbstractButton::clicked, this, &QgsMergeAttributesDialog::setAllToSkip );
connect( mTableWidget, &QTableWidget::cellChanged, this, &QgsMergeAttributesDialog::tableWidgetCellChanged );

Expand Down Expand Up @@ -465,6 +468,8 @@ void QgsMergeAttributesDialog::setAllAttributesFromFeature( QgsFeatureId feature
currentComboBox->setCurrentIndex( currentComboBox->findData( QStringLiteral( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) );
}
}

mTargetFeatureId = featureId;
}

QVariant QgsMergeAttributesDialog::calcStatistic( int col, QgsStatisticalSummary::Statistic stat )
Expand Down Expand Up @@ -666,12 +671,18 @@ void QgsMergeAttributesDialog::mRemoveFeatureFromSelectionButton_clicked()
f_it != mFeatureList.end();
++f_it )
{
if ( f_it->id() == mTargetFeatureId )
mTargetFeatureId = FID_NULL;

if ( f_it->id() == featureId )
{
mFeatureList.erase( f_it );
break;
}
}

if ( mTargetFeatureId == FID_NULL && !mFeatureList.isEmpty() )
mTargetFeatureId = mFeatureList.first().id();
}

void QgsMergeAttributesDialog::tableWidgetCellChanged( int row, int column )
Expand Down Expand Up @@ -745,6 +756,11 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const
return results;
}

QgsFeatureId QgsMergeAttributesDialog::targetFeatureId() const
{
return mTargetFeatureId;
}

QSet<int> QgsMergeAttributesDialog::skippedAttributeIndexes() const
{
QSet<int> skipped;
Expand Down
13 changes: 13 additions & 0 deletions src/app/qgsmergeattributesdialog.h
Expand Up @@ -49,6 +49,18 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA

QgsAttributes mergedAttributes() const;

/**
* Returns the id of the target feature.
* By default it is the first feature of the list. Otherwise the feature explicitly selected
* with buttons "Take attributes from selected feature" or "Take attributes from feature with
* the largest area".
*
* \returns The id of the target feature.
*
* \since QGIS 3.30
*/
QgsFeatureId targetFeatureId() const;

/**
* Returns a list of attribute indexes which should be skipped when merging (e.g., attributes
* which have been set to "skip"
Expand Down Expand Up @@ -102,6 +114,7 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA
void createRubberBandForFeature( QgsFeatureId featureId );

QgsFeatureList mFeatureList;
QgsFeatureId mTargetFeatureId = FID_NULL;
QgsVectorLayer *mVectorLayer = nullptr;
QgsMapCanvas *mMapCanvas = nullptr;
//! Item that highlights the selected feature in the merge table
Expand Down
50 changes: 50 additions & 0 deletions src/core/vector/qgsvectorlayereditutils.cpp
Expand Up @@ -721,6 +721,56 @@ int QgsVectorLayerEditUtils::addTopologicalPoints( const QgsPointXY &p )
return addTopologicalPoints( QgsPoint( p ) );
}

bool QgsVectorLayerEditUtils::mergeFeatures( const QgsFeatureId &targetFeatureId, const QgsFeatureIds &mergeFeatureIds, const QgsAttributes &mergeAttributes, const QgsGeometry &unionGeometry, QString &errorMessage )
{
errorMessage.clear();

if ( mergeFeatureIds.isEmpty() )
{
errorMessage = QObject::tr( "List of features to merge is empty" );
return false;
}

QgsAttributeMap newAttributes;
for ( int i = 0; i < mergeAttributes.count(); ++i )
{
QVariant val = mergeAttributes.at( i );

bool isDefaultValue = mLayer->fields().fieldOrigin( i ) == QgsFields::OriginProvider &&
mLayer->dataProvider() &&
mLayer->dataProvider()->defaultValueClause( mLayer->fields().fieldOriginIndex( i ) ) == val;

// convert to destination data type
QString errorMessageConvertCompatible;
if ( !isDefaultValue && !mLayer->fields().at( i ).convertCompatible( val, &errorMessageConvertCompatible ) )
{
if ( errorMessage.isEmpty() )
errorMessage = QObject::tr( "Could not store value '%1' in field of type %2: %3" ).arg( mergeAttributes.at( i ).toString(), mLayer->fields().at( i ).typeName(), errorMessageConvertCompatible );
}
newAttributes[ i ] = val;
}

mLayer->beginEditCommand( QObject::tr( "Merged features" ) );

// Delete other features but the target feature
QgsFeatureIds::const_iterator feature_it = mergeFeatureIds.constBegin();
for ( ; feature_it != mergeFeatureIds.constEnd(); ++feature_it )
{
if ( *feature_it != targetFeatureId )
mLayer->deleteFeature( *feature_it );
}

// Modify merge feature
QgsGeometry mergeGeometry = unionGeometry;
mLayer->changeGeometry( targetFeatureId, mergeGeometry );
mLayer->changeAttributeValues( targetFeatureId, newAttributes );

mLayer->endEditCommand();

mLayer->triggerRepaint();

return true;
}

bool QgsVectorLayerEditUtils::boundingBoxFromPointList( const QgsPointSequence &list, double &xmin, double &ymin, double &xmax, double &ymax ) const
{
Expand Down
14 changes: 14 additions & 0 deletions src/core/vector/qgsvectorlayereditutils.h
Expand Up @@ -268,6 +268,20 @@ class CORE_EXPORT QgsVectorLayerEditUtils
*/
int addTopologicalPoints( const QgsPointSequence &ps );

/**
* Merge features into a single one.
* \param targetFeatureId id of the target feature (will be updated)
* \param mergeFeatureIds id list of features to merge (will be deleted)
* \param mergeAttributes are the resulting attributes in the merged feature
* \param unionGeometry is the resulting geometry of the merged feature
* \param errorMessage will be set to a descriptive error message if any occurs
*
* \returns TRUE if the merge was successful, or FALSE if the operation failed.
*
* \since QGIS 3.30
*/
bool mergeFeatures( const QgsFeatureId &targetFeatureId, const QgsFeatureIds &mergeFeatureIds, const QgsAttributes &mergeAttributes, const QgsGeometry &unionGeometry, QString &errorMessage SIP_OUT );

private:

/**
Expand Down
1 change: 1 addition & 0 deletions tests/src/app/CMakeLists.txt
Expand Up @@ -46,6 +46,7 @@ set(TESTS
testqgsmeshcalculatordialog.cpp
testqgsgpsinformationwidget.cpp
testqgslabelpropertydialog.cpp
testqgsmergeattributesdialog.cpp
)

if (HAVE_GEOREFERENCER)
Expand Down
97 changes: 97 additions & 0 deletions tests/src/app/testqgsmergeattributesdialog.cpp
@@ -0,0 +1,97 @@
/***************************************************************************
testqgsmergeattributesdialog.cpp
--------------------------------
Date : Feb 2023
Copyright : (C) 2023 by Damiano Lombardi
Email : damiano at opengis dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/

#include "qgstest.h"
#include <QObject>

#include "qgisapp.h"
#include "qgsapplication.h"
#include "qgsvectorlayer.h"
#include "qgsmergeattributesdialog.h"

class TestQgsMergeattributesDialog : public QObject
{
Q_OBJECT

public:
TestQgsMergeattributesDialog() = default;

private:
QgisApp *mQgisApp = nullptr;

private slots:

void initTestCase()
{
QgsApplication::init();
QgsApplication::initQgis();
mQgisApp = new QgisApp();
}

void cleanupTestCase()
{
QgsApplication::exitQgis();
}

void test()
{
// Create test layer
QgsVectorFileWriter::SaveVectorOptions options;
QgsVectorLayer ml( "Polygon", "test", "memory" );
QVERIFY( ml.isValid() );
QTemporaryFile tmpFile( QDir::tempPath() + "/TestQgsMergeattributesDialog" );
tmpFile.open();
const QString fileName( tmpFile.fileName( ) );
options.driverName = "GPKG";
options.layerName = "test";
QString newFilename;
const QgsVectorFileWriter::WriterError error( QgsVectorFileWriter::writeAsVectorFormatV3(
&ml,
fileName,
ml.transformContext(),
options, nullptr,
&newFilename ) );

QCOMPARE( error, QgsVectorFileWriter::WriterError::NoError );
QgsVectorLayer layer( QStringLiteral( "%1|layername=test" ).arg( newFilename ), "src_test", "ogr" );
QVERIFY( layer.startEditing() );
QgsVectorDataProvider *pr = layer.dataProvider();

// Create a feature
QgsFeature f1( layer.fields(), 1 );
f1.setGeometry( QgsGeometry::fromWkt( "POLYGON((0 0, 5 0, 5 5, 0 5, 0 0))" ) );
QVERIFY( pr->addFeature( f1 ) );
QCOMPARE( layer.featureCount(), 1 );

// And a bigger feature
QgsFeature f2( layer.fields(), 2 );
f2.setGeometry( QgsGeometry::fromWkt( "POLYGON((3 3, 10 3, 10 10, 3 10, 3 3))" ) );
QVERIFY( pr->addFeature( f2 ) );
QCOMPARE( layer.featureCount(), 2 );

// Merge the attributes together
QgsMergeAttributesDialog dialog( QgsFeatureList() << f1 << f2, &layer, mQgisApp->mapCanvas() );

// At beginnning the first feature of the list is the target
QCOMPARE( dialog.targetFeatureId(), f1.id() );

// Check after taking feature with largest geometry
QVERIFY( QMetaObject::invokeMethod( &dialog, "mFromLargestPushButton_clicked" ) );
QCOMPARE( dialog.targetFeatureId(), f2.id() );
}
};

QGSTEST_MAIN( TestQgsMergeattributesDialog )
#include "testqgsmergeattributesdialog.moc"

0 comments on commit bc12bf4

Please sign in to comment.