Skip to content

Commit

Permalink
Be a bit more forgiving and handle raw map layer pointers in
Browse files Browse the repository at this point in the history
expression values

But raise a warning on debug builds that these should be avoided
in place of weak pointers
  • Loading branch information
nyalldawson committed Feb 7, 2022
1 parent 9139c08 commit 8cf7f56
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/core/expression/qgsexpressionutils.h
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,17 @@ class CORE_EXPORT QgsExpressionUtils
{
// First check if we already received a layer pointer
QgsMapLayer *ml = value.value< QgsWeakMapLayerPointer >().data();
if ( !ml )
{
ml = value.value< QgsMapLayer * >();
#ifdef QGISDEBUG
if ( ml )
{
qWarning( "Raw map layer pointer stored in expression evaluation, switch to QgsWeakMapLayerPointer instead" );
}
#endif
}

QgsProject *project = QgsProject::instance();

// No pointer yet, maybe it's a layer id?
Expand Down
51 changes: 51 additions & 0 deletions tests/src/core/testqgsexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4246,6 +4246,57 @@ class TestQgsExpression: public QObject
QCOMPARE( result.toString(), QString( "f2" ) );
}

void testExpressionUtilsMapLayerRetrieval()
{
QgsExpression exp;
// NULL value
QgsMapLayer *res = QgsExpressionUtils::getMapLayer( QVariant(), &exp );
QVERIFY( !res );
QVERIFY( !exp.hasEvalError() );

// value which CANNOT be a map layer
res = QgsExpressionUtils::getMapLayer( QVariant( 5 ), &exp );
QVERIFY( !res );
#if 0
// TODO probably **should** raise an eval error for this situation?
QVERIFY( exp.hasEvalError() );
#endif

// with weak map layer pointer
exp = QgsExpression();
QgsWeakMapLayerPointer weakPointer( mPointsLayer );
res = QgsExpressionUtils::getMapLayer( QVariant::fromValue( weakPointer ), &exp );
QCOMPARE( res, mPointsLayer );
QVERIFY( !exp.hasEvalError() );

// with raw map layer pointer
exp = QgsExpression();
res = QgsExpressionUtils::getMapLayer( QVariant::fromValue( mPointsLayer ), &exp );
QCOMPARE( res, mPointsLayer );
QVERIFY( !exp.hasEvalError() );

// with layer id
exp = QgsExpression();
res = QgsExpressionUtils::getMapLayer( mPointsLayer->id(), &exp );
QCOMPARE( res, mPointsLayer );
QVERIFY( !exp.hasEvalError() );

// with layer name
exp = QgsExpression();
res = QgsExpressionUtils::getMapLayer( mPointsLayer->name(), &exp );
QCOMPARE( res, mPointsLayer );
QVERIFY( !exp.hasEvalError() );

// with string which is neither id or name
exp = QgsExpression();
res = QgsExpressionUtils::getMapLayer( QStringLiteral( "xxxA" ), &exp );
QVERIFY( !res );
#if 0
// TODO -- probably should flag an error here?
QVERIFY( !exp.hasEvalError() );
#endif
}

void test_env()
{
QgsExpressionContext context;
Expand Down

0 comments on commit 8cf7f56

Please sign in to comment.