QGIS API Documentation 3.39.0-Master (52f98f8c831)
Loading...
Searching...
No Matches
qgsexpressionfunction.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsexpressionfunction.cpp
3 -------------------
4 begin : May 2017
5 copyright : (C) 2017 Matthias Kuhn
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
17#include <random>
18
20#include "qgscoordinateutils.h"
22#include "qgsexpressionutils.h"
24#include "qgsexiftools.h"
25#include "qgsfeaturerequest.h"
26#include "qgsgeos.h"
27#include "qgsstringutils.h"
28#include "qgsmultipoint.h"
29#include "qgsgeometryutils.h"
30#include "qgshstoreutils.h"
31#include "qgsmultilinestring.h"
32#include "qgslinestring.h"
33#include "qgscurvepolygon.h"
35#include "qgspolygon.h"
36#include "qgstriangle.h"
37#include "qgscurve.h"
38#include "qgsregularpolygon.h"
39#include "qgsquadrilateral.h"
40#include "qgsvariantutils.h"
41#include "qgsogcutils.h"
42#include "qgsdistancearea.h"
43#include "qgsgeometryengine.h"
45#include "qgssymbollayerutils.h"
46#include "qgsstyle.h"
47#include "qgsexception.h"
48#include "qgsmessagelog.h"
49#include "qgsrasterlayer.h"
50#include "qgsvectorlayer.h"
51#include "qgsvectorlayerutils.h"
52#include "qgsrasterbandstats.h"
53#include "qgscolorramp.h"
55#include "qgsfieldformatter.h"
57#include "qgsproviderregistry.h"
58#include "sqlite3.h"
59#include "qgstransaction.h"
60#include "qgsthreadingutils.h"
61#include "qgsapplication.h"
62#include "qgis.h"
64#include "qgsunittypes.h"
65#include "qgsspatialindex.h"
66#include "qgscolorrampimpl.h"
67
68#include <QMimeDatabase>
69#include <QProcessEnvironment>
70#include <QCryptographicHash>
71#include <QRegularExpression>
72#include <QUuid>
73#include <QUrlQuery>
74
75typedef QList<QgsExpressionFunction *> ExpressionFunctionList;
76
78Q_GLOBAL_STATIC( QStringList, sBuiltinFunctions )
80
83Q_DECLARE_METATYPE( std::shared_ptr<QgsVectorLayer> )
84
85const QString QgsExpressionFunction::helpText() const
86{
87 return mHelpText.isEmpty() ? QgsExpression::helpText( mName ) : mHelpText;
88}
89
91{
92 Q_UNUSED( node )
93 // evaluate arguments
94 QVariantList argValues;
95 if ( args )
96 {
97 int arg = 0;
98 const QList< QgsExpressionNode * > argList = args->list();
99 for ( QgsExpressionNode *n : argList )
100 {
101 QVariant v;
102 if ( lazyEval() )
103 {
104 // Pass in the node for the function to eval as it needs.
105 v = QVariant::fromValue( n );
106 }
107 else
108 {
109 v = n->eval( parent, context );
111 bool defaultParamIsNull = mParameterList.count() > arg && mParameterList.at( arg ).optional() && !mParameterList.at( arg ).defaultValue().isValid();
112 if ( QgsExpressionUtils::isNull( v ) && !defaultParamIsNull && !handlesNull() )
113 return QVariant(); // all "normal" functions return NULL, when any QgsExpressionFunction::Parameter is NULL (so coalesce is abnormal)
114 }
115 argValues.append( v );
116 arg++;
117 }
118 }
119
120 return func( argValues, context, parent, node );
121}
122
124{
125 Q_UNUSED( node )
126 return true;
127}
128
130{
131 return QStringList();
132}
133
135{
136 Q_UNUSED( parent )
137 Q_UNUSED( context )
138 Q_UNUSED( node )
139 return false;
140}
141
143{
144 Q_UNUSED( parent )
145 Q_UNUSED( context )
146 Q_UNUSED( node )
147 return true;
148}
149
151{
152 Q_UNUSED( node )
153 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
154}
155
157{
158 return mGroups.isEmpty() ? false : mGroups.contains( QStringLiteral( "deprecated" ) );
159}
160
162{
163 return ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 );
164}
165
167{
168 return mHandlesNull;
169}
170
171// doxygen doesn't like this constructor for some reason (maybe the function arguments?)
174 FcnEval fcn,
175 const QString &group,
176 const QString &helpText,
177 const std::function < bool ( const QgsExpressionNodeFunction *node ) > &usesGeometry,
178 const std::function < QSet<QString>( const QgsExpressionNodeFunction *node ) > &referencedColumns,
179 bool lazyEval,
180 const QStringList &aliases,
181 bool handlesNull )
182 : QgsExpressionFunction( fnname, params, group, helpText, lazyEval, handlesNull, false )
183 , mFnc( fcn )
184 , mAliases( aliases )
185 , mUsesGeometry( false )
186 , mUsesGeometryFunc( usesGeometry )
187 , mReferencedColumnsFunc( referencedColumns )
188{
189}
191
193{
194 return mAliases;
195}
196
198{
199 if ( mUsesGeometryFunc )
200 return mUsesGeometryFunc( node );
201 else
202 return mUsesGeometry;
203}
204
205void QgsStaticExpressionFunction::setUsesGeometryFunction( const std::function<bool ( const QgsExpressionNodeFunction * )> &usesGeometry )
206{
207 mUsesGeometryFunc = usesGeometry;
208}
209
211{
212 if ( mReferencedColumnsFunc )
213 return mReferencedColumnsFunc( node );
214 else
215 return mReferencedColumns;
216}
217
219{
220 if ( mIsStaticFunc )
221 return mIsStaticFunc( node, parent, context );
222 else
223 return mIsStatic;
224}
225
227{
228 if ( mPrepareFunc )
229 return mPrepareFunc( node, parent, context );
230
231 return true;
232}
233
235{
236 mIsStaticFunc = isStatic;
237}
238
240{
241 mIsStaticFunc = nullptr;
242 mIsStatic = isStatic;
243}
244
245void QgsStaticExpressionFunction::setPrepareFunction( const std::function<bool ( const QgsExpressionNodeFunction *, QgsExpression *, const QgsExpressionContext * )> &prepareFunc )
246{
247 mPrepareFunc = prepareFunc;
248}
249
251{
252 if ( node && node->args() )
253 {
254 const QList< QgsExpressionNode * > argList = node->args()->list();
255 for ( QgsExpressionNode *argNode : argList )
256 {
257 if ( !argNode->isStatic( parent, context ) )
258 return false;
259 }
260 }
261
262 return true;
263}
264
265static QVariant fcnGenerateSeries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
266{
267 double start = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
268 double stop = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
269 double step = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
270
271 if ( step == 0.0 || ( step > 0.0 && start > stop ) || ( step < 0.0 && start < stop ) )
272 return QVariant();
273
274 QVariantList array;
275 int length = 1;
276
277 array << start;
278 double current = start + step;
279 while ( ( ( step > 0.0 && current <= stop ) || ( step < 0.0 && current >= stop ) ) && length <= 1000000 )
280 {
281 array << current;
282 current += step;
283 length++;
284 }
285
286 return array;
287}
288
289static QVariant fcnGetVariable( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
290{
291 if ( !context )
292 return QVariant();
293
294 const QString name = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
295
296 if ( name == QLatin1String( "feature" ) )
297 {
298 return context->hasFeature() ? QVariant::fromValue( context->feature() ) : QVariant();
299 }
300 else if ( name == QLatin1String( "id" ) )
301 {
302 return context->hasFeature() ? QVariant::fromValue( context->feature().id() ) : QVariant();
303 }
304 else if ( name == QLatin1String( "geometry" ) )
305 {
306 if ( !context->hasFeature() )
307 return QVariant();
308
309 const QgsFeature feature = context->feature();
310 return feature.hasGeometry() ? QVariant::fromValue( feature.geometry() ) : QVariant();
311 }
312 else
313 {
314 return context->variable( name );
315 }
316}
317
318static QVariant fcnEvalTemplate( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
319{
320 QString templateString = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
321 return QgsExpression::replaceExpressionText( templateString, context );
322}
323
324static QVariant fcnEval( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
325{
326 if ( !context )
327 return QVariant();
328
329 QString expString = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
330 QgsExpression expression( expString );
331 return expression.evaluate( context );
332}
333
334static QVariant fcnSqrt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
335{
336 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
337 return QVariant( std::sqrt( x ) );
338}
339
340static QVariant fcnAbs( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
341{
342 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
343 return QVariant( std::fabs( val ) );
344}
345
346static QVariant fcnRadians( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
347{
348 double deg = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
349 return ( deg * M_PI ) / 180;
350}
351static QVariant fcnDegrees( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
352{
353 double rad = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
354 return ( 180 * rad ) / M_PI;
355}
356static QVariant fcnSin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
357{
358 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
359 return QVariant( std::sin( x ) );
360}
361static QVariant fcnCos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
362{
363 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
364 return QVariant( std::cos( x ) );
365}
366static QVariant fcnTan( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
367{
368 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
369 return QVariant( std::tan( x ) );
370}
371static QVariant fcnAsin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
372{
373 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
374 return QVariant( std::asin( x ) );
375}
376static QVariant fcnAcos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
377{
378 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
379 return QVariant( std::acos( x ) );
380}
381static QVariant fcnAtan( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
382{
383 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
384 return QVariant( std::atan( x ) );
385}
386static QVariant fcnAtan2( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
387{
388 double y = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
389 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
390 return QVariant( std::atan2( y, x ) );
391}
392static QVariant fcnExp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
393{
394 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
395 return QVariant( std::exp( x ) );
396}
397static QVariant fcnLn( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
398{
399 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
400 if ( x <= 0 )
401 return QVariant();
402 return QVariant( std::log( x ) );
403}
404static QVariant fcnLog10( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
405{
406 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
407 if ( x <= 0 )
408 return QVariant();
409 return QVariant( log10( x ) );
410}
411static QVariant fcnLog( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
412{
413 double b = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
414 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
415 if ( x <= 0 || b <= 0 )
416 return QVariant();
417 return QVariant( std::log( x ) / std::log( b ) );
418}
419static QVariant fcnRndF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
420{
421 double min = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
422 double max = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
423 if ( max < min )
424 return QVariant();
425
426 std::random_device rd;
427 std::mt19937_64 generator( rd() );
428
429 if ( !QgsExpressionUtils::isNull( values.at( 2 ) ) )
430 {
431 quint32 seed;
432 if ( QgsExpressionUtils::isIntSafe( values.at( 2 ) ) )
433 {
434 // if seed can be converted to int, we use as is
435 seed = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
436 }
437 else
438 {
439 // if not, we hash string representation to int
440 QString seedStr = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
441 std::hash<std::string> hasher;
442 seed = hasher( seedStr.toStdString() );
443 }
444 generator.seed( seed );
445 }
446
447 // Return a random double in the range [min, max] (inclusive)
448 double f = static_cast< double >( generator() ) / static_cast< double >( std::mt19937_64::max() );
449 return QVariant( min + f * ( max - min ) );
450}
451static QVariant fcnRnd( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
452{
453 qlonglong min = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
454 qlonglong max = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
455 if ( max < min )
456 return QVariant();
457
458 std::random_device rd;
459 std::mt19937_64 generator( rd() );
460
461 if ( !QgsExpressionUtils::isNull( values.at( 2 ) ) )
462 {
463 quint32 seed;
464 if ( QgsExpressionUtils::isIntSafe( values.at( 2 ) ) )
465 {
466 // if seed can be converted to int, we use as is
467 seed = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
468 }
469 else
470 {
471 // if not, we hash string representation to int
472 QString seedStr = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
473 std::hash<std::string> hasher;
474 seed = hasher( seedStr.toStdString() );
475 }
476 generator.seed( seed );
477 }
478
479 qint64 randomInteger = min + ( generator() % ( max - min + 1 ) );
480 if ( randomInteger > std::numeric_limits<int>::max() || randomInteger < -std::numeric_limits<int>::max() )
481 return QVariant( randomInteger );
482
483 // Prevent wrong conversion of QVariant. See #36412
484 return QVariant( int( randomInteger ) );
485}
486
487static QVariant fcnLinearScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
488{
489 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
490 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
491 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
492 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
493 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
494
495 if ( domainMin >= domainMax )
496 {
497 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
498 return QVariant();
499 }
500
501 // outside of domain?
502 if ( val >= domainMax )
503 {
504 return rangeMax;
505 }
506 else if ( val <= domainMin )
507 {
508 return rangeMin;
509 }
510
511 // calculate linear scale
512 double m = ( rangeMax - rangeMin ) / ( domainMax - domainMin );
513 double c = rangeMin - ( domainMin * m );
514
515 // Return linearly scaled value
516 return QVariant( m * val + c );
517}
518
519static QVariant fcnPolynomialScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
520{
521 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
522 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
523 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
524 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
525 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
526 double exponent = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
527
528 if ( domainMin >= domainMax )
529 {
530 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
531 return QVariant();
532 }
533 if ( exponent <= 0 )
534 {
535 parent->setEvalErrorString( QObject::tr( "Exponent must be greater than 0" ) );
536 return QVariant();
537 }
538
539 // outside of domain?
540 if ( val >= domainMax )
541 {
542 return rangeMax;
543 }
544 else if ( val <= domainMin )
545 {
546 return rangeMin;
547 }
548
549 // Return polynomially scaled value
550 return QVariant( ( ( rangeMax - rangeMin ) / std::pow( domainMax - domainMin, exponent ) ) * std::pow( val - domainMin, exponent ) + rangeMin );
551}
552
553static QVariant fcnExponentialScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
554{
555 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
556 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
557 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
558 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
559 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
560 double exponent = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
561
562 if ( domainMin >= domainMax )
563 {
564 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
565 return QVariant();
566 }
567 if ( exponent <= 0 )
568 {
569 parent->setEvalErrorString( QObject::tr( "Exponent must be greater than 0" ) );
570 return QVariant();
571 }
572
573 // outside of domain?
574 if ( val >= domainMax )
575 {
576 return rangeMax;
577 }
578 else if ( val <= domainMin )
579 {
580 return rangeMin;
581 }
582
583 // Return exponentially scaled value
584 double ratio = ( std::pow( exponent, val - domainMin ) - 1 ) / ( std::pow( exponent, domainMax - domainMin ) - 1 );
585 return QVariant( ( rangeMax - rangeMin ) * ratio + rangeMin );
586}
587
588static QVariant fcnMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
589{
590 QVariant result = QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
591 double maxVal = std::numeric_limits<double>::quiet_NaN();
592 for ( const QVariant &val : values )
593 {
594 double testVal = QgsVariantUtils::isNull( val ) ? std::numeric_limits<double>::quiet_NaN() : QgsExpressionUtils::getDoubleValue( val, parent );
595 if ( std::isnan( maxVal ) )
596 {
597 maxVal = testVal;
598 }
599 else if ( !std::isnan( testVal ) )
600 {
601 maxVal = std::max( maxVal, testVal );
602 }
603 }
604
605 if ( !std::isnan( maxVal ) )
606 {
607 result = QVariant( maxVal );
608 }
609 return result;
610}
611
612static QVariant fcnMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
613{
614 QVariant result = QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
615 double minVal = std::numeric_limits<double>::quiet_NaN();
616 for ( const QVariant &val : values )
617 {
618 double testVal = QgsVariantUtils::isNull( val ) ? std::numeric_limits<double>::quiet_NaN() : QgsExpressionUtils::getDoubleValue( val, parent );
619 if ( std::isnan( minVal ) )
620 {
621 minVal = testVal;
622 }
623 else if ( !std::isnan( testVal ) )
624 {
625 minVal = std::min( minVal, testVal );
626 }
627 }
628
629 if ( !std::isnan( minVal ) )
630 {
631 result = QVariant( minVal );
632 }
633 return result;
634}
635
636static QVariant fcnAggregate( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
637{
638 //lazy eval, so we need to evaluate nodes now
639
640 //first node is layer id or name
641 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
643 QVariant value = node->eval( parent, context );
645
646 // TODO this expression function is NOT thread safe
648 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( value, context, parent );
650 if ( !vl )
651 {
652 parent->setEvalErrorString( QObject::tr( "Cannot find layer with name or ID '%1'" ).arg( value.toString() ) );
653 return QVariant();
654 }
655
656 // second node is aggregate type
657 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
659 value = node->eval( parent, context );
661 bool ok = false;
662 Qgis::Aggregate aggregate = QgsAggregateCalculator::stringToAggregate( QgsExpressionUtils::getStringValue( value, parent ), &ok );
663 if ( !ok )
664 {
665 parent->setEvalErrorString( QObject::tr( "No such aggregate '%1'" ).arg( value.toString() ) );
666 return QVariant();
667 }
668
669 // third node is subexpression (or field name)
670 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
672 QString subExpression = node->dump();
673
675 //optional forth node is filter
676 if ( values.count() > 3 )
677 {
678 node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
680 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
681 if ( !nl || nl->value().isValid() )
682 parameters.filter = node->dump();
683 }
684
685 //optional fifth node is concatenator
686 if ( values.count() > 4 )
687 {
688 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
690 value = node->eval( parent, context );
692 parameters.delimiter = value.toString();
693 }
694
695 //optional sixth node is order by
696 QString orderBy;
697 if ( values.count() > 5 )
698 {
699 node = QgsExpressionUtils::getNode( values.at( 5 ), parent );
701 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
702 if ( !nl || nl->value().isValid() )
703 {
704 orderBy = node->dump();
705 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
706 }
707 }
708
709 QString aggregateError;
710 QVariant result;
711 if ( context )
712 {
713 QString cacheKey;
714 QgsExpression subExp( subExpression );
715 QgsExpression filterExp( parameters.filter );
716
717 bool isStatic = true;
718 if ( filterExp.referencedVariables().contains( QStringLiteral( "parent" ) )
719 || filterExp.referencedVariables().contains( QString() )
720 || subExp.referencedVariables().contains( QStringLiteral( "parent" ) )
721 || subExp.referencedVariables().contains( QString() ) )
722 {
723 isStatic = false;
724 }
725 else
726 {
727
728 const QSet<QString> refVars = filterExp.referencedVariables() + subExp.referencedVariables();
729 for ( const QString &varName : refVars )
730 {
731 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
732 if ( scope && !scope->isStatic( varName ) )
733 {
734 isStatic = false;
735 break;
736 }
737 }
738 }
739
740 if ( isStatic && ! parameters.orderBy.isEmpty() )
741 {
742 for ( const auto &orderByClause : std::as_const( parameters.orderBy ) )
743 {
744 const QgsExpression &orderByExpression { orderByClause.expression() };
745 if ( orderByExpression.referencedVariables().contains( QStringLiteral( "parent" ) ) || orderByExpression.referencedVariables().contains( QString() ) )
746 {
747 isStatic = false;
748 break;
749 }
750 }
751 }
752
753 if ( !isStatic )
754 {
755 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5%6:%7" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter,
756 QString::number( context->feature().id() ), QString::number( qHash( context->feature() ) ), orderBy );
757 }
758 else
759 {
760 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter, orderBy );
761 }
762
763 if ( context->hasCachedValue( cacheKey ) )
764 {
765 return context->cachedValue( cacheKey );
766 }
767
768 QgsExpressionContext subContext( *context );
770 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
771 subContext.appendScope( subScope );
772 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &aggregateError );
773
774 if ( ok )
775 {
776 // important -- we should only store cached values when the expression is successfully calculated. Otherwise subsequent
777 // use of the expression context will happily grab the invalid QVariant cached value without realising that there was actually an error
778 // associated with it's calculation!
779 context->setCachedValue( cacheKey, result );
780 }
781 }
782 else
783 {
784 result = vl->aggregate( aggregate, subExpression, parameters, nullptr, &ok, nullptr, nullptr, &aggregateError );
785 }
786 if ( !ok )
787 {
788 if ( !aggregateError.isEmpty() )
789 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, aggregateError ) );
790 else
791 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
792 return QVariant();
793 }
794
795 return result;
796}
797
798static QVariant fcnAggregateRelation( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
799{
800 if ( !context )
801 {
802 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
803 return QVariant();
804 }
805
806 // first step - find current layer
807
808 // TODO this expression function is NOT thread safe
810 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
812 if ( !vl )
813 {
814 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
815 return QVariant();
816 }
817
818 //lazy eval, so we need to evaluate nodes now
819
820 //first node is relation name
821 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
823 QVariant value = node->eval( parent, context );
825 QString relationId = value.toString();
826 // check relation exists
827 QgsRelation relation = QgsProject::instance()->relationManager()->relation( relationId );
828 if ( !relation.isValid() || relation.referencedLayer() != vl )
829 {
830 // check for relations by name
831 QList< QgsRelation > relations = QgsProject::instance()->relationManager()->relationsByName( relationId );
832 if ( relations.isEmpty() || relations.at( 0 ).referencedLayer() != vl )
833 {
834 parent->setEvalErrorString( QObject::tr( "Cannot find relation with id '%1'" ).arg( relationId ) );
835 return QVariant();
836 }
837 else
838 {
839 relation = relations.at( 0 );
840 }
841 }
842
843 QgsVectorLayer *childLayer = relation.referencingLayer();
844
845 // second node is aggregate type
846 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
848 value = node->eval( parent, context );
850 bool ok = false;
851 Qgis::Aggregate aggregate = QgsAggregateCalculator::stringToAggregate( QgsExpressionUtils::getStringValue( value, parent ), &ok );
852 if ( !ok )
853 {
854 parent->setEvalErrorString( QObject::tr( "No such aggregate '%1'" ).arg( value.toString() ) );
855 return QVariant();
856 }
857
858 //third node is subexpression (or field name)
859 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
861 QString subExpression = node->dump();
862
863 //optional fourth node is concatenator
865 if ( values.count() > 3 )
866 {
867 node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
869 value = node->eval( parent, context );
871 parameters.delimiter = value.toString();
872 }
873
874 //optional fifth node is order by
875 QString orderBy;
876 if ( values.count() > 4 )
877 {
878 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
880 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
881 if ( !nl || nl->value().isValid() )
882 {
883 orderBy = node->dump();
884 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
885 }
886 }
887
888 if ( !context->hasFeature() )
889 return QVariant();
890 QgsFeature f = context->feature();
891
892 parameters.filter = relation.getRelatedFeaturesFilter( f );
893
894 QString cacheKey = QStringLiteral( "relagg:%1:%2:%3:%4:%5" ).arg( vl->id(),
895 QString::number( static_cast< int >( aggregate ) ),
896 subExpression,
897 parameters.filter,
898 orderBy );
899 if ( context->hasCachedValue( cacheKey ) )
900 return context->cachedValue( cacheKey );
901
902 QVariant result;
903 ok = false;
904
905
906 QgsExpressionContext subContext( *context );
907 QString error;
908 result = childLayer->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
909
910 if ( !ok )
911 {
912 if ( !error.isEmpty() )
913 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
914 else
915 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
916 return QVariant();
917 }
918
919 // cache value
920 context->setCachedValue( cacheKey, result );
921 return result;
922}
923
924
925static QVariant fcnAggregateGeneric( Qgis::Aggregate aggregate, const QVariantList &values, QgsAggregateCalculator::AggregateParameters parameters, const QgsExpressionContext *context, QgsExpression *parent, int orderByPos = -1 )
926{
927 if ( !context )
928 {
929 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
930 return QVariant();
931 }
932
933 // first step - find current layer
934
935 // TODO this expression function is NOT thread safe
937 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
939 if ( !vl )
940 {
941 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
942 return QVariant();
943 }
944
945 //lazy eval, so we need to evaluate nodes now
946
947 //first node is subexpression (or field name)
948 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
950 QString subExpression = node->dump();
951
952 //optional second node is group by
953 QString groupBy;
954 if ( values.count() > 1 )
955 {
956 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
958 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
959 if ( !nl || nl->value().isValid() )
960 groupBy = node->dump();
961 }
962
963 //optional third node is filter
964 if ( values.count() > 2 )
965 {
966 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
968 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
969 if ( !nl || nl->value().isValid() )
970 parameters.filter = node->dump();
971 }
972
973 //optional order by node, if supported
974 QString orderBy;
975 if ( orderByPos >= 0 && values.count() > orderByPos )
976 {
977 node = QgsExpressionUtils::getNode( values.at( orderByPos ), parent );
979 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
980 if ( !nl || nl->value().isValid() )
981 {
982 orderBy = node->dump();
983 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
984 }
985 }
986
987 // build up filter with group by
988
989 // find current group by value
990 if ( !groupBy.isEmpty() )
991 {
992 QgsExpression groupByExp( groupBy );
993 QVariant groupByValue = groupByExp.evaluate( context );
994 QString groupByClause = QStringLiteral( "%1 %2 %3" ).arg( groupBy,
995 QgsVariantUtils::isNull( groupByValue ) ? QStringLiteral( "is" ) : QStringLiteral( "=" ),
996 QgsExpression::quotedValue( groupByValue ) );
997 if ( !parameters.filter.isEmpty() )
998 parameters.filter = QStringLiteral( "(%1) AND (%2)" ).arg( parameters.filter, groupByClause );
999 else
1000 parameters.filter = groupByClause;
1001 }
1002
1003 QgsExpression subExp( subExpression );
1004 QgsExpression filterExp( parameters.filter );
1005
1006 bool isStatic = true;
1007 const QSet<QString> refVars = filterExp.referencedVariables() + subExp.referencedVariables();
1008 for ( const QString &varName : refVars )
1009 {
1010 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
1011 if ( scope && !scope->isStatic( varName ) )
1012 {
1013 isStatic = false;
1014 break;
1015 }
1016 }
1017
1018 QString cacheKey;
1019 if ( !isStatic )
1020 {
1021 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5%6:%7" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter,
1022 QString::number( context->feature().id() ), QString::number( qHash( context->feature() ) ), orderBy );
1023 }
1024 else
1025 {
1026 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter, orderBy );
1027 }
1028
1029 if ( context->hasCachedValue( cacheKey ) )
1030 return context->cachedValue( cacheKey );
1031
1032 QVariant result;
1033 bool ok = false;
1034
1035 QgsExpressionContext subContext( *context );
1037 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
1038 subContext.appendScope( subScope );
1039 QString error;
1040 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
1041
1042 if ( !ok )
1043 {
1044 if ( !error.isEmpty() )
1045 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
1046 else
1047 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
1048 return QVariant();
1049 }
1050
1051 // cache value
1052 context->setCachedValue( cacheKey, result );
1053 return result;
1054}
1055
1056
1057static QVariant fcnAggregateCount( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1058{
1059 return fcnAggregateGeneric( Qgis::Aggregate::Count, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1060}
1061
1062static QVariant fcnAggregateCountDistinct( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1063{
1064 return fcnAggregateGeneric( Qgis::Aggregate::CountDistinct, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1065}
1066
1067static QVariant fcnAggregateCountMissing( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1068{
1069 return fcnAggregateGeneric( Qgis::Aggregate::CountMissing, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1070}
1071
1072static QVariant fcnAggregateMin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1073{
1074 return fcnAggregateGeneric( Qgis::Aggregate::Min, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1075}
1076
1077static QVariant fcnAggregateMax( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1078{
1079 return fcnAggregateGeneric( Qgis::Aggregate::Max, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1080}
1081
1082static QVariant fcnAggregateSum( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1083{
1084 return fcnAggregateGeneric( Qgis::Aggregate::Sum, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1085}
1086
1087static QVariant fcnAggregateMean( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1088{
1089 return fcnAggregateGeneric( Qgis::Aggregate::Mean, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1090}
1091
1092static QVariant fcnAggregateMedian( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1093{
1094 return fcnAggregateGeneric( Qgis::Aggregate::Median, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1095}
1096
1097static QVariant fcnAggregateStdev( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1098{
1099 return fcnAggregateGeneric( Qgis::Aggregate::StDevSample, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1100}
1101
1102static QVariant fcnAggregateRange( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1103{
1104 return fcnAggregateGeneric( Qgis::Aggregate::Range, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1105}
1106
1107static QVariant fcnAggregateMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1108{
1109 return fcnAggregateGeneric( Qgis::Aggregate::Minority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1110}
1111
1112static QVariant fcnAggregateMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1113{
1114 return fcnAggregateGeneric( Qgis::Aggregate::Majority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1115}
1116
1117static QVariant fcnAggregateQ1( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1118{
1119 return fcnAggregateGeneric( Qgis::Aggregate::FirstQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1120}
1121
1122static QVariant fcnAggregateQ3( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1123{
1124 return fcnAggregateGeneric( Qgis::Aggregate::ThirdQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1125}
1126
1127static QVariant fcnAggregateIQR( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1128{
1129 return fcnAggregateGeneric( Qgis::Aggregate::InterQuartileRange, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1130}
1131
1132static QVariant fcnAggregateMinLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1133{
1134 return fcnAggregateGeneric( Qgis::Aggregate::StringMinimumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1135}
1136
1137static QVariant fcnAggregateMaxLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1138{
1139 return fcnAggregateGeneric( Qgis::Aggregate::StringMaximumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1140}
1141
1142static QVariant fcnAggregateCollectGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1143{
1144 return fcnAggregateGeneric( Qgis::Aggregate::GeometryCollect, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1145}
1146
1147static QVariant fcnAggregateStringConcat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1148{
1150
1151 //fourth node is concatenator
1152 if ( values.count() > 3 )
1153 {
1154 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1156 QVariant value = node->eval( parent, context );
1158 parameters.delimiter = value.toString();
1159 }
1160
1161 return fcnAggregateGeneric( Qgis::Aggregate::StringConcatenate, values, parameters, context, parent, 4 );
1162}
1163
1164static QVariant fcnAggregateStringConcatUnique( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1165{
1167
1168 //fourth node is concatenator
1169 if ( values.count() > 3 )
1170 {
1171 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1173 QVariant value = node->eval( parent, context );
1175 parameters.delimiter = value.toString();
1176 }
1177
1178 return fcnAggregateGeneric( Qgis::Aggregate::StringConcatenateUnique, values, parameters, context, parent, 4 );
1179}
1180
1181static QVariant fcnAggregateArray( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1182{
1183 return fcnAggregateGeneric( Qgis::Aggregate::ArrayAggregate, values, QgsAggregateCalculator::AggregateParameters(), context, parent, 3 );
1184}
1185
1186static QVariant fcnMapScale( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1187{
1188 if ( !context )
1189 return QVariant();
1190
1191 QVariant scale = context->variable( QStringLiteral( "map_scale" ) );
1192 bool ok = false;
1193 if ( QgsVariantUtils::isNull( scale ) )
1194 return QVariant();
1195
1196 const double v = scale.toDouble( &ok );
1197 if ( ok )
1198 return v;
1199 return QVariant();
1200}
1201
1202static QVariant fcnClamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1203{
1204 double minValue = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1205 double testValue = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1206 double maxValue = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1207
1208 // force testValue to sit inside the range specified by the min and max value
1209 if ( testValue <= minValue )
1210 {
1211 return QVariant( minValue );
1212 }
1213 else if ( testValue >= maxValue )
1214 {
1215 return QVariant( maxValue );
1216 }
1217 else
1218 {
1219 return QVariant( testValue );
1220 }
1221}
1222
1223static QVariant fcnFloor( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1224{
1225 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1226 return QVariant( std::floor( x ) );
1227}
1228
1229static QVariant fcnCeil( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1230{
1231 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1232 return QVariant( std::ceil( x ) );
1233}
1234
1235static QVariant fcnToInt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1236{
1237 return QVariant( QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) );
1238}
1239static QVariant fcnToReal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1240{
1241 return QVariant( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) );
1242}
1243static QVariant fcnToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1244{
1245 return QVariant( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ) );
1246}
1247
1248static QVariant fcnToDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1249{
1250 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1251 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1252 if ( format.isEmpty() && !language.isEmpty() )
1253 {
1254 parent->setEvalErrorString( QObject::tr( "A format is required to convert to DateTime when the language is specified" ) );
1255 return QVariant( QDateTime() );
1256 }
1257
1258 if ( format.isEmpty() && language.isEmpty() )
1259 return QVariant( QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent ) );
1260
1261 QString datetimestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1262 QLocale locale = QLocale();
1263 if ( !language.isEmpty() )
1264 {
1265 locale = QLocale( language );
1266 }
1267
1268 QDateTime datetime = locale.toDateTime( datetimestring, format );
1269 if ( !datetime.isValid() )
1270 {
1271 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to DateTime" ).arg( datetimestring ) );
1272 datetime = QDateTime();
1273 }
1274 return QVariant( datetime );
1275}
1276
1277static QVariant fcnMakeDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1278{
1279 const int year = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1280 const int month = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1281 const int day = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
1282
1283 const QDate date( year, month, day );
1284 if ( !date.isValid() )
1285 {
1286 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1287 return QVariant();
1288 }
1289 return QVariant( date );
1290}
1291
1292static QVariant fcnMakeTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1293{
1294 const int hours = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1295 const int minutes = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1296 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1297
1298 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1299 if ( !time.isValid() )
1300 {
1301 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1302 return QVariant();
1303 }
1304 return QVariant( time );
1305}
1306
1307static QVariant fcnMakeDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1308{
1309 const int year = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1310 const int month = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1311 const int day = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
1312 const int hours = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
1313 const int minutes = QgsExpressionUtils::getIntValue( values.at( 4 ), parent );
1314 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1315
1316 const QDate date( year, month, day );
1317 if ( !date.isValid() )
1318 {
1319 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1320 return QVariant();
1321 }
1322 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1323 if ( !time.isValid() )
1324 {
1325 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1326 return QVariant();
1327 }
1328 return QVariant( QDateTime( date, time ) );
1329}
1330
1331static QVariant fcnMakeInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1332{
1333 const double years = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1334 const double months = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1335 const double weeks = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1336 const double days = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
1337 const double hours = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
1338 const double minutes = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1339 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
1340
1341 return QVariant::fromValue( QgsInterval( years, months, weeks, days, hours, minutes, seconds ) );
1342}
1343
1344static QVariant fcnCoalesce( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1345{
1346 for ( const QVariant &value : values )
1347 {
1348 if ( QgsVariantUtils::isNull( value ) )
1349 continue;
1350 return value;
1351 }
1352 return QVariant();
1353}
1354
1355static QVariant fcnNullIf( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1356{
1357 const QVariant val1 = values.at( 0 );
1358 const QVariant val2 = values.at( 1 );
1359
1360 if ( val1 == val2 )
1361 return QVariant();
1362 else
1363 return val1;
1364}
1365
1366static QVariant fcnLower( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1367{
1368 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1369 return QVariant( str.toLower() );
1370}
1371static QVariant fcnUpper( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1372{
1373 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1374 return QVariant( str.toUpper() );
1375}
1376static QVariant fcnTitle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1377{
1378 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1379 QStringList elems = str.split( ' ' );
1380 for ( int i = 0; i < elems.size(); i++ )
1381 {
1382 if ( elems[i].size() > 1 )
1383 elems[i] = elems[i].at( 0 ).toUpper() + elems[i].mid( 1 ).toLower();
1384 }
1385 return QVariant( elems.join( QLatin1Char( ' ' ) ) );
1386}
1387
1388static QVariant fcnTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1389{
1390 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1391 return QVariant( str.trimmed() );
1392}
1393
1394static QVariant fcnLTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1395{
1396 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1397
1398 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1399
1400 const QRegularExpression re( QStringLiteral( "^([%1]*)" ).arg( QRegularExpression::escape( characters ) ) );
1401 str.replace( re, QString() );
1402 return QVariant( str );
1403}
1404
1405static QVariant fcnRTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1406{
1407 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1408
1409 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1410
1411 const QRegularExpression re( QStringLiteral( "([%1]*)$" ).arg( QRegularExpression::escape( characters ) ) );
1412 str.replace( re, QString() );
1413 return QVariant( str );
1414}
1415
1416static QVariant fcnLevenshtein( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1417{
1418 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1419 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1420 return QVariant( QgsStringUtils::levenshteinDistance( string1, string2, true ) );
1421}
1422
1423static QVariant fcnLCS( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1424{
1425 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1426 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1427 return QVariant( QgsStringUtils::longestCommonSubstring( string1, string2, true ) );
1428}
1429
1430static QVariant fcnHamming( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1431{
1432 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1433 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1434 int dist = QgsStringUtils::hammingDistance( string1, string2 );
1435 return ( dist < 0 ? QVariant() : QVariant( QgsStringUtils::hammingDistance( string1, string2, true ) ) );
1436}
1437
1438static QVariant fcnSoundex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1439{
1440 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1441 return QVariant( QgsStringUtils::soundex( string ) );
1442}
1443
1444static QVariant fcnChar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1445{
1446 QChar character = QChar( QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent ) );
1447 return QVariant( QString( character ) );
1448}
1449
1450static QVariant fcnAscii( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1451{
1452 QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1453
1454 if ( value.isEmpty() )
1455 {
1456 return QVariant();
1457 }
1458
1459 int res = value.at( 0 ).unicode();
1460 return QVariant( res );
1461}
1462
1463static QVariant fcnWordwrap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1464{
1465 if ( values.length() == 2 || values.length() == 3 )
1466 {
1467 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1468 qlonglong wrap = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1469
1470 QString customdelimiter = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1471
1472 return QgsStringUtils::wordWrap( str, static_cast< int >( wrap ), wrap > 0, customdelimiter );
1473 }
1474
1475 return QVariant();
1476}
1477
1478static QVariant fcnLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1479{
1480 // two variants, one for geometry, one for string
1481 if ( values.at( 0 ).userType() == QMetaType::type( "QgsGeometry" ) )
1482 {
1483 //geometry variant
1484 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
1485 if ( geom.type() != Qgis::GeometryType::Line )
1486 return QVariant();
1487
1488 return QVariant( geom.length() );
1489 }
1490
1491 //otherwise fall back to string variant
1492 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1493 return QVariant( str.length() );
1494}
1495
1496static QVariant fcnLength3D( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1497{
1498 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
1499
1500 if ( geom.type() != Qgis::GeometryType::Line )
1501 return QVariant();
1502
1503 double totalLength = 0;
1504 for ( auto it = geom.const_parts_begin(); it != geom.const_parts_end(); ++it )
1505 {
1506 if ( const QgsLineString *line = qgsgeometry_cast< const QgsLineString * >( *it ) )
1507 {
1508 totalLength += line->length3D();
1509 }
1510 else
1511 {
1512 std::unique_ptr< QgsLineString > segmentized( qgsgeometry_cast< const QgsCurve * >( *it )->curveToLine() );
1513 totalLength += segmentized->length3D();
1514 }
1515 }
1516
1517 return totalLength;
1518}
1519
1520static QVariant fcnReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1521{
1522 if ( values.count() == 2 && values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
1523 {
1524 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1525 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
1526 QVector< QPair< QString, QString > > mapItems;
1527
1528 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
1529 {
1530 mapItems.append( qMakePair( it.key(), it.value().toString() ) );
1531 }
1532
1533 // larger keys should be replaced first since they may contain whole smaller keys
1534 std::sort( mapItems.begin(),
1535 mapItems.end(),
1536 []( const QPair< QString, QString > &pair1,
1537 const QPair< QString, QString > &pair2 )
1538 {
1539 return ( pair1.first.length() > pair2.first.length() );
1540 } );
1541
1542 for ( auto it = mapItems.constBegin(); it != mapItems.constEnd(); ++it )
1543 {
1544 str = str.replace( it->first, it->second );
1545 }
1546
1547 return QVariant( str );
1548 }
1549 else if ( values.count() == 3 )
1550 {
1551 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1552 QVariantList before;
1553 QVariantList after;
1554 bool isSingleReplacement = false;
1555
1556 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).userType() != QMetaType::Type::QStringList )
1557 {
1558 before = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1559 }
1560 else
1561 {
1562 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
1563 }
1564
1565 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
1566 {
1567 after = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1568 isSingleReplacement = true;
1569 }
1570 else
1571 {
1572 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
1573 }
1574
1575 if ( !isSingleReplacement && before.length() != after.length() )
1576 {
1577 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
1578 return QVariant();
1579 }
1580
1581 for ( int i = 0; i < before.length(); i++ )
1582 {
1583 str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() );
1584 }
1585
1586 return QVariant( str );
1587 }
1588 else
1589 {
1590 parent->setEvalErrorString( QObject::tr( "Function replace requires 2 or 3 arguments" ) );
1591 return QVariant();
1592 }
1593}
1594
1595static QVariant fcnRegexpReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1596{
1597 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1598 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1599 QString after = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1600
1601 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1602 if ( !re.isValid() )
1603 {
1604 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1605 return QVariant();
1606 }
1607 return QVariant( str.replace( re, after ) );
1608}
1609
1610static QVariant fcnRegexpMatch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1611{
1612 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1613 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1614
1615 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1616 if ( !re.isValid() )
1617 {
1618 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1619 return QVariant();
1620 }
1621 return QVariant( ( str.indexOf( re ) + 1 ) );
1622}
1623
1624static QVariant fcnRegexpMatches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1625{
1626 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1627 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1628 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1629
1630 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1631 if ( !re.isValid() )
1632 {
1633 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1634 return QVariant();
1635 }
1636
1637 QRegularExpressionMatch matches = re.match( str );
1638 if ( matches.hasMatch() )
1639 {
1640 QVariantList array;
1641 QStringList list = matches.capturedTexts();
1642
1643 // Skip the first string to only return captured groups
1644 for ( QStringList::const_iterator it = ++list.constBegin(); it != list.constEnd(); ++it )
1645 {
1646 array += ( !( *it ).isEmpty() ) ? *it : empty;
1647 }
1648
1649 return QVariant( array );
1650 }
1651 else
1652 {
1653 return QVariant();
1654 }
1655}
1656
1657static QVariant fcnRegexpSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1658{
1659 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1660 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1661
1662 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1663 if ( !re.isValid() )
1664 {
1665 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1666 return QVariant();
1667 }
1668
1669 // extract substring
1670 QRegularExpressionMatch match = re.match( str );
1671 if ( match.hasMatch() )
1672 {
1673 // return first capture
1674 if ( match.lastCapturedIndex() > 0 )
1675 {
1676 // a capture group was present, so use that
1677 return QVariant( match.captured( 1 ) );
1678 }
1679 else
1680 {
1681 // no capture group, so using all match
1682 return QVariant( match.captured( 0 ) );
1683 }
1684 }
1685 else
1686 {
1687 return QVariant( "" );
1688 }
1689}
1690
1691static QVariant fcnUuid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1692{
1693 QString uuid = QUuid::createUuid().toString();
1694 if ( values.at( 0 ).toString().compare( QStringLiteral( "WithoutBraces" ), Qt::CaseInsensitive ) == 0 )
1695 uuid = QUuid::createUuid().toString( QUuid::StringFormat::WithoutBraces );
1696 else if ( values.at( 0 ).toString().compare( QStringLiteral( "Id128" ), Qt::CaseInsensitive ) == 0 )
1697 uuid = QUuid::createUuid().toString( QUuid::StringFormat::Id128 );
1698 return uuid;
1699}
1700
1701static QVariant fcnSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1702{
1703 if ( !values.at( 0 ).isValid() || !values.at( 1 ).isValid() )
1704 return QVariant();
1705
1706 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1707 int from = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1708
1709 int len = 0;
1710 if ( values.at( 2 ).isValid() )
1711 len = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
1712 else
1713 len = str.size();
1714
1715 if ( from < 0 )
1716 {
1717 from = str.size() + from;
1718 if ( from < 0 )
1719 {
1720 from = 0;
1721 }
1722 }
1723 else if ( from > 0 )
1724 {
1725 //account for the fact that substr() starts at 1
1726 from -= 1;
1727 }
1728
1729 if ( len < 0 )
1730 {
1731 len = str.size() + len - from;
1732 if ( len < 0 )
1733 {
1734 len = 0;
1735 }
1736 }
1737
1738 return QVariant( str.mid( from, len ) );
1739}
1740static QVariant fcnFeatureId( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1741{
1742 FEAT_FROM_CONTEXT( context, f )
1743 // TODO: handling of 64-bit feature ids?
1744 return QVariant( static_cast< int >( f.id() ) );
1745}
1746
1747static QVariant fcnRasterValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1748{
1749 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1750 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
1751 bool foundLayer = false;
1752 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, geom]( QgsMapLayer * mapLayer )
1753 {
1754 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer * >( mapLayer );
1755 if ( !layer || !layer->dataProvider() )
1756 {
1757 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1758 return QVariant();
1759 }
1760
1761 if ( bandNb < 1 || bandNb > layer->bandCount() )
1762 {
1763 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster band number." ) );
1764 return QVariant();
1765 }
1766
1767 if ( geom.isNull() || geom.type() != Qgis::GeometryType::Point )
1768 {
1769 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid point geometry." ) );
1770 return QVariant();
1771 }
1772
1773 QgsPointXY point = geom.asPoint();
1774 if ( geom.isMultipart() )
1775 {
1776 QgsMultiPointXY multiPoint = geom.asMultiPoint();
1777 if ( multiPoint.count() == 1 )
1778 {
1779 point = multiPoint[0];
1780 }
1781 else
1782 {
1783 // if the geometry contains more than one part, return an undefined value
1784 return QVariant();
1785 }
1786 }
1787
1788 double value = layer->dataProvider()->sample( point, bandNb );
1789 return std::isnan( value ) ? QVariant() : value;
1790 },
1791 foundLayer );
1792
1793 if ( !foundLayer )
1794 {
1795 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1796 return QVariant();
1797 }
1798 else
1799 {
1800 return res;
1801 }
1802}
1803
1804static QVariant fcnRasterAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1805{
1806 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1807 const double value = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1808
1809 bool foundLayer = false;
1810 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, value]( QgsMapLayer * mapLayer )-> QVariant
1811 {
1812 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer *>( mapLayer );
1813 if ( !layer || !layer->dataProvider() )
1814 {
1815 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1816 return QVariant();
1817 }
1818
1819 if ( bandNb < 1 || bandNb > layer->bandCount() )
1820 {
1821 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster band number." ) );
1822 return QVariant();
1823 }
1824
1825 if ( std::isnan( value ) )
1826 {
1827 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster value." ) );
1828 return QVariant();
1829 }
1830
1831 if ( ! layer->dataProvider()->attributeTable( bandNb ) )
1832 {
1833 return QVariant();
1834 }
1835
1836 const QVariantList data = layer->dataProvider()->attributeTable( bandNb )->row( value );
1837 if ( data.isEmpty() )
1838 {
1839 return QVariant();
1840 }
1841
1842 QVariantMap result;
1843 const QList<QgsRasterAttributeTable::Field> fields { layer->dataProvider()->attributeTable( bandNb )->fields() };
1844 for ( int idx = 0; idx < static_cast<int>( fields.count( ) ) && idx < static_cast<int>( data.count() ); ++idx )
1845 {
1846 const QgsRasterAttributeTable::Field field { fields.at( idx ) };
1847 if ( field.isColor() || field.isRamp() )
1848 {
1849 continue;
1850 }
1851 result.insert( fields.at( idx ).name, data.at( idx ) );
1852 }
1853
1854 return result;
1855 }, foundLayer );
1856
1857 if ( !foundLayer )
1858 {
1859 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1860 return QVariant();
1861 }
1862 else
1863 {
1864 return res;
1865 }
1866}
1867
1868static QVariant fcnFeature( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1869{
1870 if ( !context )
1871 return QVariant();
1872
1873 return context->feature();
1874}
1875
1876static QVariant fcnAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1877{
1878 QgsFeature feature;
1879 QString attr;
1880 if ( values.size() == 1 )
1881 {
1882 attr = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1883 feature = context->feature();
1884 }
1885 else if ( values.size() == 2 )
1886 {
1887 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
1888 attr = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1889 }
1890 else
1891 {
1892 parent->setEvalErrorString( QObject::tr( "Function `attribute` requires one or two parameters. %n given.", nullptr, values.length() ) );
1893 return QVariant();
1894 }
1895
1896 return feature.attribute( attr );
1897}
1898
1899static QVariant fcnMapToHtmlTable( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1900{
1901 QString table { R"html(
1902 <table>
1903 <thead>
1904 <tr><th>%1</th></tr>
1905 </thead>
1906 <tbody>
1907 <tr><td>%2</td></tr>
1908 </tbody>
1909 </table>)html" };
1910 QVariantMap dict;
1911 if ( values.size() == 1 )
1912 {
1913 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1914 }
1915 else
1916 {
1917 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_table` requires one parameter. %n given.", nullptr, values.length() ) );
1918 return QVariant();
1919 }
1920
1921 if ( dict.isEmpty() )
1922 {
1923 return QVariant();
1924 }
1925
1926 QStringList headers;
1927 QStringList cells;
1928
1929 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1930 {
1931 headers.push_back( it.key().toHtmlEscaped() );
1932 cells.push_back( it.value().toString( ).toHtmlEscaped() );
1933 }
1934
1935 return table.arg( headers.join( QLatin1String( "</th><th>" ) ), cells.join( QLatin1String( "</td><td>" ) ) );
1936}
1937
1938static QVariant fcnMapToHtmlDefinitionList( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1939{
1940 QString table { R"html(
1941 <dl>
1942 %1
1943 </dl>)html" };
1944 QVariantMap dict;
1945 if ( values.size() == 1 )
1946 {
1947 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1948 }
1949 else
1950 {
1951 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_dl` requires one parameter. %n given.", nullptr, values.length() ) );
1952 return QVariant();
1953 }
1954
1955 if ( dict.isEmpty() )
1956 {
1957 return QVariant();
1958 }
1959
1960 QString rows;
1961
1962 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1963 {
1964 rows.append( QStringLiteral( "<dt>%1</dt><dd>%2</dd>" ).arg( it.key().toHtmlEscaped(), it.value().toString().toHtmlEscaped() ) );
1965 }
1966
1967 return table.arg( rows );
1968}
1969
1970static QVariant fcnValidateFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1971{
1972 QVariant layer;
1973 if ( values.size() < 1 || QgsVariantUtils::isNull( values.at( 0 ) ) )
1974 {
1975 layer = context->variable( QStringLiteral( "layer" ) );
1976 }
1977 else
1978 {
1979 //first node is layer id or name
1980 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
1982 layer = node->eval( parent, context );
1984 }
1985
1986 QgsFeature feature;
1987 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
1988 {
1989 feature = context->feature();
1990 }
1991 else
1992 {
1993 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
1994 }
1995
1997 const QString strength = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).toLower();
1998 if ( strength == QLatin1String( "hard" ) )
1999 {
2001 }
2002 else if ( strength == QLatin1String( "soft" ) )
2003 {
2005 }
2006
2007 bool foundLayer = false;
2008 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
2009 {
2010 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2011 if ( !layer )
2012 {
2013 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2014 return QVariant();
2015 }
2016
2017 const QgsFields fields = layer->fields();
2018 bool valid = true;
2019 for ( int i = 0; i < fields.size(); i++ )
2020 {
2021 QStringList errors;
2022 valid = QgsVectorLayerUtils::validateAttribute( layer, feature, i, errors, constraintStrength );
2023 if ( !valid )
2024 {
2025 break;
2026 }
2027 }
2028
2029 return valid;
2030 }, foundLayer );
2031
2032 if ( !foundLayer )
2033 {
2034 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2035 return QVariant();
2036 }
2037
2038 return res;
2039}
2040
2041static QVariant fcnValidateAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2042{
2043 QVariant layer;
2044 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
2045 {
2046 layer = context->variable( QStringLiteral( "layer" ) );
2047 }
2048 else
2049 {
2050 //first node is layer id or name
2051 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
2053 layer = node->eval( parent, context );
2055 }
2056
2057 QgsFeature feature;
2058 if ( values.size() < 3 || QgsVariantUtils::isNull( values.at( 2 ) ) )
2059 {
2060 feature = context->feature();
2061 }
2062 else
2063 {
2064 feature = QgsExpressionUtils::getFeature( values.at( 2 ), parent );
2065 }
2066
2068 const QString strength = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).toLower();
2069 if ( strength == QLatin1String( "hard" ) )
2070 {
2072 }
2073 else if ( strength == QLatin1String( "soft" ) )
2074 {
2076 }
2077
2078 const QString attributeName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2079
2080 bool foundLayer = false;
2081 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, attributeName, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
2082 {
2083 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2084 if ( !layer )
2085 {
2086 return QVariant();
2087 }
2088
2089 const int fieldIndex = layer->fields().indexFromName( attributeName );
2090 if ( fieldIndex == -1 )
2091 {
2092 parent->setEvalErrorString( QObject::tr( "The attribute name did not match any field for the given feature" ) );
2093 return QVariant();
2094 }
2095
2096 QStringList errors;
2097 bool valid = QgsVectorLayerUtils::validateAttribute( layer, feature, fieldIndex, errors, constraintStrength );
2098 return valid;
2099 }, foundLayer );
2100
2101 if ( !foundLayer )
2102 {
2103 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2104 return QVariant();
2105 }
2106
2107 return res;
2108}
2109
2110static QVariant fcnAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2111{
2112 QgsFeature feature;
2113 if ( values.size() == 0 || QgsVariantUtils::isNull( values.at( 0 ) ) )
2114 {
2115 feature = context->feature();
2116 }
2117 else
2118 {
2119 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2120 }
2121
2122 const QgsFields fields = feature.fields();
2123 QVariantMap result;
2124 for ( int i = 0; i < fields.count(); ++i )
2125 {
2126 result.insert( fields.at( i ).name(), feature.attribute( i ) );
2127 }
2128 return result;
2129}
2130
2131static QVariant fcnRepresentAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2132{
2133 QgsVectorLayer *layer = nullptr;
2134 QgsFeature feature;
2135
2136 // TODO this expression function is NOT thread safe
2138 if ( values.isEmpty() )
2139 {
2140 feature = context->feature();
2141 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2142 }
2143 else if ( values.size() == 1 )
2144 {
2145 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2146 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2147 }
2148 else if ( values.size() == 2 )
2149 {
2150 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2151 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2152 }
2153 else
2154 {
2155 parent->setEvalErrorString( QObject::tr( "Function `represent_attributes` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2156 return QVariant();
2157 }
2159
2160 if ( !layer )
2161 {
2162 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: layer could not be resolved." ) );
2163 return QVariant();
2164 }
2165
2166 if ( !feature.isValid() )
2167 {
2168 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: feature could not be resolved." ) );
2169 return QVariant();
2170 }
2171
2172 const QgsFields fields = feature.fields();
2173 QVariantMap result;
2174 for ( int fieldIndex = 0; fieldIndex < fields.count(); ++fieldIndex )
2175 {
2176 const QString fieldName { fields.at( fieldIndex ).name() };
2177 const QVariant attributeVal = feature.attribute( fieldIndex );
2178 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer->id(), fieldName, attributeVal.toString() );
2179 if ( context && context->hasCachedValue( cacheValueKey ) )
2180 {
2181 result.insert( fieldName, context->cachedValue( cacheValueKey ) );
2182 }
2183 else
2184 {
2185 const QgsEditorWidgetSetup setup = layer->editorWidgetSetup( fieldIndex );
2187 QVariant cache;
2188 if ( context )
2189 {
2190 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer->id(), fieldName );
2191
2192 if ( !context->hasCachedValue( cacheKey ) )
2193 {
2194 cache = fieldFormatter->createCache( layer, fieldIndex, setup.config() );
2195 context->setCachedValue( cacheKey, cache );
2196 }
2197 else
2198 {
2199 cache = context->cachedValue( cacheKey );
2200 }
2201 }
2202 QString value( fieldFormatter->representValue( layer, fieldIndex, setup.config(), cache, attributeVal ) );
2203
2204 result.insert( fields.at( fieldIndex ).name(), value );
2205
2206 if ( context )
2207 {
2208 context->setCachedValue( cacheValueKey, value );
2209 }
2210
2211 }
2212 }
2213 return result;
2214}
2215
2216static QVariant fcnCoreFeatureMaptipDisplay( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const bool isMaptip )
2217{
2218 QgsVectorLayer *layer = nullptr;
2219 QgsFeature feature;
2220 bool evaluate = true;
2221
2222 // TODO this expression function is NOT thread safe
2224 if ( values.isEmpty() )
2225 {
2226 feature = context->feature();
2227 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2228 }
2229 else if ( values.size() == 1 )
2230 {
2231 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2232 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2233 }
2234 else if ( values.size() == 2 )
2235 {
2236 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2237 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2238 }
2239 else if ( values.size() == 3 )
2240 {
2241 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2242 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2243 evaluate = values.value( 2 ).toBool();
2244 }
2245 else
2246 {
2247 if ( isMaptip )
2248 {
2249 parent->setEvalErrorString( QObject::tr( "Function `maptip` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2250 }
2251 else
2252 {
2253 parent->setEvalErrorString( QObject::tr( "Function `display` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2254 }
2255 return QVariant();
2256 }
2257
2258 if ( !layer )
2259 {
2260 parent->setEvalErrorString( QObject::tr( "The layer is not valid." ) );
2261 return QVariant( );
2262 }
2264
2265 if ( !feature.isValid() )
2266 {
2267 parent->setEvalErrorString( QObject::tr( "The feature is not valid." ) );
2268 return QVariant( );
2269 }
2270
2271 if ( ! evaluate )
2272 {
2273 if ( isMaptip )
2274 {
2275 return layer->mapTipTemplate();
2276 }
2277 else
2278 {
2279 return layer->displayExpression();
2280 }
2281 }
2282
2283 QgsExpressionContext subContext( *context );
2284 subContext.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( layer ) );
2285 subContext.setFeature( feature );
2286
2287 if ( isMaptip )
2288 {
2289 return QgsExpression::replaceExpressionText( layer->mapTipTemplate(), &subContext );
2290 }
2291 else
2292 {
2293 QgsExpression exp( layer->displayExpression() );
2294 exp.prepare( &subContext );
2295 return exp.evaluate( &subContext ).toString();
2296 }
2297}
2298
2299static QVariant fcnFeatureDisplayExpression( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2300{
2301 return fcnCoreFeatureMaptipDisplay( values, context, parent, false );
2302}
2303
2304static QVariant fcnFeatureMaptip( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2305{
2306 return fcnCoreFeatureMaptipDisplay( values, context, parent, true );
2307}
2308
2309static QVariant fcnIsSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2310{
2311 QgsFeature feature;
2312 QVariant layer;
2313 if ( values.isEmpty() )
2314 {
2315 feature = context->feature();
2316 layer = context->variable( QStringLiteral( "layer" ) );
2317 }
2318 else if ( values.size() == 1 )
2319 {
2320 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2321 layer = context->variable( QStringLiteral( "layer" ) );
2322 }
2323 else if ( values.size() == 2 )
2324 {
2325 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2326 layer = values.at( 0 );
2327 }
2328 else
2329 {
2330 parent->setEvalErrorString( QObject::tr( "Function `is_selected` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2331 return QVariant();
2332 }
2333
2334 bool foundLayer = false;
2335 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [feature]( QgsMapLayer * mapLayer ) -> QVariant
2336 {
2337 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2338 if ( !layer || !feature.isValid() )
2339 {
2340 return QgsVariantUtils::createNullVariant( QMetaType::Type::Bool );
2341 }
2342
2343 return layer->selectedFeatureIds().contains( feature.id() );
2344 }, foundLayer );
2345 if ( !foundLayer )
2346 return QgsVariantUtils::createNullVariant( QMetaType::Type::Bool );
2347 else
2348 return res;
2349}
2350
2351static QVariant fcnNumSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2352{
2353 QVariant layer;
2354
2355 if ( values.isEmpty() )
2356 layer = context->variable( QStringLiteral( "layer" ) );
2357 else if ( values.count() == 1 )
2358 layer = values.at( 0 );
2359 else
2360 {
2361 parent->setEvalErrorString( QObject::tr( "Function `num_selected` requires no more than one parameter. %n given.", nullptr, values.length() ) );
2362 return QVariant();
2363 }
2364
2365 bool foundLayer = false;
2366 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, []( QgsMapLayer * mapLayer ) -> QVariant
2367 {
2368 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2369 if ( !layer )
2370 {
2371 return QgsVariantUtils::createNullVariant( QMetaType::Type::LongLong );
2372 }
2373
2374 return layer->selectedFeatureCount();
2375 }, foundLayer );
2376 if ( !foundLayer )
2377 return QgsVariantUtils::createNullVariant( QMetaType::Type::LongLong );
2378 else
2379 return res;
2380}
2381
2382static QVariant fcnSqliteFetchAndIncrement( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2383{
2384 static QMap<QString, qlonglong> counterCache;
2385 QVariant functionResult;
2386
2387 auto fetchAndIncrementFunc = [ values, parent, &functionResult ]( QgsMapLayer * mapLayer, const QString & databaseArgument )
2388 {
2389 QString database;
2390
2391 const QgsVectorLayer *layer = qobject_cast< QgsVectorLayer *>( mapLayer );
2392
2393 if ( layer )
2394 {
2395 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
2396 database = decodedUri.value( QStringLiteral( "path" ) ).toString();
2397 if ( database.isEmpty() )
2398 {
2399 parent->setEvalErrorString( QObject::tr( "Could not extract file path from layer `%1`." ).arg( layer->name() ) );
2400 }
2401 }
2402 else
2403 {
2404 database = databaseArgument;
2405 }
2406
2407 const QString table = values.at( 1 ).toString();
2408 const QString idColumn = values.at( 2 ).toString();
2409 const QString filterAttribute = values.at( 3 ).toString();
2410 const QVariant filterValue = values.at( 4 ).toString();
2411 const QVariantMap defaultValues = values.at( 5 ).toMap();
2412
2413 // read from database
2415 sqlite3_statement_unique_ptr sqliteStatement;
2416
2417 if ( sqliteDb.open_v2( database, SQLITE_OPEN_READWRITE, nullptr ) != SQLITE_OK )
2418 {
2419 parent->setEvalErrorString( QObject::tr( "Could not open sqlite database %1. Error %2. " ).arg( database, sqliteDb.errorMessage() ) );
2420 functionResult = QVariant();
2421 return;
2422 }
2423
2424 QString errorMessage;
2425 QString currentValSql;
2426
2427 qlonglong nextId = 0;
2428 bool cachedMode = false;
2429 bool valueRetrieved = false;
2430
2431 QString cacheString = QStringLiteral( "%1:%2:%3:%4:%5" ).arg( database, table, idColumn, filterAttribute, filterValue.toString() );
2432
2433 // Running in transaction mode, check for cached value first
2434 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2435 {
2436 cachedMode = true;
2437
2438 auto cachedCounter = counterCache.find( cacheString );
2439
2440 if ( cachedCounter != counterCache.end() )
2441 {
2442 qlonglong &cachedValue = cachedCounter.value();
2443 nextId = cachedValue;
2444 nextId += 1;
2445 cachedValue = nextId;
2446 valueRetrieved = true;
2447 }
2448 }
2449
2450 // Either not in cached mode or no cached value found, obtain from DB
2451 if ( !cachedMode || !valueRetrieved )
2452 {
2453 int result = SQLITE_ERROR;
2454
2455 currentValSql = QStringLiteral( "SELECT %1 FROM %2" ).arg( QgsSqliteUtils::quotedIdentifier( idColumn ), QgsSqliteUtils::quotedIdentifier( table ) );
2456 if ( !filterAttribute.isNull() )
2457 {
2458 currentValSql += QStringLiteral( " WHERE %1 = %2" ).arg( QgsSqliteUtils::quotedIdentifier( filterAttribute ), QgsSqliteUtils::quotedValue( filterValue ) );
2459 }
2460
2461 sqliteStatement = sqliteDb.prepare( currentValSql, result );
2462
2463 if ( result == SQLITE_OK )
2464 {
2465 nextId = 0;
2466 if ( sqliteStatement.step() == SQLITE_ROW )
2467 {
2468 nextId = sqliteStatement.columnAsInt64( 0 ) + 1;
2469 }
2470
2471 // If in cached mode: add value to cache and connect to transaction
2472 if ( cachedMode && result == SQLITE_OK )
2473 {
2474 counterCache.insert( cacheString, nextId );
2475
2476 QObject::connect( layer->dataProvider()->transaction(), &QgsTransaction::destroyed, [cacheString]()
2477 {
2478 counterCache.remove( cacheString );
2479 } );
2480 }
2481 valueRetrieved = true;
2482 }
2483 }
2484
2485 if ( valueRetrieved )
2486 {
2487 QString upsertSql;
2488 upsertSql = QStringLiteral( "INSERT OR REPLACE INTO %1" ).arg( QgsSqliteUtils::quotedIdentifier( table ) );
2489 QStringList cols;
2490 QStringList vals;
2491 cols << QgsSqliteUtils::quotedIdentifier( idColumn );
2492 vals << QgsSqliteUtils::quotedValue( nextId );
2493
2494 if ( !filterAttribute.isNull() )
2495 {
2496 cols << QgsSqliteUtils::quotedIdentifier( filterAttribute );
2497 vals << QgsSqliteUtils::quotedValue( filterValue );
2498 }
2499
2500 for ( QVariantMap::const_iterator iter = defaultValues.constBegin(); iter != defaultValues.constEnd(); ++iter )
2501 {
2502 cols << QgsSqliteUtils::quotedIdentifier( iter.key() );
2503 vals << iter.value().toString();
2504 }
2505
2506 upsertSql += QLatin1String( " (" ) + cols.join( ',' ) + ')';
2507 upsertSql += QLatin1String( " VALUES " );
2508 upsertSql += '(' + vals.join( ',' ) + ')';
2509
2510 int result = SQLITE_ERROR;
2511 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2512 {
2513 QgsTransaction *transaction = layer->dataProvider()->transaction();
2514 if ( transaction->executeSql( upsertSql, errorMessage ) )
2515 {
2516 result = SQLITE_OK;
2517 }
2518 }
2519 else
2520 {
2521 result = sqliteDb.exec( upsertSql, errorMessage );
2522 }
2523 if ( result == SQLITE_OK )
2524 {
2525 functionResult = QVariant( nextId );
2526 return;
2527 }
2528 else
2529 {
2530 parent->setEvalErrorString( QStringLiteral( "Could not increment value: SQLite error: \"%1\" (%2)." ).arg( errorMessage, QString::number( result ) ) );
2531 functionResult = QVariant();
2532 return;
2533 }
2534 }
2535
2536 functionResult = QVariant();
2537 };
2538
2539 bool foundLayer = false;
2540 QgsExpressionUtils::executeLambdaForMapLayer( values.at( 0 ), context, parent, [&fetchAndIncrementFunc]( QgsMapLayer * layer )
2541 {
2542 fetchAndIncrementFunc( layer, QString() );
2543 }, foundLayer );
2544 if ( !foundLayer )
2545 {
2546 const QString databasePath = values.at( 0 ).toString();
2547 QgsThreadingUtils::runOnMainThread( [&fetchAndIncrementFunc, databasePath]
2548 {
2549 fetchAndIncrementFunc( nullptr, databasePath );
2550 } );
2551 }
2552
2553 return functionResult;
2554}
2555
2556static QVariant fcnConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2557{
2558 QString concat;
2559 for ( const QVariant &value : values )
2560 {
2561 if ( !QgsVariantUtils::isNull( value ) )
2562 concat += QgsExpressionUtils::getStringValue( value, parent );
2563 }
2564 return concat;
2565}
2566
2567static QVariant fcnStrpos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2568{
2569 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2570 return string.indexOf( QgsExpressionUtils::getStringValue( values.at( 1 ), parent ) ) + 1;
2571}
2572
2573static QVariant fcnRight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2574{
2575 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2576 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2577 return string.right( pos );
2578}
2579
2580static QVariant fcnLeft( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2581{
2582 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2583 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2584 return string.left( pos );
2585}
2586
2587static QVariant fcnRPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2588{
2589 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2590 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2591 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2592 return string.leftJustified( length, fill.at( 0 ), true );
2593}
2594
2595static QVariant fcnLPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2596{
2597 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2598 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2599 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2600 return string.rightJustified( length, fill.at( 0 ), true );
2601}
2602
2603static QVariant fcnFormatString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2604{
2605 if ( values.size() < 1 )
2606 {
2607 parent->setEvalErrorString( QObject::tr( "Function format requires at least 1 argument" ) );
2608 return QVariant();
2609 }
2610
2611 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2612 for ( int n = 1; n < values.length(); n++ )
2613 {
2614 string = string.arg( QgsExpressionUtils::getStringValue( values.at( n ), parent ) );
2615 }
2616 return string;
2617}
2618
2619
2620static QVariant fcnNow( const QVariantList &, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
2621{
2622 return QVariant( QDateTime::currentDateTime() );
2623}
2624
2625static QVariant fcnToDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2626{
2627 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2628 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2629 if ( format.isEmpty() && !language.isEmpty() )
2630 {
2631 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Date when the language is specified" ) );
2632 return QVariant( QDate() );
2633 }
2634
2635 if ( format.isEmpty() && language.isEmpty() )
2636 return QVariant( QgsExpressionUtils::getDateValue( values.at( 0 ), parent ) );
2637
2638 QString datestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2639 QLocale locale = QLocale();
2640 if ( !language.isEmpty() )
2641 {
2642 locale = QLocale( language );
2643 }
2644
2645 QDate date = locale.toDate( datestring, format );
2646 if ( !date.isValid() )
2647 {
2648 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Date" ).arg( datestring ) );
2649 date = QDate();
2650 }
2651 return QVariant( date );
2652}
2653
2654static QVariant fcnToTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2655{
2656 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2657 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2658 if ( format.isEmpty() && !language.isEmpty() )
2659 {
2660 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Time when the language is specified" ) );
2661 return QVariant( QTime() );
2662 }
2663
2664 if ( format.isEmpty() && language.isEmpty() )
2665 return QVariant( QgsExpressionUtils::getTimeValue( values.at( 0 ), parent ) );
2666
2667 QString timestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2668 QLocale locale = QLocale();
2669 if ( !language.isEmpty() )
2670 {
2671 locale = QLocale( language );
2672 }
2673
2674 QTime time = locale.toTime( timestring, format );
2675 if ( !time.isValid() )
2676 {
2677 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Time" ).arg( timestring ) );
2678 time = QTime();
2679 }
2680 return QVariant( time );
2681}
2682
2683static QVariant fcnToInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2684{
2685 return QVariant::fromValue( QgsExpressionUtils::getInterval( values.at( 0 ), parent ) );
2686}
2687
2688/*
2689 * DMS functions
2690 */
2691
2692static QVariant floatToDegreeFormat( const QgsCoordinateFormatter::Format format, const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2693{
2694 double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
2695 QString axis = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2696 int precision = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
2697
2698 QString formatString;
2699 if ( values.count() > 3 )
2700 formatString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent );
2701
2703 if ( formatString.compare( QLatin1String( "suffix" ), Qt::CaseInsensitive ) == 0 )
2704 {
2706 }
2707 else if ( formatString.compare( QLatin1String( "aligned" ), Qt::CaseInsensitive ) == 0 )
2708 {
2710 }
2711 else if ( ! formatString.isEmpty() )
2712 {
2713 parent->setEvalErrorString( QObject::tr( "Invalid formatting parameter: '%1'. It must be empty, or 'suffix' or 'aligned'." ).arg( formatString ) );
2714 return QVariant();
2715 }
2716
2717 if ( axis.compare( QLatin1String( "x" ), Qt::CaseInsensitive ) == 0 )
2718 {
2719 return QVariant::fromValue( QgsCoordinateFormatter::formatX( value, format, precision, flags ) );
2720 }
2721 else if ( axis.compare( QLatin1String( "y" ), Qt::CaseInsensitive ) == 0 )
2722 {
2723 return QVariant::fromValue( QgsCoordinateFormatter::formatY( value, format, precision, flags ) );
2724 }
2725 else
2726 {
2727 parent->setEvalErrorString( QObject::tr( "Invalid axis name: '%1'. It must be either 'x' or 'y'." ).arg( axis ) );
2728 return QVariant();
2729 }
2730}
2731
2732static QVariant fcnToDegreeMinute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2733{
2735 return floatToDegreeFormat( format, values, context, parent, node );
2736}
2737
2738static QVariant fcnToDecimal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2739{
2740 double value = 0.0;
2741 bool ok = false;
2742 value = QgsCoordinateUtils::dmsToDecimal( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), &ok );
2743
2744 return ok ? QVariant( value ) : QVariant();
2745}
2746
2747static QVariant fcnToDegreeMinuteSecond( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2748{
2750 return floatToDegreeFormat( format, values, context, parent, node );
2751}
2752
2753static QVariant fcnAge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2754{
2755 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2756 QDateTime d2 = QgsExpressionUtils::getDateTimeValue( values.at( 1 ), parent );
2757 qint64 seconds = d2.secsTo( d1 );
2758 return QVariant::fromValue( QgsInterval( seconds ) );
2759}
2760
2761static QVariant fcnDayOfWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2762{
2763 if ( !values.at( 0 ).canConvert<QDate>() )
2764 return QVariant();
2765
2766 QDate date = QgsExpressionUtils::getDateValue( values.at( 0 ), parent );
2767 if ( !date.isValid() )
2768 return QVariant();
2769
2770 // return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
2771 // (to match PostgreSQL behavior)
2772 return date.dayOfWeek() % 7;
2773}
2774
2775static QVariant fcnDay( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2776{
2777 QVariant value = values.at( 0 );
2778 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2779 if ( inter.isValid() )
2780 {
2781 return QVariant( inter.days() );
2782 }
2783 else
2784 {
2785 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2786 return QVariant( d1.date().day() );
2787 }
2788}
2789
2790static QVariant fcnYear( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2791{
2792 QVariant value = values.at( 0 );
2793 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2794 if ( inter.isValid() )
2795 {
2796 return QVariant( inter.years() );
2797 }
2798 else
2799 {
2800 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2801 return QVariant( d1.date().year() );
2802 }
2803}
2804
2805static QVariant fcnMonth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2806{
2807 QVariant value = values.at( 0 );
2808 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2809 if ( inter.isValid() )
2810 {
2811 return QVariant( inter.months() );
2812 }
2813 else
2814 {
2815 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2816 return QVariant( d1.date().month() );
2817 }
2818}
2819
2820static QVariant fcnWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2821{
2822 QVariant value = values.at( 0 );
2823 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2824 if ( inter.isValid() )
2825 {
2826 return QVariant( inter.weeks() );
2827 }
2828 else
2829 {
2830 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2831 return QVariant( d1.date().weekNumber() );
2832 }
2833}
2834
2835static QVariant fcnHour( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2836{
2837 QVariant value = values.at( 0 );
2838 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2839 if ( inter.isValid() )
2840 {
2841 return QVariant( inter.hours() );
2842 }
2843 else
2844 {
2845 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2846 return QVariant( t1.hour() );
2847 }
2848}
2849
2850static QVariant fcnMinute( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2851{
2852 QVariant value = values.at( 0 );
2853 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2854 if ( inter.isValid() )
2855 {
2856 return QVariant( inter.minutes() );
2857 }
2858 else
2859 {
2860 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2861 return QVariant( t1.minute() );
2862 }
2863}
2864
2865static QVariant fcnSeconds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2866{
2867 QVariant value = values.at( 0 );
2868 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2869 if ( inter.isValid() )
2870 {
2871 return QVariant( inter.seconds() );
2872 }
2873 else
2874 {
2875 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2876 return QVariant( t1.second() );
2877 }
2878}
2879
2880static QVariant fcnEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2881{
2882 QDateTime dt = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2883 if ( dt.isValid() )
2884 {
2885 return QVariant( dt.toMSecsSinceEpoch() );
2886 }
2887 else
2888 {
2889 return QVariant();
2890 }
2891}
2892
2893static QVariant fcnDateTimeFromEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2894{
2895 long long millisecs_since_epoch = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
2896 // no sense to check for strange values, as Qt behavior is undefined anyway (see docs)
2897 return QVariant( QDateTime::fromMSecsSinceEpoch( millisecs_since_epoch ) );
2898}
2899
2900static QVariant fcnExif( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2901{
2902 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2903 if ( parent->hasEvalError() )
2904 {
2905 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif" ) ) );
2906 return QVariant();
2907 }
2908 QString tag = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2909 return !tag.isNull() ? QgsExifTools::readTag( filepath, tag ) : QVariant( QgsExifTools::readTags( filepath ) );
2910}
2911
2912static QVariant fcnExifGeoTag( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2914 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2915 if ( parent->hasEvalError() )
2916 {
2917 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif_geotag" ) ) );
2918 return QVariant();
2919 }
2920 bool ok;
2921 return QVariant::fromValue( QgsGeometry( new QgsPoint( QgsExifTools::getGeoTag( filepath, ok ) ) ) );
2922}
2923
2924#define ENSURE_GEOM_TYPE(f, g, geomtype) \
2925 if ( !(f).hasGeometry() ) \
2926 return QVariant(); \
2927 QgsGeometry g = (f).geometry(); \
2928 if ( (g).type() != (geomtype) ) \
2929 return QVariant();
2930
2931static QVariant fcnX( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2932{
2933 FEAT_FROM_CONTEXT( context, f )
2935 if ( g.isMultipart() )
2936 {
2937 return g.asMultiPoint().at( 0 ).x();
2938 }
2939 else
2940 {
2941 return g.asPoint().x();
2942 }
2943}
2944
2945static QVariant fcnY( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2946{
2947 FEAT_FROM_CONTEXT( context, f )
2949 if ( g.isMultipart() )
2950 {
2951 return g.asMultiPoint().at( 0 ).y();
2952 }
2953 else
2954 {
2955 return g.asPoint().y();
2956 }
2957}
2958
2959static QVariant fcnZ( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2960{
2961 FEAT_FROM_CONTEXT( context, f )
2963
2964 if ( g.isEmpty() )
2965 return QVariant();
2966
2967 const QgsAbstractGeometry *abGeom = g.constGet();
2968
2969 if ( g.isEmpty() || !abGeom->is3D() )
2970 return QVariant();
2971
2972 if ( g.type() == Qgis::GeometryType::Point && !g.isMultipart() )
2973 {
2974 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( g.constGet() );
2975 if ( point )
2976 return point->z();
2977 }
2978 else if ( g.type() == Qgis::GeometryType::Point && g.isMultipart() )
2979 {
2980 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( g.constGet() ) )
2981 {
2982 if ( collection->numGeometries() > 0 )
2983 {
2984 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
2985 return point->z();
2986 }
2987 }
2988 }
2989
2990 return QVariant();
2991}
2992
2993static QVariant fcnGeomIsValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2994{
2995 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
2996 if ( geom.isNull() )
2997 return QVariant();
2998
2999 bool isValid = geom.isGeosValid();
3000
3001 return QVariant( isValid );
3002}
3003
3004static QVariant fcnGeomMakeValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3005{
3006 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3007 if ( geom.isNull() )
3008 return QVariant();
3009
3010 const QString methodString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).trimmed();
3011#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
3013#else
3015#endif
3016 if ( methodString.compare( QLatin1String( "linework" ), Qt::CaseInsensitive ) == 0 )
3018 else if ( methodString.compare( QLatin1String( "structure" ), Qt::CaseInsensitive ) == 0 )
3020
3021 const bool keepCollapsed = values.value( 2 ).toBool();
3022
3023 QgsGeometry valid;
3024 try
3025 {
3026 valid = geom.makeValid( method, keepCollapsed );
3027 }
3028 catch ( QgsNotSupportedException & )
3029 {
3030 parent->setEvalErrorString( QObject::tr( "The make_valid parameters require a newer GEOS library version" ) );
3031 return QVariant();
3032 }
3033
3034 return QVariant::fromValue( valid );
3035}
3036
3037static QVariant fcnGeometryCollectionAsArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3038{
3039 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3040 if ( geom.isNull() )
3041 return QVariant();
3042
3043 QVector<QgsGeometry> multiGeom = geom.asGeometryCollection();
3044 QVariantList array;
3045 for ( int i = 0; i < multiGeom.size(); ++i )
3046 {
3047 array += QVariant::fromValue( multiGeom.at( i ) );
3048 }
3049
3050 return array;
3051}
3052
3053static QVariant fcnGeomX( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3054{
3055 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3056 if ( geom.isNull() )
3057 return QVariant();
3058
3059 //if single point, return the point's x coordinate
3060 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3061 {
3062 return geom.asPoint().x();
3063 }
3064
3065 //otherwise return centroid x
3066 QgsGeometry centroid = geom.centroid();
3067 QVariant result( centroid.asPoint().x() );
3068 return result;
3069}
3070
3071static QVariant fcnGeomY( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3072{
3073 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3074 if ( geom.isNull() )
3075 return QVariant();
3076
3077 //if single point, return the point's y coordinate
3078 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3079 {
3080 return geom.asPoint().y();
3081 }
3082
3083 //otherwise return centroid y
3084 QgsGeometry centroid = geom.centroid();
3085 QVariant result( centroid.asPoint().y() );
3086 return result;
3087}
3088
3089static QVariant fcnGeomZ( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3090{
3091 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3092 if ( geom.isNull() )
3093 return QVariant(); //or 0?
3094
3095 if ( !geom.constGet()->is3D() )
3096 return QVariant();
3097
3098 //if single point, return the point's z coordinate
3099 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3100 {
3101 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3102 if ( point )
3103 return point->z();
3104 }
3105 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3106 {
3107 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3108 {
3109 if ( collection->numGeometries() == 1 )
3110 {
3111 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3112 return point->z();
3113 }
3114 }
3115 }
3116
3117 return QVariant();
3118}
3119
3120static QVariant fcnGeomM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3121{
3122 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3123 if ( geom.isNull() )
3124 return QVariant(); //or 0?
3125
3126 if ( !geom.constGet()->isMeasure() )
3127 return QVariant();
3128
3129 //if single point, return the point's m value
3130 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3131 {
3132 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3133 if ( point )
3134 return point->m();
3135 }
3136 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3137 {
3138 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3139 {
3140 if ( collection->numGeometries() == 1 )
3141 {
3142 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3143 return point->m();
3144 }
3145 }
3146 }
3147
3148 return QVariant();
3149}
3150
3151static QVariant fcnPointN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3152{
3153 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3154
3155 if ( geom.isNull() )
3156 return QVariant();
3157
3158 int idx = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
3159
3160 if ( idx < 0 )
3161 {
3162 //negative idx
3163 int count = geom.constGet()->nCoordinates();
3164 idx = count + idx;
3165 }
3166 else
3167 {
3168 //positive idx is 1 based
3169 idx -= 1;
3170 }
3171
3172 QgsVertexId vId;
3173 if ( idx < 0 || !geom.vertexIdFromVertexNr( idx, vId ) )
3174 {
3175 parent->setEvalErrorString( QObject::tr( "Point index is out of range" ) );
3176 return QVariant();
3177 }
3178
3179 QgsPoint point = geom.constGet()->vertexAt( vId );
3180 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3181}
3182
3183static QVariant fcnStartPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3184{
3185 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3186
3187 if ( geom.isNull() )
3188 return QVariant();
3189
3190 QgsVertexId vId;
3191 if ( !geom.vertexIdFromVertexNr( 0, vId ) )
3192 {
3193 return QVariant();
3194 }
3195
3196 QgsPoint point = geom.constGet()->vertexAt( vId );
3197 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3198}
3199
3200static QVariant fcnEndPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3201{
3202 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3203
3204 if ( geom.isNull() )
3205 return QVariant();
3206
3207 QgsVertexId vId;
3208 if ( !geom.vertexIdFromVertexNr( geom.constGet()->nCoordinates() - 1, vId ) )
3209 {
3210 return QVariant();
3211 }
3212
3213 QgsPoint point = geom.constGet()->vertexAt( vId );
3214 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3215}
3216
3217static QVariant fcnNodesToPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3218{
3219 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3220
3221 if ( geom.isNull() )
3222 return QVariant();
3223
3224 bool ignoreClosing = false;
3225 if ( values.length() > 1 )
3226 {
3227 ignoreClosing = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3228 }
3229
3230 QgsMultiPoint *mp = new QgsMultiPoint();
3231
3232 const QgsCoordinateSequence sequence = geom.constGet()->coordinateSequence();
3233 for ( const QgsRingSequence &part : sequence )
3234 {
3235 for ( const QgsPointSequence &ring : part )
3236 {
3237 bool skipLast = false;
3238 if ( ignoreClosing && ring.count() > 2 && ring.first() == ring.last() )
3239 {
3240 skipLast = true;
3241 }
3242
3243 for ( int i = 0; i < ( skipLast ? ring.count() - 1 : ring.count() ); ++ i )
3244 {
3245 mp->addGeometry( ring.at( i ).clone() );
3246 }
3247 }
3248 }
3249
3250 return QVariant::fromValue( QgsGeometry( mp ) );
3251}
3252
3253static QVariant fcnSegmentsToLines( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3254{
3255 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3256
3257 if ( geom.isNull() )
3258 return QVariant();
3259
3260 const QVector< QgsLineString * > linesToProcess = QgsGeometryUtils::extractLineStrings( geom.constGet() );
3261
3262 //OK, now we have a complete list of segmentized lines from the geometry
3264 for ( QgsLineString *line : linesToProcess )
3265 {
3266 for ( int i = 0; i < line->numPoints() - 1; ++i )
3267 {
3269 segment->setPoints( QgsPointSequence()
3270 << line->pointN( i )
3271 << line->pointN( i + 1 ) );
3272 ml->addGeometry( segment );
3273 }
3274 delete line;
3275 }
3276
3277 return QVariant::fromValue( QgsGeometry( ml ) );
3278}
3279
3280static QVariant fcnInteriorRingN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3281{
3282 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3283
3284 if ( geom.isNull() )
3285 return QVariant();
3286
3287 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
3288 if ( !curvePolygon && geom.isMultipart() )
3289 {
3290 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3291 {
3292 if ( collection->numGeometries() == 1 )
3293 {
3294 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
3295 }
3296 }
3297 }
3298
3299 if ( !curvePolygon )
3300 return QVariant();
3301
3302 //idx is 1 based
3303 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3304
3305 if ( idx >= curvePolygon->numInteriorRings() || idx < 0 )
3306 return QVariant();
3307
3308 QgsCurve *curve = static_cast< QgsCurve * >( curvePolygon->interiorRing( static_cast< int >( idx ) )->clone() );
3309 QVariant result = curve ? QVariant::fromValue( QgsGeometry( curve ) ) : QVariant();
3310 return result;
3311}
3312
3313static QVariant fcnGeometryN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3314{
3315 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3316
3317 if ( geom.isNull() )
3318 return QVariant();
3319
3320 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
3321 if ( !collection )
3322 return QVariant();
3323
3324 //idx is 1 based
3325 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3326
3327 if ( idx < 0 || idx >= collection->numGeometries() )
3328 return QVariant();
3329
3330 QgsAbstractGeometry *part = collection->geometryN( static_cast< int >( idx ) )->clone();
3331 QVariant result = part ? QVariant::fromValue( QgsGeometry( part ) ) : QVariant();
3332 return result;
3333}
3334
3335static QVariant fcnBoundary( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3336{
3337 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3338
3339 if ( geom.isNull() )
3340 return QVariant();
3341
3342 QgsAbstractGeometry *boundary = geom.constGet()->boundary();
3343 if ( !boundary )
3344 return QVariant();
3345
3346 return QVariant::fromValue( QgsGeometry( boundary ) );
3347}
3348
3349static QVariant fcnLineMerge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3350{
3351 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3352
3353 if ( geom.isNull() )
3354 return QVariant();
3355
3356 QgsGeometry merged = geom.mergeLines();
3357 if ( merged.isNull() )
3358 return QVariant();
3359
3360 return QVariant::fromValue( merged );
3361}
3362
3363static QVariant fcnSharedPaths( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3364{
3365 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3366 if ( geom.isNull() )
3367 return QVariant();
3368
3369 const QgsGeometry geom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
3370 if ( geom2.isNull() )
3371 return QVariant();
3372
3373 const QgsGeometry sharedPaths = geom.sharedPaths( geom2 );
3374 if ( sharedPaths.isNull() )
3375 return QVariant();
3376
3377 return QVariant::fromValue( sharedPaths );
3378}
3379
3380
3381static QVariant fcnSimplify( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3382{
3383 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3384
3385 if ( geom.isNull() )
3386 return QVariant();
3387
3388 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3389
3390 QgsGeometry simplified = geom.simplify( tolerance );
3391 if ( simplified.isNull() )
3392 return QVariant();
3393
3394 return simplified;
3395}
3396
3397static QVariant fcnSimplifyVW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3398{
3399 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3400
3401 if ( geom.isNull() )
3402 return QVariant();
3403
3404 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3405
3407
3408 QgsGeometry simplified = simplifier.simplify( geom );
3409 if ( simplified.isNull() )
3410 return QVariant();
3411
3412 return simplified;
3413}
3414
3415static QVariant fcnSmooth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3416{
3417 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3418
3419 if ( geom.isNull() )
3420 return QVariant();
3421
3422 int iterations = std::min( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), 10 );
3423 double offset = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0.0, 0.5 );
3424 double minLength = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3425 double maxAngle = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ), 0.0, 180.0 );
3426
3427 QgsGeometry smoothed = geom.smooth( static_cast<unsigned int>( iterations ), offset, minLength, maxAngle );
3428 if ( smoothed.isNull() )
3429 return QVariant();
3430
3431 return smoothed;
3432}
3433
3434static QVariant fcnTriangularWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3435{
3436 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3437
3438 if ( geom.isNull() )
3439 return QVariant();
3440
3441 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3442 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3443 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3444
3445 const QgsGeometry waved = geom.triangularWaves( wavelength, amplitude, strict );
3446 if ( waved.isNull() )
3447 return QVariant();
3448
3449 return waved;
3450}
3451
3452static QVariant fcnTriangularWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3453{
3454 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3455
3456 if ( geom.isNull() )
3457 return QVariant();
3458
3459 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3460 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3461 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3462 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3463 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3464
3465 const QgsGeometry waved = geom.triangularWavesRandomized( minWavelength, maxWavelength,
3466 minAmplitude, maxAmplitude, seed );
3467 if ( waved.isNull() )
3468 return QVariant();
3469
3470 return waved;
3471}
3472
3473static QVariant fcnSquareWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3474{
3475 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3476
3477 if ( geom.isNull() )
3478 return QVariant();
3479
3480 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3481 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3482 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3483
3484 const QgsGeometry waved = geom.squareWaves( wavelength, amplitude, strict );
3485 if ( waved.isNull() )
3486 return QVariant();
3487
3488 return waved;
3489}
3490
3491static QVariant fcnSquareWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3492{
3493 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3494
3495 if ( geom.isNull() )
3496 return QVariant();
3497
3498 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3499 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3500 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3501 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3502 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3503
3504 const QgsGeometry waved = geom.squareWavesRandomized( minWavelength, maxWavelength,
3505 minAmplitude, maxAmplitude, seed );
3506 if ( waved.isNull() )
3507 return QVariant();
3508
3509 return waved;
3510}
3511
3512static QVariant fcnRoundWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3513{
3514 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3515
3516 if ( geom.isNull() )
3517 return QVariant();
3518
3519 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3520 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3521 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3522
3523 const QgsGeometry waved = geom.roundWaves( wavelength, amplitude, strict );
3524 if ( waved.isNull() )
3525 return QVariant();
3526
3527 return waved;
3528}
3529
3530static QVariant fcnRoundWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3531{
3532 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3533
3534 if ( geom.isNull() )
3535 return QVariant();
3536
3537 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3538 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3539 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3540 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3541 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3542
3543 const QgsGeometry waved = geom.roundWavesRandomized( minWavelength, maxWavelength,
3544 minAmplitude, maxAmplitude, seed );
3545 if ( waved.isNull() )
3546 return QVariant();
3547
3548 return waved;
3549}
3550
3551static QVariant fcnApplyDashPattern( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3552{
3553 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3554
3555 if ( geom.isNull() )
3556 return QVariant();
3557
3558 const QVariantList pattern = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
3559 QVector< double > dashPattern;
3560 dashPattern.reserve( pattern.size() );
3561 for ( const QVariant &value : std::as_const( pattern ) )
3562 {
3563 bool ok = false;
3564 double v = value.toDouble( &ok );
3565 if ( ok )
3566 {
3567 dashPattern << v;
3568 }
3569 else
3570 {
3571 parent->setEvalErrorString( QStringLiteral( "Dash pattern must be an array of numbers" ) );
3572 return QgsGeometry();
3573 }
3574 }
3575
3576 if ( dashPattern.size() % 2 != 0 )
3577 {
3578 parent->setEvalErrorString( QStringLiteral( "Dash pattern must contain an even number of elements" ) );
3579 return QgsGeometry();
3580 }
3581
3582 const QString startRuleString = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).trimmed();
3584 if ( startRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3586 else if ( startRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3588 else if ( startRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3590 else if ( startRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3592 else if ( startRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3594 else
3595 {
3596 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( startRuleString ) );
3597 return QgsGeometry();
3598 }
3599
3600 const QString endRuleString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
3602 if ( endRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3604 else if ( endRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3606 else if ( endRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3608 else if ( endRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3610 else if ( endRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3612 else
3613 {
3614 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( endRuleString ) );
3615 return QgsGeometry();
3616 }
3617
3618 const QString adjustString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
3620 if ( adjustString.compare( QLatin1String( "both" ), Qt::CaseInsensitive ) == 0 )
3622 else if ( adjustString.compare( QLatin1String( "dash" ), Qt::CaseInsensitive ) == 0 )
3624 else if ( adjustString.compare( QLatin1String( "gap" ), Qt::CaseInsensitive ) == 0 )
3626 else
3627 {
3628 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern size adjustment" ).arg( adjustString ) );
3629 return QgsGeometry();
3630 }
3631
3632 const double patternOffset = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
3633
3634 const QgsGeometry result = geom.applyDashPattern( dashPattern, startRule, endRule, adjustment, patternOffset );
3635 if ( result.isNull() )
3636 return QVariant();
3637
3638 return result;
3639}
3640
3641static QVariant fcnDensifyByCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3642{
3643 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3644
3645 if ( geom.isNull() )
3646 return QVariant();
3647
3648 const long long count = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3649 const QgsGeometry densified = geom.densifyByCount( static_cast< int >( count ) );
3650 if ( densified.isNull() )
3651 return QVariant();
3652
3653 return densified;
3654}
3655
3656static QVariant fcnDensifyByDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3657{
3658 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3659
3660 if ( geom.isNull() )
3661 return QVariant();
3662
3663 const double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3664 const QgsGeometry densified = geom.densifyByDistance( distance );
3665 if ( densified.isNull() )
3666 return QVariant();
3667
3668 return densified;
3669}
3670
3671static QVariant fcnCollectGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3672{
3673 QVariantList list;
3674 if ( values.size() == 1 && QgsExpressionUtils::isList( values.at( 0 ) ) )
3675 {
3676 list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
3677 }
3678 else
3679 {
3680 list = values;
3681 }
3682
3683 QVector< QgsGeometry > parts;
3684 parts.reserve( list.size() );
3685 for ( const QVariant &value : std::as_const( list ) )
3686 {
3687 if ( value.userType() == QMetaType::type( "QgsGeometry" ) )
3688 {
3689 parts << value.value<QgsGeometry>();
3690 }
3691 else
3692 {
3693 parent->setEvalErrorString( QStringLiteral( "Cannot convert to geometry" ) );
3694 return QgsGeometry();
3695 }
3696 }
3697
3698 return QgsGeometry::collectGeometry( parts );
3699}
3700
3701static QVariant fcnMakePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3702{
3703 if ( values.count() < 2 || values.count() > 4 )
3704 {
3705 parent->setEvalErrorString( QObject::tr( "Function make_point requires 2-4 arguments" ) );
3706 return QVariant();
3707 }
3708
3709 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3710 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3711 double z = values.count() >= 3 ? QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) : 0.0;
3712 double m = values.count() >= 4 ? QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) : 0.0;
3713 switch ( values.count() )
3714 {
3715 case 2:
3716 return QVariant::fromValue( QgsGeometry( new QgsPoint( x, y ) ) );
3717 case 3:
3718 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZ, x, y, z ) ) );
3719 case 4:
3720 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZM, x, y, z, m ) ) );
3721 }
3722 return QVariant(); //avoid warning
3723}
3724
3725static QVariant fcnMakePointM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3726{
3727 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3728 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3729 double m = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3730 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointM, x, y, 0.0, m ) ) );
3731}
3732
3733static QVariant fcnMakeLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3734{
3735 if ( values.empty() )
3736 {
3737 return QVariant();
3738 }
3739
3740 QVector<QgsPoint> points;
3741 points.reserve( values.count() );
3742
3743 auto addPoint = [&points]( const QgsGeometry & geom )
3744 {
3745 if ( geom.isNull() )
3746 return;
3747
3748 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3749 return;
3750
3751 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3752 if ( !point )
3753 return;
3754
3755 points << *point;
3756 };
3757
3758 for ( const QVariant &value : values )
3759 {
3760 if ( value.userType() == QMetaType::Type::QVariantList )
3761 {
3762 const QVariantList list = value.toList();
3763 for ( const QVariant &v : list )
3764 {
3765 addPoint( QgsExpressionUtils::getGeometry( v, parent ) );
3766 }
3767 }
3768 else
3769 {
3770 addPoint( QgsExpressionUtils::getGeometry( value, parent ) );
3771 }
3772 }
3773
3774 if ( points.count() < 2 )
3775 return QVariant();
3776
3777 return QgsGeometry( new QgsLineString( points ) );
3778}
3779
3780static QVariant fcnMakePolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3781{
3782 if ( values.count() < 1 )
3783 {
3784 parent->setEvalErrorString( QObject::tr( "Function make_polygon requires an argument" ) );
3785 return QVariant();
3786 }
3787
3788 QgsGeometry outerRing = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3789
3790 if ( outerRing.type() == Qgis::GeometryType::Polygon )
3791 return outerRing; // if it's already a polygon we have nothing to do
3792
3793 if ( outerRing.type() != Qgis::GeometryType::Line || outerRing.isNull() )
3794 return QVariant();
3795
3796 std::unique_ptr< QgsPolygon > polygon = std::make_unique< QgsPolygon >();
3797
3798 const QgsCurve *exteriorRing = qgsgeometry_cast< QgsCurve * >( outerRing.constGet() );
3799 if ( !exteriorRing && outerRing.isMultipart() )
3800 {
3801 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( outerRing.constGet() ) )
3802 {
3803 if ( collection->numGeometries() == 1 )
3804 {
3805 exteriorRing = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3806 }
3807 }
3808 }
3809
3810 if ( !exteriorRing )
3811 return QVariant();
3812
3813 polygon->setExteriorRing( exteriorRing->segmentize() );
3814
3815
3816 for ( int i = 1; i < values.count(); ++i )
3817 {
3818 QgsGeometry ringGeom = QgsExpressionUtils::getGeometry( values.at( i ), parent );
3819 if ( ringGeom.isNull() )
3820 continue;
3821
3822 if ( ringGeom.type() != Qgis::GeometryType::Line || ringGeom.isNull() )
3823 continue;
3824
3825 const QgsCurve *ring = qgsgeometry_cast< QgsCurve * >( ringGeom.constGet() );
3826 if ( !ring && ringGeom.isMultipart() )
3827 {
3828 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( ringGeom.constGet() ) )
3829 {
3830 if ( collection->numGeometries() == 1 )
3831 {
3832 ring = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3833 }
3834 }
3835 }
3836
3837 if ( !ring )
3838 continue;
3839
3840 polygon->addInteriorRing( ring->segmentize() );
3841 }
3842
3843 return QVariant::fromValue( QgsGeometry( std::move( polygon ) ) );
3844}
3845
3846static QVariant fcnMakeTriangle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3847{
3848 std::unique_ptr<QgsTriangle> tr( new QgsTriangle() );
3849 std::unique_ptr<QgsLineString> lineString( new QgsLineString() );
3850 lineString->clear();
3851
3852 for ( const QVariant &value : values )
3853 {
3854 QgsGeometry geom = QgsExpressionUtils::getGeometry( value, parent );
3855 if ( geom.isNull() )
3856 return QVariant();
3857
3858 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3859 return QVariant();
3860
3861 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3862 if ( !point && geom.isMultipart() )
3863 {
3864 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3865 {
3866 if ( collection->numGeometries() == 1 )
3867 {
3868 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3869 }
3870 }
3871 }
3872
3873 if ( !point )
3874 return QVariant();
3875
3876 lineString->addVertex( *point );
3877 }
3878
3879 tr->setExteriorRing( lineString.release() );
3880
3881 return QVariant::fromValue( QgsGeometry( tr.release() ) );
3882}
3883
3884static QVariant fcnMakeCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3885{
3886 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3887 if ( geom.isNull() )
3888 return QVariant();
3889
3890 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3891 return QVariant();
3892
3893 double radius = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3894 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
3895
3896 if ( segment < 3 )
3897 {
3898 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3899 return QVariant();
3900 }
3901 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3902 if ( !point && geom.isMultipart() )
3903 {
3904 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3905 {
3906 if ( collection->numGeometries() == 1 )
3907 {
3908 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3909 }
3910 }
3911 }
3912 if ( !point )
3913 return QVariant();
3914
3915 QgsCircle circ( *point, radius );
3916 return QVariant::fromValue( QgsGeometry( circ.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3917}
3918
3919static QVariant fcnMakeEllipse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3920{
3921 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3922 if ( geom.isNull() )
3923 return QVariant();
3924
3925 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3926 return QVariant();
3927
3928 double majorAxis = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3929 double minorAxis = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3930 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3931 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 4 ), parent );
3932 if ( segment < 3 )
3933 {
3934 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3935 return QVariant();
3936 }
3937 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3938 if ( !point && geom.isMultipart() )
3939 {
3940 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3941 {
3942 if ( collection->numGeometries() == 1 )
3943 {
3944 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3945 }
3946 }
3947 }
3948 if ( !point )
3949 return QVariant();
3950
3951 QgsEllipse elp( *point, majorAxis, minorAxis, azimuth );
3952 return QVariant::fromValue( QgsGeometry( elp.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3953}
3954
3955static QVariant fcnMakeRegularPolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3956{
3957
3958 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3959 if ( pt1.isNull() )
3960 return QVariant();
3961
3962 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
3963 return QVariant();
3964
3965 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
3966 if ( pt2.isNull() )
3967 return QVariant();
3968
3969 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
3970 return QVariant();
3971
3972 unsigned int nbEdges = static_cast<unsigned int>( QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) );
3973 if ( nbEdges < 3 )
3974 {
3975 parent->setEvalErrorString( QObject::tr( "Number of edges/sides must be greater than 2" ) );
3976 return QVariant();
3977 }
3978
3979 QgsRegularPolygon::ConstructionOption option = static_cast< QgsRegularPolygon::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
3981 {
3982 parent->setEvalErrorString( QObject::tr( "Option can be 0 (inscribed) or 1 (circumscribed)" ) );
3983 return QVariant();
3984 }
3985
3986 const QgsPoint *center = qgsgeometry_cast< const QgsPoint * >( pt1.constGet() );
3987 if ( !center && pt1.isMultipart() )
3988 {
3989 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt1.constGet() ) )
3990 {
3991 if ( collection->numGeometries() == 1 )
3992 {
3993 center = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3994 }
3995 }
3996 }
3997 if ( !center )
3998 return QVariant();
3999
4000 const QgsPoint *corner = qgsgeometry_cast< const QgsPoint * >( pt2.constGet() );
4001 if ( !corner && pt2.isMultipart() )
4002 {
4003 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt2.constGet() ) )
4004 {
4005 if ( collection->numGeometries() == 1 )
4006 {
4007 corner = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4008 }
4009 }
4010 }
4011 if ( !corner )
4012 return QVariant();
4013
4014 QgsRegularPolygon rp = QgsRegularPolygon( *center, *corner, nbEdges, option );
4015
4016 return QVariant::fromValue( QgsGeometry( rp.toPolygon() ) );
4017
4018}
4019
4020static QVariant fcnMakeSquare( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4021{
4022 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4023 if ( pt1.isNull() )
4024 return QVariant();
4025 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4026 return QVariant();
4027
4028 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4029 if ( pt2.isNull() )
4030 return QVariant();
4031 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4032 return QVariant();
4033
4034 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4035 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4036 QgsQuadrilateral square = QgsQuadrilateral::squareFromDiagonal( *point1, *point2 );
4037
4038 return QVariant::fromValue( QgsGeometry( square.toPolygon() ) );
4039}
4040
4041static QVariant fcnMakeRectangleFrom3Points( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4042{
4043 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4044 if ( pt1.isNull() )
4045 return QVariant();
4046 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4047 return QVariant();
4048
4049 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4050 if ( pt2.isNull() )
4051 return QVariant();
4052 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4053 return QVariant();
4054
4055 QgsGeometry pt3 = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
4056 if ( pt3.isNull() )
4057 return QVariant();
4058 if ( pt3.type() != Qgis::GeometryType::Point || pt3.isMultipart() )
4059 return QVariant();
4060
4061 QgsQuadrilateral::ConstructionOption option = static_cast< QgsQuadrilateral::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4062 if ( ( option < QgsQuadrilateral::Distance ) || ( option > QgsQuadrilateral::Projected ) )
4063 {
4064 parent->setEvalErrorString( QObject::tr( "Option can be 0 (distance) or 1 (projected)" ) );
4065 return QVariant();
4066 }
4067 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4068 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4069 const QgsPoint *point3 = qgsgeometry_cast< const QgsPoint *>( pt3.constGet() );
4070 QgsQuadrilateral rect = QgsQuadrilateral::rectangleFrom3Points( *point1, *point2, *point3, option );
4071 return QVariant::fromValue( QgsGeometry( rect.toPolygon() ) );
4072}
4073
4074static QVariant pointAt( const QgsGeometry &geom, int idx, QgsExpression *parent ) // helper function
4075{
4076 if ( geom.isNull() )
4077 return QVariant();
4078
4079 if ( idx < 0 )
4080 {
4081 idx += geom.constGet()->nCoordinates();
4082 }
4083 if ( idx < 0 || idx >= geom.constGet()->nCoordinates() )
4084 {
4085 parent->setEvalErrorString( QObject::tr( "Index is out of range" ) );
4086 return QVariant();
4087 }
4088 return QVariant::fromValue( geom.vertexAt( idx ) );
4089}
4090
4091// function used for the old $ style
4092static QVariant fcnOldXat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4093{
4094 FEAT_FROM_CONTEXT( context, feature )
4095 const QgsGeometry geom = feature.geometry();
4096 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4097
4098 const QVariant v = pointAt( geom, idx, parent );
4099
4100 if ( !v.isNull() )
4101 return QVariant( v.value<QgsPoint>().x() );
4102 else
4103 return QVariant();
4104}
4105static QVariant fcnXat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4106{
4107 if ( values.at( 1 ).isNull() && !values.at( 0 ).isNull() ) // the case where the alias x_at function is called like a $ function (x_at(i))
4108 {
4109 return fcnOldXat( values, f, parent, node );
4110 }
4111 else if ( values.at( 0 ).isNull() && !values.at( 1 ).isNull() ) // same as above with x_at(i:=0) (vertex value is at the second position)
4112 {
4113 return fcnOldXat( QVariantList() << values[1], f, parent, node );
4114 }
4115
4116 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4117 if ( geom.isNull() )
4118 {
4119 return QVariant();
4120 }
4121
4122 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4123
4124 const QVariant v = pointAt( geom, vertexNumber, parent );
4125 if ( !v.isNull() )
4126 return QVariant( v.value<QgsPoint>().x() );
4127 else
4128 return QVariant();
4129}
4130
4131// function used for the old $ style
4132static QVariant fcnOldYat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4133{
4134 FEAT_FROM_CONTEXT( context, feature )
4135 const QgsGeometry geom = feature.geometry();
4136 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4137
4138 const QVariant v = pointAt( geom, idx, parent );
4139
4140 if ( !v.isNull() )
4141 return QVariant( v.value<QgsPoint>().y() );
4142 else
4143 return QVariant();
4144}
4145static QVariant fcnYat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4146{
4147 if ( values.at( 1 ).isNull() && !values.at( 0 ).isNull() ) // the case where the alias y_at function is called like a $ function (y_at(i))
4148 {
4149 return fcnOldYat( values, f, parent, node );
4150 }
4151 else if ( values.at( 0 ).isNull() && !values.at( 1 ).isNull() ) // same as above with x_at(i:=0) (vertex value is at the second position)
4152 {
4153 return fcnOldYat( QVariantList() << values[1], f, parent, node );
4154 }
4155
4156 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4157 if ( geom.isNull() )
4158 {
4159 return QVariant();
4160 }
4161
4162 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4163
4164 const QVariant v = pointAt( geom, vertexNumber, parent );
4165 if ( !v.isNull() )
4166 return QVariant( v.value<QgsPoint>().y() );
4167 else
4168 return QVariant();
4169}
4170
4171static QVariant fcnZat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4172{
4173 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4174 if ( geom.isNull() )
4175 {
4176 return QVariant();
4177 }
4178
4179 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4180
4181 const QVariant v = pointAt( geom, vertexNumber, parent );
4182 if ( !v.isNull() && v.value<QgsPoint>().is3D() )
4183 return QVariant( v.value<QgsPoint>().z() );
4184 else
4185 return QVariant();
4186}
4187
4188static QVariant fcnMat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4189{
4190 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4191 if ( geom.isNull() )
4192 {
4193 return QVariant();
4194 }
4195
4196 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4197
4198 const QVariant v = pointAt( geom, vertexNumber, parent );
4199 if ( !v.isNull() && v.value<QgsPoint>().isMeasure() )
4200 return QVariant( v.value<QgsPoint>().m() );
4201 else
4202 return QVariant();
4203}
4204
4205
4206static QVariant fcnGeometry( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
4207{
4208 if ( !context )
4209 return QVariant();
4210
4211 // prefer geometry from context if it's present, otherwise fallback to context's feature's geometry
4212 if ( context->hasGeometry() )
4213 return context->geometry();
4214 else
4215 {
4216 FEAT_FROM_CONTEXT( context, f )
4217 QgsGeometry geom = f.geometry();
4218 if ( !geom.isNull() )
4219 return QVariant::fromValue( geom );
4220 else
4221 return QVariant();
4222 }
4223}
4224
4225static QVariant fcnGeomFromWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4226{
4227 QString wkt = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4228 QgsGeometry geom = QgsGeometry::fromWkt( wkt );
4229 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4230 return result;
4231}
4232
4233static QVariant fcnGeomFromWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4234{
4235 const QByteArray wkb = QgsExpressionUtils::getBinaryValue( values.at( 0 ), parent );
4236 if ( wkb.isNull() )
4237 return QVariant();
4238
4239 QgsGeometry geom;
4240 geom.fromWkb( wkb );
4241 return !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4242}
4243
4244static QVariant fcnGeomFromGML( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4245{
4246 QString gml = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4247 QgsOgcUtils::Context ogcContext;
4248 if ( context )
4249 {
4250 QgsWeakMapLayerPointer mapLayerPtr {context->variable( QStringLiteral( "layer" ) ).value<QgsWeakMapLayerPointer>() };
4251 if ( mapLayerPtr )
4252 {
4253 ogcContext.layer = mapLayerPtr.data();
4254 ogcContext.transformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
4255 }
4256 }
4257 QgsGeometry geom = QgsOgcUtils::geometryFromGML( gml, ogcContext );
4258 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4259 return result;
4260}
4261
4262static QVariant fcnGeomArea( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4263{
4264 FEAT_FROM_CONTEXT( context, f )
4266 QgsDistanceArea *calc = parent->geomCalculator();
4267 if ( calc )
4268 {
4269 double area = calc->measureArea( f.geometry() );
4270 area = calc->convertAreaMeasurement( area, parent->areaUnits() );
4271 return QVariant( area );
4272 }
4273 else
4274 {
4275 return QVariant( f.geometry().area() );
4276 }
4277}
4278
4279static QVariant fcnArea( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4280{
4281 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4282
4283 if ( geom.type() != Qgis::GeometryType::Polygon )
4284 return QVariant();
4285
4286 return QVariant( geom.area() );
4287}
4288
4289static QVariant fcnGeomLength( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4290{
4291 FEAT_FROM_CONTEXT( context, f )
4293 QgsDistanceArea *calc = parent->geomCalculator();
4294 if ( calc )
4295 {
4296 double len = calc->measureLength( f.geometry() );
4297 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4298 return QVariant( len );
4299 }
4300 else
4301 {
4302 return QVariant( f.geometry().length() );
4303 }
4304}
4305
4306static QVariant fcnGeomPerimeter( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4307{
4308 FEAT_FROM_CONTEXT( context, f )
4310 QgsDistanceArea *calc = parent->geomCalculator();
4311 if ( calc )
4312 {
4313 double len = calc->measurePerimeter( f.geometry() );
4314 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4315 return QVariant( len );
4316 }
4317 else
4318 {
4319 return f.geometry().isNull() ? QVariant( 0 ) : QVariant( f.geometry().constGet()->perimeter() );
4320 }
4321}
4322
4323static QVariant fcnPerimeter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4324{
4325 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4326
4327 if ( geom.type() != Qgis::GeometryType::Polygon )
4328 return QVariant();
4329
4330 //length for polygons = perimeter
4331 return QVariant( geom.length() );
4332}
4333
4334static QVariant fcnGeomNumPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4335{
4336 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4337 return QVariant( geom.isNull() ? 0 : geom.constGet()->nCoordinates() );
4338}
4339
4340static QVariant fcnGeomNumGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4341{
4342 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4343 if ( geom.isNull() )
4344 return QVariant();
4345
4346 return QVariant( geom.constGet()->partCount() );
4347}
4348
4349static QVariant fcnGeomIsMultipart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4350{
4351 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4352 if ( geom.isNull() )
4353 return QVariant();
4354
4355 return QVariant( geom.isMultipart() );
4356}
4357
4358static QVariant fcnGeomNumInteriorRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4359{
4360 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4361
4362 if ( geom.isNull() )
4363 return QVariant();
4364
4365 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4366 if ( curvePolygon )
4367 return QVariant( curvePolygon->numInteriorRings() );
4368
4369 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4370 if ( collection )
4371 {
4372 //find first CurvePolygon in collection
4373 for ( int i = 0; i < collection->numGeometries(); ++i )
4374 {
4375 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon *>( collection->geometryN( i ) );
4376 if ( !curvePolygon )
4377 continue;
4378
4379 return QVariant( curvePolygon->isEmpty() ? 0 : curvePolygon->numInteriorRings() );
4380 }
4381 }
4382
4383 return QVariant();
4384}
4385
4386static QVariant fcnGeomNumRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4387{
4388 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4389
4390 if ( geom.isNull() )
4391 return QVariant();
4392
4393 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4394 if ( curvePolygon )
4395 return QVariant( curvePolygon->ringCount() );
4396
4397 bool foundPoly = false;
4398 int ringCount = 0;
4399 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4400 if ( collection )
4401 {
4402 //find CurvePolygons in collection
4403 for ( int i = 0; i < collection->numGeometries(); ++i )
4404 {
4405 curvePolygon = qgsgeometry_cast< QgsCurvePolygon *>( collection->geometryN( i ) );
4406 if ( !curvePolygon )
4407 continue;
4408
4409 foundPoly = true;
4410 ringCount += curvePolygon->ringCount();
4411 }
4412 }
4413
4414 if ( !foundPoly )
4415 return QVariant();
4416
4417 return QVariant( ringCount );
4418}
4419
4420static QVariant fcnBounds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4421{
4422 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4423 QgsGeometry geomBounds = QgsGeometry::fromRect( geom.boundingBox() );
4424 QVariant result = !geomBounds.isNull() ? QVariant::fromValue( geomBounds ) : QVariant();
4425 return result;
4426}
4427
4428static QVariant fcnBoundsWidth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4429{
4430 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4431 return QVariant::fromValue( geom.boundingBox().width() );
4432}
4433
4434static QVariant fcnBoundsHeight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4435{
4436 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4437 return QVariant::fromValue( geom.boundingBox().height() );
4438}
4439
4440static QVariant fcnGeometryType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4441{
4442 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4443 if ( geom.isNull() )
4444 return QVariant();
4445
4447}
4448
4449static QVariant fcnXMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4450{
4451 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4452 return QVariant::fromValue( geom.boundingBox().xMinimum() );
4453}
4454
4455static QVariant fcnXMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4456{
4457 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4458 return QVariant::fromValue( geom.boundingBox().xMaximum() );
4459}
4460
4461static QVariant fcnYMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4462{
4463 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4464 return QVariant::fromValue( geom.boundingBox().yMinimum() );
4465}
4466
4467static QVariant fcnYMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4468{
4469 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4470 return QVariant::fromValue( geom.boundingBox().yMaximum() );
4471}
4472
4473static QVariant fcnZMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4474{
4475 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4476
4477 if ( geom.isNull() || geom.isEmpty( ) )
4478 return QVariant();
4479
4480 if ( !geom.constGet()->is3D() )
4481 return QVariant();
4482
4483 double max = std::numeric_limits< double >::lowest();
4484
4485 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4486 {
4487 double z = ( *it ).z();
4488
4489 if ( max < z )
4490 max = z;
4491 }
4492
4493 if ( max == std::numeric_limits< double >::lowest() )
4494 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4495
4496 return QVariant( max );
4497}
4498
4499static QVariant fcnZMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4500{
4501 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4502
4503 if ( geom.isNull() || geom.isEmpty() )
4504 return QVariant();
4505
4506 if ( !geom.constGet()->is3D() )
4507 return QVariant();
4508
4509 double min = std::numeric_limits< double >::max();
4510
4511 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4512 {
4513 double z = ( *it ).z();
4514
4515 if ( z < min )
4516 min = z;
4517 }
4518
4519 if ( min == std::numeric_limits< double >::max() )
4520 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4521
4522 return QVariant( min );
4523}
4524
4525static QVariant fcnMMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4526{
4527 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4528
4529 if ( geom.isNull() || geom.isEmpty() )
4530 return QVariant();
4531
4532 if ( !geom.constGet()->isMeasure() )
4533 return QVariant();
4534
4535 double min = std::numeric_limits< double >::max();
4536
4537 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4538 {
4539 double m = ( *it ).m();
4540
4541 if ( m < min )
4542 min = m;
4543 }
4544
4545 if ( min == std::numeric_limits< double >::max() )
4546 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4547
4548 return QVariant( min );
4549}
4550
4551static QVariant fcnMMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4552{
4553 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4554
4555 if ( geom.isNull() || geom.isEmpty() )
4556 return QVariant();
4557
4558 if ( !geom.constGet()->isMeasure() )
4559 return QVariant();
4560
4561 double max = std::numeric_limits< double >::lowest();
4562
4563 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4564 {
4565 double m = ( *it ).m();
4566
4567 if ( max < m )
4568 max = m;
4569 }
4570
4571 if ( max == std::numeric_limits< double >::lowest() )
4572 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4573
4574 return QVariant( max );
4575}
4576
4577static QVariant fcnSinuosity( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4578{
4579 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4580 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom.constGet() );
4581 if ( !curve )
4582 {
4583 parent->setEvalErrorString( QObject::tr( "Function `sinuosity` requires a line geometry." ) );
4584 return QVariant();
4585 }
4586
4587 return QVariant( curve->sinuosity() );
4588}
4589
4590static QVariant fcnStraightDistance2d( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4591{
4592 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4593 const QgsCurve *curve = geom.constGet() ? qgsgeometry_cast< const QgsCurve * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4594 if ( !curve )
4595 {
4596 parent->setEvalErrorString( QObject::tr( "Function `straight_distance_2d` requires a line geometry or a multi line geometry with a single part." ) );
4597 return QVariant();
4598 }
4599
4600 return QVariant( curve->straightDistance2d() );
4601}
4602
4603static QVariant fcnRoundness( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4604{
4605 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4606 const QgsCurvePolygon *poly = geom.constGet() ? qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4607
4608 if ( !poly )
4609 {
4610 parent->setEvalErrorString( QObject::tr( "Function `roundness` requires a polygon geometry or a multi polygon geometry with a single part." ) );
4611 return QVariant();
4612 }
4613
4614 return QVariant( poly->roundness() );
4615}
4616
4617
4618
4619static QVariant fcnFlipCoordinates( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4620{
4621 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4622 if ( geom.isNull() )
4623 return QVariant();
4624
4625 std::unique_ptr< QgsAbstractGeometry > flipped( geom.constGet()->clone() );
4626 flipped->swapXy();
4627 return QVariant::fromValue( QgsGeometry( std::move( flipped ) ) );
4628}
4629
4630static QVariant fcnIsClosed( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4631{
4632 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4633 if ( fGeom.isNull() )
4634 return QVariant();
4635
4636 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( fGeom.constGet() );
4637 if ( !curve && fGeom.isMultipart() )
4638 {
4639 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4640 {
4641 if ( collection->numGeometries() == 1 )
4642 {
4643 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
4644 }
4645 }
4646 }
4647
4648 if ( !curve )
4649 return QVariant();
4650
4651 return QVariant::fromValue( curve->isClosed() );
4652}
4653
4654static QVariant fcnCloseLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4655{
4656 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4657
4658 if ( geom.isNull() )
4659 return QVariant();
4660
4661 QVariant result;
4662 if ( !geom.isMultipart() )
4663 {
4664 const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( geom.constGet() );
4665
4666 if ( !line )
4667 return QVariant();
4668
4669 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4670 closedLine->close();
4671
4672 result = QVariant::fromValue( QgsGeometry( std::move( closedLine ) ) );
4673 }
4674 else
4675 {
4676 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( geom.constGet() );
4677
4678 std::unique_ptr< QgsGeometryCollection > closed( collection->createEmptyWithSameType() );
4679
4680 for ( int i = 0; i < collection->numGeometries(); ++i )
4681 {
4682 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( collection->geometryN( i ) ) )
4683 {
4684 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4685 closedLine->close();
4686
4687 closed->addGeometry( closedLine.release() );
4688 }
4689 }
4690 result = QVariant::fromValue( QgsGeometry( std::move( closed ) ) );
4691 }
4692
4693 return result;
4694}
4695
4696static QVariant fcnIsEmpty( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4697{
4698 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4699 if ( fGeom.isNull() )
4700 return QVariant();
4701
4702 return QVariant::fromValue( fGeom.isEmpty() );
4703}
4704
4705static QVariant fcnIsEmptyOrNull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4706{
4707 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
4708 return QVariant::fromValue( true );
4709
4710 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4711 return QVariant::fromValue( fGeom.isNull() || fGeom.isEmpty() );
4712}
4713
4714static QVariant fcnRelate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4715{
4716 if ( values.length() < 2 || values.length() > 3 )
4717 return QVariant();
4718
4719 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4720 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4721
4722 if ( fGeom.isNull() || sGeom.isNull() )
4723 return QVariant();
4724
4725 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( fGeom.constGet() ) );
4726
4727 if ( values.length() == 2 )
4728 {
4729 //two geometry arguments, return relation
4730 QString result = engine->relate( sGeom.constGet() );
4731 return QVariant::fromValue( result );
4732 }
4733 else
4734 {
4735 //three arguments, test pattern
4736 QString pattern = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
4737 bool result = engine->relatePattern( sGeom.constGet(), pattern );
4738 return QVariant::fromValue( result );
4739 }
4740}
4741
4742static QVariant fcnBbox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4743{
4744 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4745 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4746 return fGeom.intersects( sGeom.boundingBox() ) ? TVL_True : TVL_False;
4747}
4748static QVariant fcnDisjoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4749{
4750 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4751 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4752 return fGeom.disjoint( sGeom ) ? TVL_True : TVL_False;
4753}
4754static QVariant fcnIntersects( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4755{
4756 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4757 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4758 return fGeom.intersects( sGeom ) ? TVL_True : TVL_False;
4759}
4760static QVariant fcnTouches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4761{
4762 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4763 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4764 return fGeom.touches( sGeom ) ? TVL_True : TVL_False;
4765}
4766static QVariant fcnCrosses( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4767{
4768 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4769 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4770 return fGeom.crosses( sGeom ) ? TVL_True : TVL_False;
4771}
4772static QVariant fcnContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4773{
4774 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4775 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4776 return fGeom.contains( sGeom ) ? TVL_True : TVL_False;
4777}
4778static QVariant fcnOverlaps( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4779{
4780 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4781 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4782 return fGeom.overlaps( sGeom ) ? TVL_True : TVL_False;
4783}
4784static QVariant fcnWithin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4785{
4786 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4787 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4788 return fGeom.within( sGeom ) ? TVL_True : TVL_False;
4789}
4790
4791static QVariant fcnBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4792{
4793 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4794 const double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4795 const int seg = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4796 const QString endCapString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
4797 const QString joinString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
4798 const double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
4799
4801 if ( endCapString.compare( QLatin1String( "flat" ), Qt::CaseInsensitive ) == 0 )
4802 capStyle = Qgis::EndCapStyle::Flat;
4803 else if ( endCapString.compare( QLatin1String( "square" ), Qt::CaseInsensitive ) == 0 )
4804 capStyle = Qgis::EndCapStyle::Square;
4805
4807 if ( joinString.compare( QLatin1String( "miter" ), Qt::CaseInsensitive ) == 0 )
4808 joinStyle = Qgis::JoinStyle::Miter;
4809 else if ( joinString.compare( QLatin1String( "bevel" ), Qt::CaseInsensitive ) == 0 )
4810 joinStyle = Qgis::JoinStyle::Bevel;
4811
4812 QgsGeometry geom = fGeom.buffer( dist, seg, capStyle, joinStyle, miterLimit );
4813 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4814 return result;
4815}
4816
4817static QVariant fcnForceRHR( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4818{
4819 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4820 const QgsGeometry reoriented = fGeom.forceRHR();
4821 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4822}
4823
4824static QVariant fcnForcePolygonCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4825{
4826 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4827 const QgsGeometry reoriented = fGeom.forcePolygonClockwise();
4828 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4829}
4830
4831static QVariant fcnForcePolygonCCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4832{
4833 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4834 const QgsGeometry reoriented = fGeom.forcePolygonCounterClockwise();
4835 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4836}
4837
4838static QVariant fcnWedgeBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4839{
4840 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4841 const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( fGeom.constGet() );
4842 if ( !pt && fGeom.isMultipart() )
4843 {
4844 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4845 {
4846 if ( collection->numGeometries() == 1 )
4847 {
4848 pt = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4849 }
4850 }
4851 }
4852
4853 if ( !pt )
4854 {
4855 parent->setEvalErrorString( QObject::tr( "Function `wedge_buffer` requires a point value for the center." ) );
4856 return QVariant();
4857 }
4858
4859 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4860 double width = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4861 double outerRadius = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4862 double innerRadius = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
4863
4864 QgsGeometry geom = QgsGeometry::createWedgeBuffer( *pt, azimuth, width, outerRadius, innerRadius );
4865 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4866 return result;
4867}
4868
4869static QVariant fcnTaperedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4870{
4871 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4872 if ( fGeom.type() != Qgis::GeometryType::Line )
4873 {
4874 parent->setEvalErrorString( QObject::tr( "Function `tapered_buffer` requires a line geometry." ) );
4875 return QVariant();
4876 }
4877
4878 double startWidth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4879 double endWidth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4880 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4881
4882 QgsGeometry geom = fGeom.taperedBuffer( startWidth, endWidth, segments );
4883 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4884 return result;
4885}
4886
4887static QVariant fcnBufferByM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4888{
4889 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4890 if ( fGeom.type() != Qgis::GeometryType::Line )
4891 {
4892 parent->setEvalErrorString( QObject::tr( "Function `buffer_by_m` requires a line geometry." ) );
4893 return QVariant();
4894 }
4895
4896 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) );
4897
4898 QgsGeometry geom = fGeom.variableWidthBufferByM( segments );
4899 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4900 return result;
4901}
4902
4903static QVariant fcnOffsetCurve( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4904{
4905 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4906 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4907 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4908 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4909 if ( joinInt < 1 || joinInt > 3 )
4910 return QVariant();
4911 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
4912
4913 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4914
4915 QgsGeometry geom = fGeom.offsetCurve( dist, segments, join, miterLimit );
4916 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4917 return result;
4918}
4919
4920static QVariant fcnSingleSidedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4921{
4922 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4923 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4924 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4925
4926 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4927 if ( joinInt < 1 || joinInt > 3 )
4928 return QVariant();
4929 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
4930
4931 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4932
4933 QgsGeometry geom = fGeom.singleSidedBuffer( dist, segments, Qgis::BufferSide::Left, join, miterLimit );
4934 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4935 return result;
4936}
4937
4938static QVariant fcnExtend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4939{
4940 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4941 double distStart = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4942 double distEnd = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4943
4944 QgsGeometry geom = fGeom.extendLine( distStart, distEnd );
4945 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4946 return result;
4947}
4948
4949static QVariant fcnTranslate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4950{
4951 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4952 double dx = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4953 double dy = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4954 fGeom.translate( dx, dy );
4955 return QVariant::fromValue( fGeom );
4956}
4957
4958static QVariant fcnRotate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4959{
4960 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4961 const double rotation = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4962 const QgsGeometry center = values.at( 2 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 2 ), parent )
4963 : QgsGeometry();
4964 const bool perPart = values.value( 3 ).toBool();
4965
4966 if ( center.isNull() && perPart && fGeom.isMultipart() )
4967 {
4968 // no explicit center, rotating per part
4969 // (note that we only do this branch for multipart geometries -- for singlepart geometries
4970 // the result is equivalent to setting perPart as false anyway)
4971 std::unique_ptr< QgsGeometryCollection > collection( qgsgeometry_cast< QgsGeometryCollection * >( fGeom.constGet()->clone() ) );
4972 for ( auto it = collection->parts_begin(); it != collection->parts_end(); ++it )
4973 {
4974 const QgsPointXY partCenter = ( *it )->boundingBox().center();
4975 QTransform t = QTransform::fromTranslate( partCenter.x(), partCenter.y() );
4976 t.rotate( -rotation );
4977 t.translate( -partCenter.x(), -partCenter.y() );
4978 ( *it )->transform( t );
4979 }
4980 return QVariant::fromValue( QgsGeometry( std::move( collection ) ) );
4981 }
4982 else
4983 {
4984 QgsPointXY pt;
4985 if ( center.isEmpty() )
4986 {
4987 // if center wasn't specified, use bounding box centroid
4988 pt = fGeom.boundingBox().center();
4989 }
4991 {
4992 parent->setEvalErrorString( QObject::tr( "Function 'rotate' requires a point value for the center" ) );
4993 return QVariant();
4994 }
4995 else
4996 {
4997 pt = QgsPointXY( *qgsgeometry_cast< const QgsPoint * >( center.constGet()->simplifiedTypeRef() ) );
4998 }
4999
5000 fGeom.rotate( rotation, pt );
5001 return QVariant::fromValue( fGeom );
5002 }
5003}
5004
5005static QVariant fcnScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5006{
5007 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5008 const double xScale = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5009 const double yScale = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5010 const QgsGeometry center = values.at( 3 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 3 ), parent )
5011 : QgsGeometry();
5012
5013 QgsPointXY pt;
5014 if ( center.isNull() )
5015 {
5016 // if center wasn't specified, use bounding box centroid
5017 pt = fGeom.boundingBox().center();
5018 }
5020 {
5021 parent->setEvalErrorString( QObject::tr( "Function 'scale' requires a point value for the center" ) );
5022 return QVariant();
5023 }
5024 else
5025 {
5026 pt = center.asPoint();
5027 }
5028
5029 QTransform t = QTransform::fromTranslate( pt.x(), pt.y() );
5030 t.scale( xScale, yScale );
5031 t.translate( -pt.x(), -pt.y() );
5032 fGeom.transform( t );
5033 return QVariant::fromValue( fGeom );
5034}
5035
5036static QVariant fcnAffineTransform( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5037{
5038 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5039 if ( fGeom.isNull() )
5040 {
5041 return QVariant();
5042 }
5043
5044 const double deltaX = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5045 const double deltaY = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5046
5047 const double rotationZ = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5048
5049 const double scaleX = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
5050 const double scaleY = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
5051
5052 const double deltaZ = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
5053 const double deltaM = QgsExpressionUtils::getDoubleValue( values.at( 7 ), parent );
5054 const double scaleZ = QgsExpressionUtils::getDoubleValue( values.at( 8 ), parent );
5055 const double scaleM = QgsExpressionUtils::getDoubleValue( values.at( 9 ), parent );
5056
5057 if ( deltaZ != 0.0 && !fGeom.constGet()->is3D() )
5058 {
5059 fGeom.get()->addZValue( 0 );
5060 }
5061 if ( deltaM != 0.0 && !fGeom.constGet()->isMeasure() )
5062 {
5063 fGeom.get()->addMValue( 0 );
5064 }
5065
5066 QTransform transform;
5067 transform.translate( deltaX, deltaY );
5068 transform.rotate( rotationZ );
5069 transform.scale( scaleX, scaleY );
5070 fGeom.transform( transform, deltaZ, scaleZ, deltaM, scaleM );
5071
5072 return QVariant::fromValue( fGeom );
5073}
5074
5075
5076static QVariant fcnCentroid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5077{
5078 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5079 QgsGeometry geom = fGeom.centroid();
5080 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5081 return result;
5082}
5083static QVariant fcnPointOnSurface( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5084{
5085 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5086 QgsGeometry geom = fGeom.pointOnSurface();
5087 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5088 return result;
5089}
5090
5091static QVariant fcnPoleOfInaccessibility( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5092{
5093 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5094 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5095 QgsGeometry geom = fGeom.poleOfInaccessibility( tolerance );
5096 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5097 return result;
5098}
5099
5100static QVariant fcnConvexHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5101{
5102 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5103 QgsGeometry geom = fGeom.convexHull();
5104 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5105 return result;
5106}
5107
5108#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
5109static QVariant fcnConcaveHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5110{
5111 try
5112 {
5113 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5114 const double targetPercent = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5115 const bool allowHoles = values.value( 2 ).toBool();
5116 QgsGeometry geom = fGeom.concaveHull( targetPercent, allowHoles );
5117 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5118 return result;
5119 }
5120 catch ( QgsCsException &cse )
5121 {
5122 QgsMessageLog::logMessage( QObject::tr( "Error caught in concave_hull() function: %1" ).arg( cse.what() ) );
5123 return QVariant();
5124 }
5125}
5126#endif
5127
5128static QVariant fcnMinimalCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5129{
5130 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5131 int segments = 36;
5132 if ( values.length() == 2 )
5133 segments = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5134 if ( segments < 0 )
5135 {
5136 parent->setEvalErrorString( QObject::tr( "Parameter can not be negative." ) );
5137 return QVariant();
5138 }
5139
5140 QgsGeometry geom = fGeom.minimalEnclosingCircle( static_cast<unsigned int>( segments ) );
5141 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5142 return result;
5143}
5144
5145static QVariant fcnOrientedBBox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5146{
5147 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5149 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5150 return result;
5151}
5152
5153static QVariant fcnMainAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5154{
5155 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5156
5157 // we use the angle of the oriented minimum bounding box to calculate the polygon main angle.
5158 // While ArcGIS uses a different approach ("the angle of longest collection of segments that have similar orientation"), this
5159 // yields similar results to OMBB approach under the same constraints ("this tool is meant for primarily orthogonal polygons rather than organically shaped ones.")
5160
5161 double area, angle, width, height;
5162 const QgsGeometry geom = fGeom.orientedMinimumBoundingBox( area, angle, width, height );
5163
5164 if ( geom.isNull() )
5165 {
5166 parent->setEvalErrorString( QObject::tr( "Error calculating polygon main angle: %1" ).arg( geom.lastError() ) );
5167 return QVariant();
5168 }
5169 return angle;
5170}
5171
5172static QVariant fcnDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5173{
5174 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5175 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5176 QgsGeometry geom = fGeom.difference( sGeom );
5177 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5178 return result;
5179}
5180
5181static QVariant fcnReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5182{
5183 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5184 if ( fGeom.isNull() )
5185 return QVariant();
5186
5187 QVariant result;
5188 if ( !fGeom.isMultipart() )
5189 {
5190 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( fGeom.constGet() );
5191 if ( !curve )
5192 return QVariant();
5193
5194 QgsCurve *reversed = curve->reversed();
5195 result = reversed ? QVariant::fromValue( QgsGeometry( reversed ) ) : QVariant();
5196 }
5197 else
5198 {
5199 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( fGeom.constGet() );
5200 std::unique_ptr< QgsGeometryCollection > reversed( collection->createEmptyWithSameType() );
5201 for ( int i = 0; i < collection->numGeometries(); ++i )
5202 {
5203 if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( collection->geometryN( i ) ) )
5204 {
5205 reversed->addGeometry( curve->reversed() );
5206 }
5207 else
5208 {
5209 reversed->addGeometry( collection->geometryN( i )->clone() );
5210 }
5211 }
5212 result = reversed ? QVariant::fromValue( QgsGeometry( std::move( reversed ) ) ) : QVariant();
5213 }
5214 return result;
5215}
5216
5217static QVariant fcnExteriorRing( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5218{
5219 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5220 if ( fGeom.isNull() )
5221 return QVariant();
5222
5223 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( fGeom.constGet() );
5224 if ( !curvePolygon && fGeom.isMultipart() )
5225 {
5226 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
5227 {
5228 if ( collection->numGeometries() == 1 )
5229 {
5230 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
5231 }
5232 }
5233 }
5234
5235 if ( !curvePolygon || !curvePolygon->exteriorRing() )
5236 return QVariant();
5237
5238 QgsCurve *exterior = static_cast< QgsCurve * >( curvePolygon->exteriorRing()->clone() );
5239 QVariant result = exterior ? QVariant::fromValue( QgsGeometry( exterior ) ) : QVariant();
5240 return result;
5241}
5242
5243static QVariant fcnDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5244{
5245 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5246 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5247 return QVariant( fGeom.distance( sGeom ) );
5248}
5249
5250static QVariant fcnHausdorffDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5251{
5252 QgsGeometry g1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5253 QgsGeometry g2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5254
5255 double res = -1;
5256 if ( values.length() == 3 && values.at( 2 ).isValid() )
5257 {
5258 double densify = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5259 densify = std::clamp( densify, 0.0, 1.0 );
5260 res = g1.hausdorffDistanceDensify( g2, densify );
5261 }
5262 else
5263 {
5264 res = g1.hausdorffDistance( g2 );
5265 }
5266
5267 return res > -1 ? QVariant( res ) : QVariant();
5268}
5269
5270static QVariant fcnIntersection( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5271{
5272 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5273 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5274 QgsGeometry geom = fGeom.intersection( sGeom );
5275 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5276 return result;
5277}
5278static QVariant fcnSymDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5279{
5280 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5281 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5282 QgsGeometry geom = fGeom.symDifference( sGeom );
5283 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5284 return result;
5285}
5286static QVariant fcnCombine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5287{
5288 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5289 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5290 QgsGeometry geom = fGeom.combine( sGeom );
5291 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5292 return result;
5293}
5294
5295static QVariant fcnGeomToWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5296{
5297 if ( values.length() < 1 || values.length() > 2 )
5298 return QVariant();
5299
5300 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5301 int prec = 8;
5302 if ( values.length() == 2 )
5303 prec = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5304 QString wkt = fGeom.asWkt( prec );
5305 return QVariant( wkt );
5306}
5307
5308static QVariant fcnGeomToWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5309{
5310 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5311 return fGeom.isNull() ? QVariant() : QVariant( fGeom.asWkb() );
5312}
5313
5314static QVariant fcnAzimuth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5315{
5316 if ( values.length() != 2 )
5317 {
5318 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires exactly two parameters. %n given.", nullptr, values.length() ) );
5319 return QVariant();
5320 }
5321
5322 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5323 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5324
5325 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5326 if ( !pt1 && fGeom1.isMultipart() )
5327 {
5328 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5329 {
5330 if ( collection->numGeometries() == 1 )
5331 {
5332 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5333 }
5334 }
5335 }
5336
5337 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5338 if ( !pt2 && fGeom2.isMultipart() )
5339 {
5340 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5341 {
5342 if ( collection->numGeometries() == 1 )
5343 {
5344 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5345 }
5346 }
5347 }
5348
5349 if ( !pt1 || !pt2 )
5350 {
5351 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires two points as arguments." ) );
5352 return QVariant();
5353 }
5354
5355 // Code from PostGIS
5356 if ( qgsDoubleNear( pt1->x(), pt2->x() ) )
5357 {
5358 if ( pt1->y() < pt2->y() )
5359 return 0.0;
5360 else if ( pt1->y() > pt2->y() )
5361 return M_PI;
5362 else
5363 return 0;
5364 }
5365
5366 if ( qgsDoubleNear( pt1->y(), pt2->y() ) )
5367 {
5368 if ( pt1->x() < pt2->x() )
5369 return M_PI_2;
5370 else if ( pt1->x() > pt2->x() )
5371 return M_PI + ( M_PI_2 );
5372 else
5373 return 0;
5374 }
5375
5376 if ( pt1->x() < pt2->x() )
5377 {
5378 if ( pt1->y() < pt2->y() )
5379 {
5380 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) );
5381 }
5382 else /* ( pt1->y() > pt2->y() ) - equality case handled above */
5383 {
5384 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5385 + ( M_PI_2 );
5386 }
5387 }
5388
5389 else /* ( pt1->x() > pt2->x() ) - equality case handled above */
5390 {
5391 if ( pt1->y() > pt2->y() )
5392 {
5393 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) )
5394 + M_PI;
5395 }
5396 else /* ( pt1->y() < pt2->y() ) - equality case handled above */
5397 {
5398 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5399 + ( M_PI + ( M_PI_2 ) );
5400 }
5401 }
5402}
5403
5404static QVariant fcnBearing( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5405{
5406 const QgsGeometry geom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5407 const QgsGeometry geom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5408 QString sourceCrs = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5409 QString ellipsoid = QgsExpressionUtils::getStringValue( values.at( 3 ), parent );
5410
5411 if ( geom1.isNull() || geom2.isNull() || geom1.type() != Qgis::GeometryType::Point || geom2.type() != Qgis::GeometryType::Point )
5412 {
5413 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires two valid point geometries." ) );
5414 return QVariant();
5415 }
5416
5417 const QgsPointXY point1 = geom1.asPoint();
5418 const QgsPointXY point2 = geom2.asPoint();
5419 if ( point1.isEmpty() || point2.isEmpty() )
5420 {
5421 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires point geometries or multi point geometries with a single part." ) );
5422 return QVariant();
5423 }
5424
5426 if ( context )
5427 {
5428 tContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
5429
5430 if ( sourceCrs.isEmpty() )
5431 {
5432 sourceCrs = context->variable( QStringLiteral( "layer_crs" ) ).toString();
5433 }
5434
5435 if ( ellipsoid.isEmpty() )
5436 {
5437 ellipsoid = context->variable( QStringLiteral( "project_ellipsoid" ) ).toString();
5438 }
5439 }
5440
5442 if ( !sCrs.isValid() )
5443 {
5444 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires a valid source CRS." ) );
5445 return QVariant();
5446 }
5447
5448 QgsDistanceArea da;
5449 da.setSourceCrs( sCrs, tContext );
5450 if ( !da.setEllipsoid( ellipsoid ) )
5451 {
5452 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires a valid ellipsoid acronym or ellipsoid authority ID." ) );
5453 return QVariant();
5454 }
5455
5456 try
5457 {
5458 const double bearing = da.bearing( point1, point2 );
5459 if ( std::isfinite( bearing ) )
5460 {
5461 return std::fmod( bearing + 2 * M_PI, 2 * M_PI );
5462 }
5463 }
5464 catch ( QgsCsException &cse )
5465 {
5466 QgsMessageLog::logMessage( QObject::tr( "Error caught in bearing() function: %1" ).arg( cse.what() ) );
5467 return QVariant();
5468 }
5469 return QVariant();
5470}
5471
5472static QVariant fcnProject( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5473{
5474 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5475
5477 {
5478 parent->setEvalErrorString( QStringLiteral( "'project' requires a point geometry" ) );
5479 return QVariant();
5480 }
5481
5482 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5483 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5484 double inclination = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5485
5486 const QgsPoint *p = static_cast<const QgsPoint *>( geom.constGet()->simplifiedTypeRef( ) );
5487 QgsPoint newPoint = p->project( distance, 180.0 * azimuth / M_PI, 180.0 * inclination / M_PI );
5488
5489 return QVariant::fromValue( QgsGeometry( new QgsPoint( newPoint ) ) );
5490}
5491
5492static QVariant fcnInclination( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5493{
5494 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5495 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5496
5497 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5498 if ( !pt1 && fGeom1.isMultipart() )
5499 {
5500 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5501 {
5502 if ( collection->numGeometries() == 1 )
5503 {
5504 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5505 }
5506 }
5507 }
5508 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5509 if ( !pt2 && fGeom2.isMultipart() )
5510 {
5511 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5512 {
5513 if ( collection->numGeometries() == 1 )
5514 {
5515 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5516 }
5517 }
5518 }
5519
5520 if ( ( fGeom1.type() != Qgis::GeometryType::Point ) || ( fGeom2.type() != Qgis::GeometryType::Point ) ||
5521 !pt1 || !pt2 )
5522 {
5523 parent->setEvalErrorString( QStringLiteral( "Function 'inclination' requires two points as arguments." ) );
5524 return QVariant();
5525 }
5526
5527 return pt1->inclination( *pt2 );
5528
5529}
5530
5531static QVariant fcnExtrude( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5532{
5533 if ( values.length() != 3 )
5534 return QVariant();
5535
5536 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5537 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5538 double y = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5539
5540 QgsGeometry geom = fGeom.extrude( x, y );
5541
5542 QVariant result = geom.constGet() ? QVariant::fromValue( geom ) : QVariant();
5543 return result;
5544}
5545
5546static QVariant fcnOrderParts( const QVariantList &values, const QgsExpressionContext *ctx, QgsExpression *parent, const QgsExpressionNodeFunction * )
5547{
5548 if ( values.length() < 2 )
5549 return QVariant();
5550
5551 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5552
5553 if ( !fGeom.isMultipart() )
5554 return values.at( 0 );
5555
5556 QString expString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5557 QVariant cachedExpression;
5558 if ( ctx )
5559 cachedExpression = ctx->cachedValue( expString );
5560 QgsExpression expression;
5561
5562 if ( cachedExpression.isValid() )
5563 {
5564 expression = cachedExpression.value<QgsExpression>();
5565 }
5566 else
5567 expression = QgsExpression( expString );
5568
5569 bool asc = values.value( 2 ).toBool();
5570
5571 QgsExpressionContext *unconstedContext = nullptr;
5572 QgsFeature f;
5573 if ( ctx )
5574 {
5575 // ExpressionSorter wants a modifiable expression context, but it will return it in the same shape after
5576 // so no reason to worry
5577 unconstedContext = const_cast<QgsExpressionContext *>( ctx );
5578 f = ctx->feature();
5579 }
5580 else
5581 {
5582 // If there's no context provided, create a fake one
5583 unconstedContext = new QgsExpressionContext();
5584 }
5585
5586 const QgsGeometryCollection *collection = qgsgeometry_cast<const QgsGeometryCollection *>( fGeom.constGet() );
5587 Q_ASSERT( collection ); // Should have failed the multipart check above
5588
5590 orderBy.append( QgsFeatureRequest::OrderByClause( expression, asc ) );
5591 QgsExpressionSorter sorter( orderBy );
5592
5593 QList<QgsFeature> partFeatures;
5594 partFeatures.reserve( collection->partCount() );
5595 for ( int i = 0; i < collection->partCount(); ++i )
5596 {
5597 f.setGeometry( QgsGeometry( collection->geometryN( i )->clone() ) );
5598 partFeatures << f;
5599 }
5600
5601 sorter.sortFeatures( partFeatures, unconstedContext );
5602
5603 QgsGeometryCollection *orderedGeom = qgsgeometry_cast<QgsGeometryCollection *>( fGeom.constGet()->clone() );
5604
5605 Q_ASSERT( orderedGeom );
5606
5607 while ( orderedGeom->partCount() )
5608 orderedGeom->removeGeometry( 0 );
5609
5610 for ( const QgsFeature &feature : std::as_const( partFeatures ) )
5611 {
5612 orderedGeom->addGeometry( feature.geometry().constGet()->clone() );
5613 }
5614
5615 QVariant result = QVariant::fromValue( QgsGeometry( orderedGeom ) );
5616
5617 if ( !ctx )
5618 delete unconstedContext;
5619
5620 return result;
5621}
5622
5623static QVariant fcnClosestPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5624{
5625 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5626 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5627
5628 QgsGeometry geom = fromGeom.nearestPoint( toGeom );
5629
5630 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5631 return result;
5632}
5633
5634static QVariant fcnShortestLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5635{
5636 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5637 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5638
5639 QgsGeometry geom = fromGeom.shortestLine( toGeom );
5640
5641 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5642 return result;
5643}
5644
5645static QVariant fcnLineInterpolatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5646{
5647 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5648 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5649
5650 QgsGeometry geom = lineGeom.interpolate( distance );
5651
5652 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5653 return result;
5654}
5655
5656static QVariant fcnLineSubset( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5657{
5658 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5659 if ( lineGeom.type() != Qgis::GeometryType::Line )
5660 {
5661 parent->setEvalErrorString( QObject::tr( "line_substring requires a curve geometry input" ) );
5662 return QVariant();
5663 }
5664
5665 const QgsCurve *curve = nullptr;
5666 if ( !lineGeom.isMultipart() )
5667 curve = qgsgeometry_cast< const QgsCurve * >( lineGeom.constGet() );
5668 else
5669 {
5670 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( lineGeom.constGet() ) )
5671 {
5672 if ( collection->numGeometries() > 0 )
5673 {
5674 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
5675 }
5676 }
5677 }
5678 if ( !curve )
5679 return QVariant();
5680
5681 double startDistance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5682 double endDistance = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5683
5684 std::unique_ptr< QgsCurve > substring( curve->curveSubstring( startDistance, endDistance ) );
5685 QgsGeometry result( std::move( substring ) );
5686 return !result.isNull() ? QVariant::fromValue( result ) : QVariant();
5687}
5688
5689static QVariant fcnLineInterpolateAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5690{
5691 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5692 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5693
5694 return lineGeom.interpolateAngle( distance ) * 180.0 / M_PI;
5695}
5696
5697static QVariant fcnAngleAtVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5698{
5699 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5700 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5701 if ( vertex < 0 )
5702 {
5703 //negative idx
5704 int count = geom.constGet()->nCoordinates();
5705 vertex = count + vertex;
5706 }
5707
5708 return geom.angleAtVertex( vertex ) * 180.0 / M_PI;
5709}
5710
5711static QVariant fcnDistanceToVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5712{
5713 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5714 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5715 if ( vertex < 0 )
5716 {
5717 //negative idx
5718 int count = geom.constGet()->nCoordinates();
5719 vertex = count + vertex;
5720 }
5721
5722 return geom.distanceToVertex( vertex );
5723}
5724
5725static QVariant fcnLineLocatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5726{
5727 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5728 QgsGeometry pointGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5729
5730 double distance = lineGeom.lineLocatePoint( pointGeom );
5731
5732 return distance >= 0 ? distance : QVariant();
5733}
5734
5735static QVariant fcnRound( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5736{
5737 if ( values.length() == 2 && values.at( 1 ).toInt() != 0 )
5738 {
5739 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5740 return qgsRound( number, QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
5741 }
5742
5743 if ( values.length() >= 1 )
5744 {
5745 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5746 return QVariant( qlonglong( std::round( number ) ) );
5747 }
5748
5749 return QVariant();
5750}
5751
5752static QVariant fcnPi( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5753{
5754 Q_UNUSED( values )
5755 Q_UNUSED( parent )
5756 return M_PI;
5757}
5758
5759static QVariant fcnFormatNumber( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5760{
5761 const double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5762 const int places = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5763 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5764 if ( places < 0 )
5765 {
5766 parent->setEvalErrorString( QObject::tr( "Number of places must be positive" ) );
5767 return QVariant();
5768 }
5769
5770 const bool omitGroupSeparator = values.value( 3 ).toBool();
5771 const bool trimTrailingZeros = values.value( 4 ).toBool();
5772
5773 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5774 if ( !omitGroupSeparator )
5775 locale.setNumberOptions( locale.numberOptions() & ~QLocale::NumberOption::OmitGroupSeparator );
5776 else
5777 locale.setNumberOptions( locale.numberOptions() | QLocale::NumberOption::OmitGroupSeparator );
5778
5779 QString res = locale.toString( value, 'f', places );
5780
5781 if ( trimTrailingZeros )
5782 {
5783#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5784 const QChar decimal = locale.decimalPoint();
5785 const QChar zeroDigit = locale.zeroDigit();
5786#else
5787 const QChar decimal = locale.decimalPoint().at( 0 );
5788 const QChar zeroDigit = locale.zeroDigit().at( 0 );
5789#endif
5790
5791 if ( res.contains( decimal ) )
5792 {
5793 int trimPoint = res.length() - 1;
5794
5795 while ( res.at( trimPoint ) == zeroDigit )
5796 trimPoint--;
5797
5798 if ( res.at( trimPoint ) == decimal )
5799 trimPoint--;
5800
5801 res.truncate( trimPoint + 1 );
5802 }
5803 }
5804
5805 return res;
5806}
5807
5808static QVariant fcnFormatDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5809{
5810 QDateTime datetime = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
5811 const QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5812 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5813
5814 // Convert to UTC if the format string includes a Z, as QLocale::toString() doesn't do it
5815 if ( format.indexOf( "Z" ) > 0 )
5816 datetime = datetime.toUTC();
5817
5818 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5819 return locale.toString( datetime, format );
5820}
5821
5822static QVariant fcnColorGrayscaleAverage( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
5823{
5824 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5825 int avg = ( color.red() + color.green() + color.blue() ) / 3;
5826 int alpha = color.alpha();
5827
5828 color.setRgb( avg, avg, avg, alpha );
5829
5830 return QgsSymbolLayerUtils::encodeColor( color );
5831}
5832
5833static QVariant fcnColorMixRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5834{
5835 QColor color1 = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5836 QColor color2 = QgsSymbolLayerUtils::decodeColor( values.at( 1 ).toString() );
5837 double ratio = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5838 if ( ratio > 1 )
5839 {
5840 ratio = 1;
5841 }
5842 else if ( ratio < 0 )
5843 {
5844 ratio = 0;
5845 }
5846
5847 int red = static_cast<int>( color1.red() * ( 1 - ratio ) + color2.red() * ratio );
5848 int green = static_cast<int>( color1.green() * ( 1 - ratio ) + color2.green() * ratio );
5849 int blue = static_cast<int>( color1.blue() * ( 1 - ratio ) + color2.blue() * ratio );
5850 int alpha = static_cast<int>( color1.alpha() * ( 1 - ratio ) + color2.alpha() * ratio );
5851
5852 QColor newColor( red, green, blue, alpha );
5853
5854 return QgsSymbolLayerUtils::encodeColor( newColor );
5855}
5856
5857static QVariant fcnColorRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5858{
5859 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
5860 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5861 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
5862 QColor color = QColor( red, green, blue );
5863 if ( ! color.isValid() )
5864 {
5865 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( red ).arg( green ).arg( blue ) );
5866 color = QColor( 0, 0, 0 );
5867 }
5868
5869 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5870}
5871
5872static QVariant fcnTry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5873{
5874 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
5875 QVariant value = node->eval( parent, context );
5876 if ( parent->hasEvalError() )
5877 {
5878 parent->setEvalErrorString( QString() );
5879 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
5881 value = node->eval( parent, context );
5883 }
5884 return value;
5885}
5886
5887static QVariant fcnIf( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5888{
5889 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
5891 QVariant value = node->eval( parent, context );
5893 if ( value.toBool() )
5894 {
5895 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
5897 value = node->eval( parent, context );
5899 }
5900 else
5901 {
5902 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
5904 value = node->eval( parent, context );
5906 }
5907 return value;
5908}
5909
5910static QVariant fncColorRgba( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5911{
5912 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
5913 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5914 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
5915 int alpha = QgsExpressionUtils::getNativeIntValue( values.at( 3 ), parent );
5916 QColor color = QColor( red, green, blue, alpha );
5917 if ( ! color.isValid() )
5918 {
5919 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) );
5920 color = QColor( 0, 0, 0 );
5921 }
5922 return QgsSymbolLayerUtils::encodeColor( color );
5923}
5924
5925QVariant fcnRampColor( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5926{
5927 QgsGradientColorRamp expRamp;
5928 const QgsColorRamp *ramp = nullptr;
5929 if ( values.at( 0 ).userType() == QMetaType::type( "QgsGradientColorRamp" ) )
5930 {
5931 expRamp = QgsExpressionUtils::getRamp( values.at( 0 ), parent );
5932 ramp = &expRamp;
5933 }
5934 else
5935 {
5936 QString rampName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
5937 ramp = QgsStyle::defaultStyle()->colorRampRef( rampName );
5938 if ( ! ramp )
5939 {
5940 parent->setEvalErrorString( QObject::tr( "\"%1\" is not a valid color ramp" ).arg( rampName ) );
5941 return QVariant();
5942 }
5943 }
5944
5945 double value = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5946 QColor color = ramp->color( value );
5947 return QgsSymbolLayerUtils::encodeColor( color );
5948}
5949
5950static QVariant fcnColorHsl( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5951{
5952 // Hue ranges from 0 - 360
5953 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5954 // Saturation ranges from 0 - 100
5955 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5956 // Lightness ranges from 0 - 100
5957 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5958
5959 QColor color = QColor::fromHslF( hue, saturation, lightness );
5960
5961 if ( ! color.isValid() )
5962 {
5963 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( lightness ) );
5964 color = QColor( 0, 0, 0 );
5965 }
5966
5967 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5968}
5969
5970static QVariant fncColorHsla( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5971{
5972 // Hue ranges from 0 - 360
5973 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5974 // Saturation ranges from 0 - 100
5975 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5976 // Lightness ranges from 0 - 100
5977 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5978 // Alpha ranges from 0 - 255
5979 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
5980
5981 QColor color = QColor::fromHslF( hue, saturation, lightness, alpha );
5982 if ( ! color.isValid() )
5983 {
5984 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( lightness ).arg( alpha ) );
5985 color = QColor( 0, 0, 0 );
5986 }
5987 return QgsSymbolLayerUtils::encodeColor( color );
5988}
5989
5990static QVariant fcnColorHsv( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5991{
5992 // Hue ranges from 0 - 360
5993 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5994 // Saturation ranges from 0 - 100
5995 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5996 // Value ranges from 0 - 100
5997 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5998
5999 QColor color = QColor::fromHsvF( hue, saturation, value );
6000
6001 if ( ! color.isValid() )
6002 {
6003 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( value ) );
6004 color = QColor( 0, 0, 0 );
6005 }
6006
6007 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
6008}
6009
6010static QVariant fncColorHsva( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6011{
6012 // Hue ranges from 0 - 360
6013 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
6014 // Saturation ranges from 0 - 100
6015 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6016 // Value ranges from 0 - 100
6017 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6018 // Alpha ranges from 0 - 255
6019 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
6020
6021 QColor color = QColor::fromHsvF( hue, saturation, value, alpha );
6022 if ( ! color.isValid() )
6023 {
6024 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( value ).arg( alpha ) );
6025 color = QColor( 0, 0, 0 );
6026 }
6027 return QgsSymbolLayerUtils::encodeColor( color );
6028}
6029
6030static QVariant fcnColorCmyk( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6031{
6032 // Cyan ranges from 0 - 100
6033 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
6034 // Magenta ranges from 0 - 100
6035 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6036 // Yellow ranges from 0 - 100
6037 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6038 // Black ranges from 0 - 100
6039 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
6040
6041 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black );
6042
6043 if ( ! color.isValid() )
6044 {
6045 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ) );
6046 color = QColor( 0, 0, 0 );
6047 }
6048
6049 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
6050}
6051
6052static QVariant fncColorCmyka( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6053{
6054 // Cyan ranges from 0 - 100
6055 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
6056 // Magenta ranges from 0 - 100
6057 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6058 // Yellow ranges from 0 - 100
6059 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6060 // Black ranges from 0 - 100
6061 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
6062 // Alpha ranges from 0 - 255
6063 double alpha = QgsExpressionUtils::getIntValue( values.at( 4 ), parent ) / 255.0;
6064
6065 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black, alpha );
6066 if ( ! color.isValid() )
6067 {
6068 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4:%5' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ).arg( alpha ) );
6069 color = QColor( 0, 0, 0 );
6070 }
6071 return QgsSymbolLayerUtils::encodeColor( color );
6072}
6073
6074static QVariant fncColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6075{
6076 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6077 if ( ! color.isValid() )
6078 {
6079 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6080 return QVariant();
6081 }
6082
6083 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6084 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
6085 return color.red();
6086 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6087 return color.green();
6088 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6089 return color.blue();
6090 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6091 return color.alpha();
6092 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6093 return static_cast< double >( color.hsvHueF() * 360 );
6094 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6095 return static_cast< double >( color.hsvSaturationF() * 100 );
6096 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6097 return static_cast< double >( color.valueF() * 100 );
6098 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6099 return static_cast< double >( color.hslHueF() * 360 );
6100 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6101 return static_cast< double >( color.hslSaturationF() * 100 );
6102 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6103 return static_cast< double >( color.lightnessF() * 100 );
6104 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6105 return static_cast< double >( color.cyanF() * 100 );
6106 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6107 return static_cast< double >( color.magentaF() * 100 );
6108 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6109 return static_cast< double >( color.yellowF() * 100 );
6110 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6111 return static_cast< double >( color.blackF() * 100 );
6112
6113 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6114 return QVariant();
6115}
6116
6117static QVariant fcnCreateRamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6118{
6119 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
6120 if ( map.empty() )
6121 {
6122 parent->setEvalErrorString( QObject::tr( "A minimum of two colors is required to create a ramp" ) );
6123 return QVariant();
6124 }
6125
6126 QList< QColor > colors;
6128 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
6129 {
6130 colors << QgsSymbolLayerUtils::decodeColor( it.value().toString() );
6131 if ( !colors.last().isValid() )
6132 {
6133 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( it.value().toString() ) );
6134 return QVariant();
6135 }
6136
6137 double step = it.key().toDouble();
6138 if ( it == map.constBegin() )
6139 {
6140 if ( step != 0.0 )
6141 stops << QgsGradientStop( step, colors.last() );
6142 }
6143 else if ( it == map.constEnd() )
6144 {
6145 if ( step != 1.0 )
6146 stops << QgsGradientStop( step, colors.last() );
6147 }
6148 else
6149 {
6150 stops << QgsGradientStop( step, colors.last() );
6151 }
6152 }
6153 bool discrete = values.at( 1 ).toBool();
6154
6155 if ( colors.empty() )
6156 return QVariant();
6157
6158 return QVariant::fromValue( QgsGradientColorRamp( colors.first(), colors.last(), discrete, stops ) );
6159}
6160
6161static QVariant fncSetColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6162{
6163 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6164 if ( ! color.isValid() )
6165 {
6166 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6167 return QVariant();
6168 }
6169
6170 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6171 int value = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
6172 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
6173 color.setRed( std::clamp( value, 0, 255 ) );
6174 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6175 color.setGreen( std::clamp( value, 0, 255 ) );
6176 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6177 color.setBlue( std::clamp( value, 0, 255 ) );
6178 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6179 color.setAlpha( std::clamp( value, 0, 255 ) );
6180 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6181 color.setHsv( std::clamp( value, 0, 359 ), color.hsvSaturation(), color.value(), color.alpha() );
6182 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6183 color.setHsvF( color.hsvHueF(), std::clamp( value, 0, 100 ) / 100.0, color.valueF(), color.alphaF() );
6184 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6185 color.setHsvF( color.hsvHueF(), color.hsvSaturationF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6186 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6187 color.setHsl( std::clamp( value, 0, 359 ), color.hslSaturation(), color.lightness(), color.alpha() );
6188 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6189 color.setHslF( color.hslHueF(), std::clamp( value, 0, 100 ) / 100.0, color.lightnessF(), color.alphaF() );
6190 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6191 color.setHslF( color.hslHueF(), color.hslSaturationF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6192 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6193 color.setCmykF( std::clamp( value, 0, 100 ) / 100.0, color.magentaF(), color.yellowF(), color.blackF(), color.alphaF() );
6194 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6195 color.setCmykF( color.cyanF(), std::clamp( value, 0, 100 ) / 100.0, color.yellowF(), color.blackF(), color.alphaF() );
6196 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6197 color.setCmykF( color.cyanF(), color.magentaF(), std::clamp( value, 0, 100 ) / 100.0, color.blackF(), color.alphaF() );
6198 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6199 color.setCmykF( color.cyanF(), color.magentaF(), color.yellowF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6200 else
6201 {
6202 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6203 return QVariant();
6204 }
6205 return QgsSymbolLayerUtils::encodeColor( color );
6206}
6207
6208static QVariant fncDarker( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6209{
6210 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6211 if ( ! color.isValid() )
6212 {
6213 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6214 return QVariant();
6215 }
6216
6217 color = color.darker( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6218
6219 return QgsSymbolLayerUtils::encodeColor( color );
6220}
6221
6222static QVariant fncLighter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6223{
6224 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6225 if ( ! color.isValid() )
6226 {
6227 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6228 return QVariant();
6229 }
6230
6231 color = color.lighter( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6232
6233 return QgsSymbolLayerUtils::encodeColor( color );
6234}
6235
6236static QVariant fcnGetGeometry( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6237{
6238 QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6239 QgsGeometry geom = feat.geometry();
6240 if ( !geom.isNull() )
6241 return QVariant::fromValue( geom );
6242 return QVariant();
6243}
6244
6245static QVariant fcnGetFeatureId( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6246{
6247 const QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6248 if ( !feat.isValid() )
6249 return QVariant();
6250 return feat.id();
6251}
6252
6253static QVariant fcnTransformGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6254{
6255 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
6256 QString sAuthId = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6257 QString dAuthId = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
6258
6260 if ( ! s.isValid() )
6261 return QVariant::fromValue( fGeom );
6263 if ( ! d.isValid() )
6264 return QVariant::fromValue( fGeom );
6265
6267 if ( context )
6268 tContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
6269 QgsCoordinateTransform t( s, d, tContext );
6270 try
6271 {
6273 return QVariant::fromValue( fGeom );
6274 }
6275 catch ( QgsCsException &cse )
6276 {
6277 QgsMessageLog::logMessage( QObject::tr( "Transform error caught in transform() function: %1" ).arg( cse.what() ) );
6278 return QVariant();
6279 }
6280 return QVariant();
6281}
6282
6283
6284static QVariant fcnGetFeatureById( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6285{
6286 bool foundLayer = false;
6287 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6288
6289 //no layer found
6290 if ( !featureSource || !foundLayer )
6291 {
6292 return QVariant();
6293 }
6294
6295 const QgsFeatureId fid = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
6296
6298 req.setFilterFid( fid );
6299 req.setTimeout( 10000 );
6300 req.setRequestMayBeNested( true );
6301 if ( context )
6302 req.setFeedback( context->feedback() );
6303 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6304
6305 QgsFeature fet;
6306 QVariant result;
6307 if ( fIt.nextFeature( fet ) )
6308 result = QVariant::fromValue( fet );
6309
6310 return result;
6311}
6312
6313static QVariant fcnGetFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6314{
6315 //arguments: 1. layer id / name, 2. key attribute, 3. eq value
6316 bool foundLayer = false;
6317 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6318
6319 //no layer found
6320 if ( !featureSource || !foundLayer )
6321 {
6322 return QVariant();
6323 }
6325 QString cacheValueKey;
6326 if ( values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
6327 {
6328 QVariantMap attributeMap = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
6329
6330 QMap <QString, QVariant>::const_iterator i = attributeMap.constBegin();
6331 QString filterString;
6332 for ( ; i != attributeMap.constEnd(); ++i )
6333 {
6334 if ( !filterString.isEmpty() )
6335 {
6336 filterString.append( " AND " );
6337 }
6338 filterString.append( QgsExpression::createFieldEqualityExpression( i.key(), i.value() ) );
6339 }
6340 cacheValueKey = QStringLiteral( "getfeature:%1:%2" ).arg( featureSource->id(), filterString );
6341 if ( context && context->hasCachedValue( cacheValueKey ) )
6342 {
6343 return context->cachedValue( cacheValueKey );
6344 }
6345 req.setFilterExpression( filterString );
6346 }
6347 else
6348 {
6349 QString attribute = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6350 int attributeId = featureSource->fields().lookupField( attribute );
6351 if ( attributeId == -1 )
6352 {
6353 return QVariant();
6354 }
6355
6356 const QVariant &attVal = values.at( 2 );
6357
6358 cacheValueKey = QStringLiteral( "getfeature:%1:%2:%3" ).arg( featureSource->id(), QString::number( attributeId ), attVal.toString() );
6359 if ( context && context->hasCachedValue( cacheValueKey ) )
6360 {
6361 return context->cachedValue( cacheValueKey );
6362 }
6363
6365 }
6366 req.setLimit( 1 );
6367 req.setTimeout( 10000 );
6368 req.setRequestMayBeNested( true );
6369 if ( context )
6370 req.setFeedback( context->feedback() );
6371 if ( !parent->needsGeometry() )
6372 {
6374 }
6375 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6376
6377 QgsFeature fet;
6378 QVariant res;
6379 if ( fIt.nextFeature( fet ) )
6380 {
6381 res = QVariant::fromValue( fet );
6382 }
6383
6384 if ( context )
6385 context->setCachedValue( cacheValueKey, res );
6386 return res;
6387}
6388
6389static QVariant fcnRepresentValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6390{
6391 QVariant result;
6392 QString fieldName;
6393
6394 if ( context )
6395 {
6396 if ( !values.isEmpty() )
6397 {
6398 QgsExpressionNodeColumnRef *col = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
6399 if ( col && ( values.size() == 1 || !values.at( 1 ).isValid() ) )
6400 fieldName = col->name();
6401 else if ( values.size() == 2 )
6402 fieldName = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6403 }
6404
6405 QVariant value = values.at( 0 );
6406
6407 const QgsFields fields = context->fields();
6408 int fieldIndex = fields.lookupField( fieldName );
6409
6410 if ( fieldIndex == -1 )
6411 {
6412 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: Field not found %2" ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6413 }
6414 else
6415 {
6416 // TODO this function is NOT thread safe
6418 QgsVectorLayer *layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
6420
6421 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName, value.toString() );
6422 if ( context->hasCachedValue( cacheValueKey ) )
6423 {
6424 return context->cachedValue( cacheValueKey );
6425 }
6426
6427 const QgsEditorWidgetSetup setup = fields.at( fieldIndex ).editorWidgetSetup();
6429
6430 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName );
6431
6432 QVariant cache;
6433 if ( !context->hasCachedValue( cacheKey ) )
6434 {
6435 cache = formatter->createCache( layer, fieldIndex, setup.config() );
6436 context->setCachedValue( cacheKey, cache );
6437 }
6438 else
6439 cache = context->cachedValue( cacheKey );
6440
6441 result = formatter->representValue( layer, fieldIndex, setup.config(), cache, value );
6442
6443 context->setCachedValue( cacheValueKey, result );
6444 }
6445 }
6446 else
6447 {
6448 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: function cannot be evaluated without a context." ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6449 }
6450
6451 return result;
6452}
6453
6454static QVariant fcnMimeType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6455{
6456 const QVariant data = values.at( 0 );
6457 const QMimeDatabase db;
6458 return db.mimeTypeForData( data.toByteArray() ).name();
6459}
6460
6461static QVariant fcnGetLayerProperty( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6462{
6463 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6464
6465 bool foundLayer = false;
6466 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [layerProperty]( QgsMapLayer * layer )-> QVariant
6467 {
6468 if ( !layer )
6469 return QVariant();
6470
6471 // here, we always prefer the layer metadata values over the older server-specific published values
6472 if ( QString::compare( layerProperty, QStringLiteral( "name" ), Qt::CaseInsensitive ) == 0 )
6473 return layer->name();
6474 else if ( QString::compare( layerProperty, QStringLiteral( "id" ), Qt::CaseInsensitive ) == 0 )
6475 return layer->id();
6476 else if ( QString::compare( layerProperty, QStringLiteral( "title" ), Qt::CaseInsensitive ) == 0 )
6477 return !layer->metadata().title().isEmpty() ? layer->metadata().title() : layer->serverProperties()->title();
6478 else if ( QString::compare( layerProperty, QStringLiteral( "abstract" ), Qt::CaseInsensitive ) == 0 )
6479 return !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->serverProperties()->abstract();
6480 else if ( QString::compare( layerProperty, QStringLiteral( "keywords" ), Qt::CaseInsensitive ) == 0 )
6481 {
6482 QStringList keywords;
6483 const QgsAbstractMetadataBase::KeywordMap keywordMap = layer->metadata().keywords();
6484 for ( auto it = keywordMap.constBegin(); it != keywordMap.constEnd(); ++it )
6485 {
6486 keywords.append( it.value() );
6487 }
6488 if ( !keywords.isEmpty() )
6489 return keywords;
6490 return layer->serverProperties()->keywordList();
6491 }
6492 else if ( QString::compare( layerProperty, QStringLiteral( "data_url" ), Qt::CaseInsensitive ) == 0 )
6493 return layer->serverProperties()->dataUrl();
6494 else if ( QString::compare( layerProperty, QStringLiteral( "attribution" ), Qt::CaseInsensitive ) == 0 )
6495 {
6496 return !layer->metadata().rights().isEmpty() ? QVariant( layer->metadata().rights() ) : QVariant( layer->serverProperties()->attribution() );
6497 }
6498 else if ( QString::compare( layerProperty, QStringLiteral( "attribution_url" ), Qt::CaseInsensitive ) == 0 )
6499 return layer->serverProperties()->attributionUrl();
6500 else if ( QString::compare( layerProperty, QStringLiteral( "source" ), Qt::CaseInsensitive ) == 0 )
6501 return layer->publicSource();
6502 else if ( QString::compare( layerProperty, QStringLiteral( "min_scale" ), Qt::CaseInsensitive ) == 0 )
6503 return layer->minimumScale();
6504 else if ( QString::compare( layerProperty, QStringLiteral( "max_scale" ), Qt::CaseInsensitive ) == 0 )
6505 return layer->maximumScale();
6506 else if ( QString::compare( layerProperty, QStringLiteral( "is_editable" ), Qt::CaseInsensitive ) == 0 )
6507 return layer->isEditable();
6508 else if ( QString::compare( layerProperty, QStringLiteral( "crs" ), Qt::CaseInsensitive ) == 0 )
6509 return layer->crs().authid();
6510 else if ( QString::compare( layerProperty, QStringLiteral( "crs_definition" ), Qt::CaseInsensitive ) == 0 )
6511 return layer->crs().toProj();
6512 else if ( QString::compare( layerProperty, QStringLiteral( "crs_description" ), Qt::CaseInsensitive ) == 0 )
6513 return layer->crs().description();
6514 else if ( QString::compare( layerProperty, QStringLiteral( "crs_ellipsoid" ), Qt::CaseInsensitive ) == 0 )
6515 return layer->crs().ellipsoidAcronym();
6516 else if ( QString::compare( layerProperty, QStringLiteral( "extent" ), Qt::CaseInsensitive ) == 0 )
6517 {
6518 QgsGeometry extentGeom = QgsGeometry::fromRect( layer->extent() );
6519 QVariant result = QVariant::fromValue( extentGeom );
6520 return result;
6521 }
6522 else if ( QString::compare( layerProperty, QStringLiteral( "distance_units" ), Qt::CaseInsensitive ) == 0 )
6523 return QgsUnitTypes::encodeUnit( layer->crs().mapUnits() );
6524 else if ( QString::compare( layerProperty, QStringLiteral( "path" ), Qt::CaseInsensitive ) == 0 )
6525 {
6526 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
6527 return decodedUri.value( QStringLiteral( "path" ) );
6528 }
6529 else if ( QString::compare( layerProperty, QStringLiteral( "type" ), Qt::CaseInsensitive ) == 0 )
6530 {
6531 switch ( layer->type() )
6532 {
6534 return QCoreApplication::translate( "expressions", "Vector" );
6536 return QCoreApplication::translate( "expressions", "Raster" );
6538 return QCoreApplication::translate( "expressions", "Mesh" );
6540 return QCoreApplication::translate( "expressions", "Vector Tile" );
6542 return QCoreApplication::translate( "expressions", "Plugin" );
6544 return QCoreApplication::translate( "expressions", "Annotation" );
6546 return QCoreApplication::translate( "expressions", "Point Cloud" );
6548 return QCoreApplication::translate( "expressions", "Group" );
6550 return QCoreApplication::translate( "expressions", "Tiled Scene" );
6551 }
6552 }
6553 else
6554 {
6555 //vector layer methods
6556 QgsVectorLayer *vLayer = qobject_cast< QgsVectorLayer * >( layer );
6557 if ( vLayer )
6558 {
6559 if ( QString::compare( layerProperty, QStringLiteral( "storage_type" ), Qt::CaseInsensitive ) == 0 )
6560 return vLayer->storageType();
6561 else if ( QString::compare( layerProperty, QStringLiteral( "geometry_type" ), Qt::CaseInsensitive ) == 0 )
6563 else if ( QString::compare( layerProperty, QStringLiteral( "feature_count" ), Qt::CaseInsensitive ) == 0 )
6564 return QVariant::fromValue( vLayer->featureCount() );
6565 }
6566 }
6567
6568 return QVariant();
6569 }, foundLayer );
6570
6571 if ( !foundLayer )
6572 return QVariant();
6573 else
6574 return res;
6575}
6576
6577static QVariant fcnDecodeUri( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6578{
6579 const QString uriPart = values.at( 1 ).toString();
6580
6581 bool foundLayer = false;
6582
6583 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, uriPart]( QgsMapLayer * layer )-> QVariant
6584 {
6585 if ( !layer->dataProvider() )
6586 {
6587 parent->setEvalErrorString( QObject::tr( "Layer %1 has invalid data provider" ).arg( layer->name() ) );
6588 return QVariant();
6589 }
6590
6591 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
6592
6593 if ( !uriPart.isNull() )
6594 {
6595 return decodedUri.value( uriPart );
6596 }
6597 else
6598 {
6599 return decodedUri;
6600 }
6601 }, foundLayer );
6602
6603 if ( !foundLayer )
6604 {
6605 parent->setEvalErrorString( QObject::tr( "Function `decode_uri` requires a valid layer." ) );
6606 return QVariant();
6607 }
6608 else
6609 {
6610 return res;
6611 }
6612}
6613
6614static QVariant fcnGetRasterBandStat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6615{
6616 const int band = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6617 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
6618
6619 bool foundLayer = false;
6620 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, band, layerProperty]( QgsMapLayer * layer )-> QVariant
6621 {
6622 QgsRasterLayer *rl = qobject_cast< QgsRasterLayer * >( layer );
6623 if ( !rl )
6624 return QVariant();
6625
6626 if ( band < 1 || band > rl->bandCount() )
6627 {
6628 parent->setEvalErrorString( QObject::tr( "Invalid band number %1 for layer" ).arg( band ) );
6629 return QVariant();
6630 }
6631
6633
6634 if ( QString::compare( layerProperty, QStringLiteral( "avg" ), Qt::CaseInsensitive ) == 0 )
6636 else if ( QString::compare( layerProperty, QStringLiteral( "stdev" ), Qt::CaseInsensitive ) == 0 )
6638 else if ( QString::compare( layerProperty, QStringLiteral( "min" ), Qt::CaseInsensitive ) == 0 )
6640 else if ( QString::compare( layerProperty, QStringLiteral( "max" ), Qt::CaseInsensitive ) == 0 )
6642 else if ( QString::compare( layerProperty, QStringLiteral( "range" ), Qt::CaseInsensitive ) == 0 )
6644 else if ( QString::compare( layerProperty, QStringLiteral( "sum" ), Qt::CaseInsensitive ) == 0 )
6646 else
6647 {
6648 parent->setEvalErrorString( QObject::tr( "Invalid raster statistic: '%1'" ).arg( layerProperty ) );
6649 return QVariant();
6650 }
6651
6652 QgsRasterBandStats stats = rl->dataProvider()->bandStatistics( band, stat );
6653 switch ( stat )
6654 {
6656 return stats.mean;
6658 return stats.stdDev;
6660 return stats.minimumValue;
6662 return stats.maximumValue;
6664 return stats.range;
6666 return stats.sum;
6667 default:
6668 break;
6669 }
6670 return QVariant();
6671 }, foundLayer );
6672
6673 if ( !foundLayer )
6674 {
6675#if 0 // for consistency with other functions we should raise an error here, but for compatibility with old projects we don't
6676 parent->setEvalErrorString( QObject::tr( "Function `raster_statistic` requires a valid raster layer." ) );
6677#endif
6678 return QVariant();
6679 }
6680 else
6681 {
6682 return res;
6683 }
6684}
6685
6686static QVariant fcnArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6687{
6688 return values;
6689}
6690
6691static QVariant fcnArraySort( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6692{
6693 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6694 bool ascending = values.value( 1 ).toBool();
6695 std::sort( list.begin(), list.end(), [ascending]( QVariant a, QVariant b ) -> bool { return ( !ascending ? qgsVariantLessThan( b, a ) : qgsVariantLessThan( a, b ) ); } );
6696 return list;
6697}
6698
6699static QVariant fcnArrayLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6700{
6701 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).length();
6702}
6703
6704static QVariant fcnArrayContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6705{
6706 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).contains( values.at( 1 ) ) );
6707}
6708
6709static QVariant fcnArrayCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6710{
6711 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).count( values.at( 1 ) ) );
6712}
6713
6714static QVariant fcnArrayAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6715{
6716 QVariantList listA = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6717 QVariantList listB = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
6718 int match = 0;
6719 for ( const auto &item : listB )
6720 {
6721 if ( listA.contains( item ) )
6722 match++;
6723 }
6724
6725 return QVariant( match == listB.count() );
6726}
6727
6728static QVariant fcnArrayFind( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6729{
6730 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).indexOf( values.at( 1 ) );
6731}
6732
6733static QVariant fcnArrayGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6734{
6735 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6736 const int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6737 if ( pos < list.length() && pos >= 0 ) return list.at( pos );
6738 else if ( pos < 0 && ( list.length() + pos ) >= 0 )
6739 return list.at( list.length() + pos );
6740 return QVariant();
6741}
6742
6743static QVariant fcnArrayFirst( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6744{
6745 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6746 return list.value( 0 );
6747}
6748
6749static QVariant fcnArrayLast( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6750{
6751 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6752 return list.value( list.size() - 1 );
6753}
6754
6755static QVariant fcnArrayMinimum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6756{
6757 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6758 return list.isEmpty() ? QVariant() : *std::min_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6759}
6760
6761static QVariant fcnArrayMaximum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6762{
6763 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6764 return list.isEmpty() ? QVariant() : *std::max_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6765}
6766
6767static QVariant fcnArrayMean( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6768{
6769 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6770 int i = 0;
6771 double total = 0.0;
6772 for ( const QVariant &item : list )
6773 {
6774 switch ( item.userType() )
6775 {
6776 case QMetaType::Int:
6777 case QMetaType::UInt:
6778 case QMetaType::LongLong:
6779 case QMetaType::ULongLong:
6780 case QMetaType::Float:
6781 case QMetaType::Double:
6782 total += item.toDouble();
6783 ++i;
6784 break;
6785 }
6786 }
6787 return i == 0 ? QVariant() : total / i;
6788}
6789
6790static QVariant fcnArrayMedian( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6791{
6792 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6793 QVariantList numbers;
6794 for ( const auto &item : list )
6795 {
6796 switch ( item.userType() )
6797 {
6798 case QMetaType::Int:
6799 case QMetaType::UInt:
6800 case QMetaType::LongLong:
6801 case QMetaType::ULongLong:
6802 case QMetaType::Float:
6803 case QMetaType::Double:
6804 numbers.append( item );
6805 break;
6806 }
6807 }
6808 std::sort( numbers.begin(), numbers.end(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6809 const int count = numbers.count();
6810 if ( count == 0 )
6811 {
6812 return QVariant();
6813 }
6814 else if ( count % 2 )
6815 {
6816 return numbers.at( count / 2 );
6817 }
6818 else
6819 {
6820 return ( numbers.at( count / 2 - 1 ).toDouble() + numbers.at( count / 2 ).toDouble() ) / 2;
6821 }
6822}
6823
6824static QVariant fcnArraySum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6825{
6826 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6827 int i = 0;
6828 double total = 0.0;
6829 for ( const QVariant &item : list )
6830 {
6831 switch ( item.userType() )
6832 {
6833 case QMetaType::Int:
6834 case QMetaType::UInt:
6835 case QMetaType::LongLong:
6836 case QMetaType::ULongLong:
6837 case QMetaType::Float:
6838 case QMetaType::Double:
6839 total += item.toDouble();
6840 ++i;
6841 break;
6842 }
6843 }
6844 return i == 0 ? QVariant() : total;
6845}
6846
6847static QVariant convertToSameType( const QVariant &value, QMetaType::Type type )
6848{
6849 QVariant result = value;
6850 result.convert( static_cast<int>( type ) );
6851 return result;
6852}
6853
6854static QVariant fcnArrayMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6855{
6856 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6857 QHash< QVariant, int > hash;
6858 for ( const auto &item : list )
6859 {
6860 ++hash[item];
6861 }
6862 const QList< int > occurrences = hash.values();
6863 if ( occurrences.empty() )
6864 return QVariantList();
6865
6866 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
6867
6868 const QString option = values.at( 1 ).toString();
6869 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
6870 {
6871 return convertToSameType( hash.keys( maxValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6872 }
6873 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
6874 {
6875 if ( hash.isEmpty() )
6876 return QVariant();
6877
6878 return QVariant( hash.key( maxValue ) );
6879 }
6880 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
6881 {
6882 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( maxValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) ), context, parent, node );
6883 }
6884 else if ( option.compare( QLatin1String( "real_majority" ), Qt::CaseInsensitive ) == 0 )
6885 {
6886 if ( maxValue * 2 <= list.size() )
6887 return QVariant();
6888
6889 return QVariant( hash.key( maxValue ) );
6890 }
6891 else
6892 {
6893 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
6894 return QVariant();
6895 }
6896}
6897
6898static QVariant fcnArrayMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6899{
6900 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6901 QHash< QVariant, int > hash;
6902 for ( const auto &item : list )
6903 {
6904 ++hash[item];
6905 }
6906 const QList< int > occurrences = hash.values();
6907 if ( occurrences.empty() )
6908 return QVariantList();
6909
6910 const int minValue = *std::min_element( occurrences.constBegin(), occurrences.constEnd() );
6911
6912 const QString option = values.at( 1 ).toString();
6913 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
6914 {
6915 return convertToSameType( hash.keys( minValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6916 }
6917 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
6918 {
6919 if ( hash.isEmpty() )
6920 return QVariant();
6921
6922 return QVariant( hash.key( minValue ) );
6923 }
6924 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
6925 {
6926 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( minValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) ), context, parent, node );
6927 }
6928 else if ( option.compare( QLatin1String( "real_minority" ), Qt::CaseInsensitive ) == 0 )
6929 {
6930 if ( hash.isEmpty() )
6931 return QVariant();
6932
6933 // Remove the majority, all others are minority
6934 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
6935 if ( maxValue * 2 > list.size() )
6936 hash.remove( hash.key( maxValue ) );
6937
6938 return convertToSameType( hash.keys(), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6939 }
6940 else
6941 {
6942 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
6943 return QVariant();
6944 }
6945}
6946
6947static QVariant fcnArrayAppend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6948{
6949 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6950 list.append( values.at( 1 ) );
6951 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6952}
6953
6954static QVariant fcnArrayPrepend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6955{
6956 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6957 list.prepend( values.at( 1 ) );
6958 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6959}
6960
6961static QVariant fcnArrayInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6962{
6963 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6964 list.insert( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), values.at( 2 ) );
6965 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6966}
6967
6968static QVariant fcnArrayRemoveAt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6969{
6970 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6971 int position = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6972 if ( position < 0 )
6973 position = position + list.length();
6974 if ( position >= 0 && position < list.length() )
6975 list.removeAt( position );
6976 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6977}
6978
6979static QVariant fcnArrayRemoveAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6980{
6981 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
6982 return QVariant();
6983
6984 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6985
6986 const QVariant toRemove = values.at( 1 );
6987 if ( QgsVariantUtils::isNull( toRemove ) )
6988 {
6989 list.erase( std::remove_if( list.begin(), list.end(), []( const QVariant & element )
6990 {
6991 return QgsVariantUtils::isNull( element );
6992 } ), list.end() );
6993 }
6994 else
6995 {
6996 list.removeAll( toRemove );
6997 }
6998 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
6999}
7000
7001static QVariant fcnArrayReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7002{
7003 if ( values.count() == 2 && values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
7004 {
7005 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
7006
7007 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7008 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
7009 {
7010 int index = list.indexOf( it.key() );
7011 while ( index >= 0 )
7012 {
7013 list.replace( index, it.value() );
7014 index = list.indexOf( it.key() );
7015 }
7016 }
7017
7018 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7019 }
7020 else if ( values.count() == 3 )
7021 {
7022 QVariantList before;
7023 QVariantList after;
7024 bool isSingleReplacement = false;
7025
7026 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).userType() != QMetaType::Type::QStringList )
7027 {
7028 before = QVariantList() << values.at( 1 );
7029 }
7030 else
7031 {
7032 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
7033 }
7034
7035 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
7036 {
7037 after = QVariantList() << values.at( 2 );
7038 isSingleReplacement = true;
7039 }
7040 else
7041 {
7042 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
7043 }
7044
7045 if ( !isSingleReplacement && before.length() != after.length() )
7046 {
7047 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
7048 return QVariant();
7049 }
7050
7051 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7052 for ( int i = 0; i < before.length(); i++ )
7053 {
7054 int index = list.indexOf( before.at( i ) );
7055 while ( index >= 0 )
7056 {
7057 list.replace( index, after.at( isSingleReplacement ? 0 : i ) );
7058 index = list.indexOf( before.at( i ) );
7059 }
7060 }
7061
7062 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7063 }
7064 else
7065 {
7066 parent->setEvalErrorString( QObject::tr( "Function array_replace requires 2 or 3 arguments" ) );
7067 return QVariant();
7068 }
7069}
7070
7071static QVariant fcnArrayPrioritize( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7072{
7073 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7074 QVariantList list_new;
7075
7076 for ( const QVariant &cur : QgsExpressionUtils::getListValue( values.at( 1 ), parent ) )
7077 {
7078 while ( list.removeOne( cur ) )
7079 {
7080 list_new.append( cur );
7081 }
7082 }
7083
7084 list_new.append( list );
7085
7086 return convertToSameType( list_new, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7087}
7088
7089static QVariant fcnArrayCat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7090{
7091 QVariantList list;
7092 for ( const QVariant &cur : values )
7093 {
7094 list += QgsExpressionUtils::getListValue( cur, parent );
7095 }
7096 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7097}
7098
7099static QVariant fcnArraySlice( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7100{
7101 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7102 int start_pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
7103 const int end_pos = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
7104 int slice_length = 0;
7105 // negative positions means positions taken relative to the end of the array
7106 if ( start_pos < 0 )
7107 {
7108 start_pos = list.length() + start_pos;
7109 }
7110 if ( end_pos >= 0 )
7111 {
7112 slice_length = end_pos - start_pos + 1;
7113 }
7114 else
7115 {
7116 slice_length = list.length() + end_pos - start_pos + 1;
7117 }
7118 //avoid negative lengths in QList.mid function
7119 if ( slice_length < 0 )
7120 {
7121 slice_length = 0;
7122 }
7123 list = list.mid( start_pos, slice_length );
7124 return list;
7125}
7126
7127static QVariant fcnArrayReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7128{
7129 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7130 std::reverse( list.begin(), list.end() );
7131 return list;
7132}
7133
7134static QVariant fcnArrayIntersect( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7135{
7136 const QVariantList array1 = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7137 const QVariantList array2 = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
7138 for ( const QVariant &cur : array2 )
7139 {
7140 if ( array1.contains( cur ) )
7141 return QVariant( true );
7142 }
7143 return QVariant( false );
7144}
7145
7146static QVariant fcnArrayDistinct( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7147{
7148 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7149
7150 QVariantList distinct;
7151
7152 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7153 {
7154 if ( !distinct.contains( *it ) )
7155 {
7156 distinct += ( *it );
7157 }
7158 }
7159
7160 return distinct;
7161}
7162
7163static QVariant fcnArrayToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7164{
7165 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7166 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7167 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7168
7169 QString str;
7170
7171 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7172 {
7173 str += ( !( *it ).toString().isEmpty() ) ? ( *it ).toString() : empty;
7174 if ( it != ( array.constEnd() - 1 ) )
7175 {
7176 str += delimiter;
7177 }
7178 }
7179
7180 return QVariant( str );
7181}
7182
7183static QVariant fcnStringToArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7184{
7185 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7186 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7187 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7188
7189 QStringList list = str.split( delimiter );
7190 QVariantList array;
7191
7192 for ( QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it )
7193 {
7194 array += ( !( *it ).isEmpty() ) ? *it : empty;
7195 }
7196
7197 return array;
7198}
7199
7200static QVariant fcnLoadJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7201{
7202 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7203 QJsonDocument document = QJsonDocument::fromJson( str.toUtf8() );
7204 if ( document.isNull() )
7205 return QVariant();
7206
7207 return document.toVariant();
7208}
7209
7210static QVariant fcnWriteJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7211{
7212 Q_UNUSED( parent )
7213 QJsonDocument document = QJsonDocument::fromVariant( values.at( 0 ) );
7214 return QString( document.toJson( QJsonDocument::Compact ) );
7215}
7216
7217static QVariant fcnHstoreToMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7218{
7219 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7220 if ( str.isEmpty() )
7221 return QVariantMap();
7222 str = str.trimmed();
7223
7224 return QgsHstoreUtils::parse( str );
7225}
7226
7227static QVariant fcnMapToHstore( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7228{
7229 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7230 return QgsHstoreUtils::build( map );
7231}
7232
7233static QVariant fcnMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7234{
7235 QVariantMap result;
7236 for ( int i = 0; i + 1 < values.length(); i += 2 )
7237 {
7238 result.insert( QgsExpressionUtils::getStringValue( values.at( i ), parent ), values.at( i + 1 ) );
7239 }
7240 return result;
7241}
7242
7243static QVariant fcnMapPrefixKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7244{
7245 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7246 const QString prefix = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7247 QVariantMap resultMap;
7248
7249 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7250 {
7251 resultMap.insert( QString( it.key() ).prepend( prefix ), it.value() );
7252 }
7253
7254 return resultMap;
7255}
7256
7257static QVariant fcnMapGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7258{
7259 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).value( values.at( 1 ).toString() );
7260}
7261
7262static QVariant fcnMapExist( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7263{
7264 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).contains( values.at( 1 ).toString() );
7265}
7266
7267static QVariant fcnMapDelete( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7268{
7269 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7270 map.remove( values.at( 1 ).toString() );
7271 return map;
7272}
7273
7274static QVariant fcnMapInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7275{
7276 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7277 map.insert( values.at( 1 ).toString(), values.at( 2 ) );
7278 return map;
7279}
7280
7281static QVariant fcnMapConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7282{
7283 QVariantMap result;
7284 for ( const QVariant &cur : values )
7285 {
7286 const QVariantMap curMap = QgsExpressionUtils::getMapValue( cur, parent );
7287 for ( QVariantMap::const_iterator it = curMap.constBegin(); it != curMap.constEnd(); ++it )
7288 result.insert( it.key(), it.value() );
7289 }
7290 return result;
7291}
7292
7293static QVariant fcnMapAKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7294{
7295 return QStringList( QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).keys() );
7296}
7297
7298static QVariant fcnMapAVals( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7299{
7300 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).values();
7301}
7302
7303static QVariant fcnEnvVar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7304{
7305 const QString envVarName = values.at( 0 ).toString();
7306 if ( !QProcessEnvironment::systemEnvironment().contains( envVarName ) )
7307 return QVariant();
7308
7309 return QProcessEnvironment::systemEnvironment().value( envVarName );
7310}
7311
7312static QVariant fcnBaseFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7313{
7314 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7315 if ( parent->hasEvalError() )
7316 {
7317 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "base_file_name" ) ) );
7318 return QVariant();
7319 }
7320 return QFileInfo( file ).completeBaseName();
7321}
7322
7323static QVariant fcnFileSuffix( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7324{
7325 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7326 if ( parent->hasEvalError() )
7327 {
7328 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_suffix" ) ) );
7329 return QVariant();
7330 }
7331 return QFileInfo( file ).completeSuffix();
7332}
7333
7334static QVariant fcnFileExists( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7335{
7336 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7337 if ( parent->hasEvalError() )
7338 {
7339 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_exists" ) ) );
7340 return QVariant();
7341 }
7342 return QFileInfo::exists( file );
7343}
7344
7345static QVariant fcnFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7346{
7347 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7348 if ( parent->hasEvalError() )
7349 {
7350 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_name" ) ) );
7351 return QVariant();
7352 }
7353 return QFileInfo( file ).fileName();
7354}
7355
7356static QVariant fcnPathIsFile( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7357{
7358 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7359 if ( parent->hasEvalError() )
7360 {
7361 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_file" ) ) );
7362 return QVariant();
7363 }
7364 return QFileInfo( file ).isFile();
7365}
7366
7367static QVariant fcnPathIsDir( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7368{
7369 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7370 if ( parent->hasEvalError() )
7371 {
7372 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_directory" ) ) );
7373 return QVariant();
7374 }
7375 return QFileInfo( file ).isDir();
7376}
7377
7378static QVariant fcnFilePath( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7379{
7380 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7381 if ( parent->hasEvalError() )
7382 {
7383 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_path" ) ) );
7384 return QVariant();
7385 }
7386 return QDir::toNativeSeparators( QFileInfo( file ).path() );
7387}
7388
7389static QVariant fcnFileSize( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7390{
7391 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7392 if ( parent->hasEvalError() )
7393 {
7394 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_size" ) ) );
7395 return QVariant();
7396 }
7397 return QFileInfo( file ).size();
7398}
7399
7400static QVariant fcnHash( const QString &str, const QCryptographicHash::Algorithm algorithm )
7401{
7402 return QString( QCryptographicHash::hash( str.toUtf8(), algorithm ).toHex() );
7403}
7404
7405static QVariant fcnGenericHash( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7406{
7407 QVariant hash;
7408 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7409 QString method = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).toLower();
7410
7411 if ( method == QLatin1String( "md4" ) )
7412 {
7413 hash = fcnHash( str, QCryptographicHash::Md4 );
7414 }
7415 else if ( method == QLatin1String( "md5" ) )
7416 {
7417 hash = fcnHash( str, QCryptographicHash::Md5 );
7418 }
7419 else if ( method == QLatin1String( "sha1" ) )
7420 {
7421 hash = fcnHash( str, QCryptographicHash::Sha1 );
7422 }
7423 else if ( method == QLatin1String( "sha224" ) )
7424 {
7425 hash = fcnHash( str, QCryptographicHash::Sha224 );
7426 }
7427 else if ( method == QLatin1String( "sha256" ) )
7428 {
7429 hash = fcnHash( str, QCryptographicHash::Sha256 );
7430 }
7431 else if ( method == QLatin1String( "sha384" ) )
7432 {
7433 hash = fcnHash( str, QCryptographicHash::Sha384 );
7434 }
7435 else if ( method == QLatin1String( "sha512" ) )
7436 {
7437 hash = fcnHash( str, QCryptographicHash::Sha512 );
7438 }
7439 else if ( method == QLatin1String( "sha3_224" ) )
7440 {
7441 hash = fcnHash( str, QCryptographicHash::Sha3_224 );
7442 }
7443 else if ( method == QLatin1String( "sha3_256" ) )
7444 {
7445 hash = fcnHash( str, QCryptographicHash::Sha3_256 );
7446 }
7447 else if ( method == QLatin1String( "sha3_384" ) )
7448 {
7449 hash = fcnHash( str, QCryptographicHash::Sha3_384 );
7450 }
7451 else if ( method == QLatin1String( "sha3_512" ) )
7452 {
7453 hash = fcnHash( str, QCryptographicHash::Sha3_512 );
7454 }
7455 else if ( method == QLatin1String( "keccak_224" ) )
7456 {
7457 hash = fcnHash( str, QCryptographicHash::Keccak_224 );
7458 }
7459 else if ( method == QLatin1String( "keccak_256" ) )
7460 {
7461 hash = fcnHash( str, QCryptographicHash::Keccak_256 );
7462 }
7463 else if ( method == QLatin1String( "keccak_384" ) )
7464 {
7465 hash = fcnHash( str, QCryptographicHash::Keccak_384 );
7466 }
7467 else if ( method == QLatin1String( "keccak_512" ) )
7468 {
7469 hash = fcnHash( str, QCryptographicHash::Keccak_512 );
7470 }
7471 else
7472 {
7473 parent->setEvalErrorString( QObject::tr( "Hash method %1 is not available on this system." ).arg( str ) );
7474 }
7475 return hash;
7476}
7477
7478static QVariant fcnHashMd5( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7479{
7480 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Md5 );
7481}
7482
7483static QVariant fcnHashSha256( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7484{
7485 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Sha256 );
7486}
7487
7488static QVariant fcnToBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7489{
7490 const QByteArray input = values.at( 0 ).toByteArray();
7491 return QVariant( QString( input.toBase64() ) );
7492}
7493
7494static QVariant fcnToFormUrlEncode( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7495{
7496 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7497 QUrlQuery query;
7498 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7499 {
7500 query.addQueryItem( it.key(), it.value().toString() );
7501 }
7502 return query.toString( QUrl::ComponentFormattingOption::FullyEncoded );
7503}
7504
7505static QVariant fcnFromBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7506{
7507 const QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7508 const QByteArray base64 = value.toLocal8Bit();
7509 const QByteArray decoded = QByteArray::fromBase64( base64 );
7510 return QVariant( decoded );
7511}
7512
7513typedef bool ( QgsGeometry::*RelationFunction )( const QgsGeometry &geometry ) const;
7514
7515static QVariant executeGeomOverlay( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const RelationFunction &relationFunction, bool invert = false, double bboxGrow = 0, bool isNearestFunc = false, bool isIntersectsFunc = false )
7516{
7517
7518 const QVariant sourceLayerRef = context->variable( QStringLiteral( "layer" ) ); //used to detect if sourceLayer and targetLayer are the same
7519 // TODO this function is NOT thread safe
7521 QgsVectorLayer *sourceLayer = QgsExpressionUtils::getVectorLayer( sourceLayerRef, context, parent );
7523
7524 QgsFeatureRequest request;
7525 request.setTimeout( 10000 );
7526 request.setRequestMayBeNested( true );
7527 request.setFeedback( context->feedback() );
7528
7529 // First parameter is the overlay layer
7530 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
7532
7533 const bool layerCanBeCached = node->isStatic( parent, context );
7534 QVariant targetLayerValue = node->eval( parent, context );
7536
7537 // Second parameter is the expression to evaluate (or null for testonly)
7538 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
7540 QString subExpString = node->dump();
7541
7542 bool testOnly = ( subExpString == "NULL" );
7543 // TODO this function is NOT thread safe
7545 QgsVectorLayer *targetLayer = QgsExpressionUtils::getVectorLayer( targetLayerValue, context, parent );
7547 if ( !targetLayer ) // No layer, no joy
7548 {
7549 parent->setEvalErrorString( QObject::tr( "Layer '%1' could not be loaded." ).arg( targetLayerValue.toString() ) );
7550 return QVariant();
7551 }
7552
7553 // Third parameter is the filtering expression
7554 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
7556 QString filterString = node->dump();
7557 if ( filterString != "NULL" )
7558 {
7559 request.setFilterExpression( filterString ); //filter cached features
7560 }
7561
7562 // Fourth parameter is the limit
7563 node = QgsExpressionUtils::getNode( values.at( 3 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7565 QVariant limitValue = node->eval( parent, context );
7567 qlonglong limit = QgsExpressionUtils::getIntValue( limitValue, parent );
7568
7569 // Fifth parameter (for nearest only) is the max distance
7570 double max_distance = 0;
7571 if ( isNearestFunc ) //maxdistance param handling
7572 {
7573 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
7575 QVariant distanceValue = node->eval( parent, context );
7577 max_distance = QgsExpressionUtils::getDoubleValue( distanceValue, parent );
7578 }
7579
7580 // Fifth or sixth (for nearest only) parameter is the cache toggle
7581 node = QgsExpressionUtils::getNode( values.at( isNearestFunc ? 5 : 4 ), parent );
7583 QVariant cacheValue = node->eval( parent, context );
7585 bool cacheEnabled = cacheValue.toBool();
7586
7587 // Sixth parameter (for intersects only) is the min overlap (area or length)
7588 // Seventh parameter (for intersects only) is the min inscribed circle radius
7589 // Eighth parameter (for intersects only) is the return_details
7590 // Ninth parameter (for intersects only) is the sort_by_intersection_size flag
7591 double minOverlap { -1 };
7592 double minInscribedCircleRadius { -1 };
7593 bool returnDetails = false; //#spellok
7594 bool sortByMeasure = false;
7595 bool sortAscending = false;
7596 bool requireMeasures = false;
7597 bool overlapOrRadiusFilter = false;
7598 if ( isIntersectsFunc )
7599 {
7600
7601 node = QgsExpressionUtils::getNode( values.at( 5 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7603 const QVariant minOverlapValue = node->eval( parent, context );
7605 minOverlap = QgsExpressionUtils::getDoubleValue( minOverlapValue, parent );
7606 node = QgsExpressionUtils::getNode( values.at( 6 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7608 const QVariant minInscribedCircleRadiusValue = node->eval( parent, context );
7610 minInscribedCircleRadius = QgsExpressionUtils::getDoubleValue( minInscribedCircleRadiusValue, parent );
7611 node = QgsExpressionUtils::getNode( values.at( 7 ), parent );
7612 // Return measures is only effective when an expression is set
7613 returnDetails = !testOnly && node->eval( parent, context ).toBool(); //#spellok
7614 node = QgsExpressionUtils::getNode( values.at( 8 ), parent );
7615 // Sort by measures is only effective when an expression is set
7616 const QString sorting { node->eval( parent, context ).toString().toLower() };
7617 sortByMeasure = !testOnly && ( sorting.startsWith( "asc" ) || sorting.startsWith( "des" ) );
7618 sortAscending = sorting.startsWith( "asc" );
7619 requireMeasures = sortByMeasure || returnDetails; //#spellok
7620 overlapOrRadiusFilter = minInscribedCircleRadius != -1 || minOverlap != -1;
7621 }
7622
7623
7624 FEAT_FROM_CONTEXT( context, feat )
7625 const QgsGeometry geometry = feat.geometry();
7626
7627 if ( sourceLayer && targetLayer->crs() != sourceLayer->crs() )
7628 {
7629 QgsCoordinateTransformContext TransformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
7630 request.setDestinationCrs( sourceLayer->crs(), TransformContext ); //if crs are not the same, cached target will be reprojected to source crs
7631 }
7632
7633 bool sameLayers = ( sourceLayer && sourceLayer->id() == targetLayer->id() );
7634
7635 QgsRectangle intDomain = geometry.boundingBox();
7636 if ( bboxGrow != 0 )
7637 {
7638 intDomain.grow( bboxGrow ); //optional parameter to enlarge boundary context for touches and equals methods
7639 }
7640
7641 const QString cacheBase { QStringLiteral( "%1:%2:%3" ).arg( targetLayer->id(), subExpString, filterString ) };
7642
7643 // Cache (a local spatial index) is always enabled for nearest function (as we need QgsSpatialIndex::nearestNeighbor)
7644 // Otherwise, it can be toggled by the user
7645 QgsSpatialIndex spatialIndex;
7646 QgsVectorLayer *cachedTarget;
7647 QList<QgsFeature> features;
7648 if ( isNearestFunc || ( layerCanBeCached && cacheEnabled ) )
7649 {
7650 // If the cache (local spatial index) is enabled, we materialize the whole
7651 // layer, then do the request on that layer instead.
7652 const QString cacheLayer { QStringLiteral( "ovrlaylyr:%1" ).arg( cacheBase ) };
7653 const QString cacheIndex { QStringLiteral( "ovrlayidx:%1" ).arg( cacheBase ) };
7654
7655 if ( !context->hasCachedValue( cacheLayer ) ) // should check for same crs. if not the same we could think to reproject target layer before charging cache
7656 {
7657 cachedTarget = targetLayer->materialize( request );
7658 if ( layerCanBeCached )
7659 context->setCachedValue( cacheLayer, QVariant::fromValue( cachedTarget ) );
7660 }
7661 else
7662 {
7663 cachedTarget = context->cachedValue( cacheLayer ).value<QgsVectorLayer *>();
7664 }
7665
7666 if ( !context->hasCachedValue( cacheIndex ) )
7667 {
7668 spatialIndex = QgsSpatialIndex( cachedTarget->getFeatures(), nullptr, QgsSpatialIndex::FlagStoreFeatureGeometries );
7669 if ( layerCanBeCached )
7670 context->setCachedValue( cacheIndex, QVariant::fromValue( spatialIndex ) );
7671 }
7672 else
7673 {
7674 spatialIndex = context->cachedValue( cacheIndex ).value<QgsSpatialIndex>();
7675 }
7676
7677 QList<QgsFeatureId> fidsList;
7678 if ( isNearestFunc )
7679 {
7680 fidsList = spatialIndex.nearestNeighbor( geometry, sameLayers ? limit + 1 : limit, max_distance );
7681 }
7682 else
7683 {
7684 fidsList = spatialIndex.intersects( intDomain );
7685 }
7686
7687 QListIterator<QgsFeatureId> i( fidsList );
7688 while ( i.hasNext() )
7689 {
7690 QgsFeatureId fId2 = i.next();
7691 if ( sameLayers && feat.id() == fId2 )
7692 continue;
7693 features.append( cachedTarget->getFeature( fId2 ) );
7694 }
7695
7696 }
7697 else
7698 {
7699 // If the cache (local spatial index) is not enabled, we directly
7700 // get the features from the target layer
7701 request.setFilterRect( intDomain );
7702 QgsFeatureIterator fit = targetLayer->getFeatures( request );
7703 QgsFeature feat2;
7704 while ( fit.nextFeature( feat2 ) )
7705 {
7706 if ( sameLayers && feat.id() == feat2.id() )
7707 continue;
7708 features.append( feat2 );
7709 }
7710 }
7711
7712 QgsExpression subExpression;
7713 QgsExpressionContext subContext;
7714 if ( !testOnly )
7715 {
7716 const QString expCacheKey { QStringLiteral( "exp:%1" ).arg( cacheBase ) };
7717 const QString ctxCacheKey { QStringLiteral( "ctx:%1" ).arg( cacheBase ) };
7718
7719 if ( !context->hasCachedValue( expCacheKey ) || !context->hasCachedValue( ctxCacheKey ) )
7720 {
7721 subExpression = QgsExpression( subExpString );
7723 subExpression.prepare( &subContext );
7724 }
7725 else
7726 {
7727 subExpression = context->cachedValue( expCacheKey ).value<QgsExpression>();
7728 subContext = context->cachedValue( ctxCacheKey ).value<QgsExpressionContext>();
7729 }
7730 }
7731
7732 // //////////////////////////////////////////////////////////////////
7733 // Helper functions for geometry tests
7734
7735 // Test function for linestring geometries, returns TRUE if test passes
7736 auto testLinestring = [ = ]( const QgsGeometry intersection, double & overlapValue ) -> bool
7737 {
7738 bool testResult { false };
7739 // For return measures:
7740 QVector<double> overlapValues;
7741 for ( auto it = intersection.const_parts_begin(); ! testResult && it != intersection.const_parts_end(); ++it )
7742 {
7743 const QgsCurve *geom = qgsgeometry_cast< const QgsCurve * >( *it );
7744 // Check min overlap for intersection (if set)
7745 if ( minOverlap != -1 || requireMeasures )
7746 {
7747 overlapValue = geom->length();
7748 overlapValues.append( overlapValue );
7749 if ( minOverlap != -1 )
7750 {
7751 if ( overlapValue >= minOverlap )
7752 {
7753 testResult = true;
7754 }
7755 else
7756 {
7757 continue;
7758 }
7759 }
7760 }
7761 }
7762
7763 if ( ! overlapValues.isEmpty() )
7764 {
7765 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
7766 }
7767
7768 return testResult;
7769 };
7770
7771 // Test function for polygon geometries, returns TRUE if test passes
7772 auto testPolygon = [ = ]( const QgsGeometry intersection, double & radiusValue, double & overlapValue ) -> bool
7773 {
7774 // overlap and inscribed circle tests must be checked both (if the values are != -1)
7775 bool testResult { false };
7776 // For return measures:
7777 QVector<double> overlapValues;
7778 QVector<double> radiusValues;
7779 for ( auto it = intersection.const_parts_begin(); ( ! testResult || requireMeasures ) && it != intersection.const_parts_end(); ++it )
7780 {
7781 const QgsCurvePolygon *geom = qgsgeometry_cast< const QgsCurvePolygon * >( *it );
7782 // Check min overlap for intersection (if set)
7783 if ( minOverlap != -1 || requireMeasures )
7784 {
7785 overlapValue = geom->area();
7786 overlapValues.append( geom->area() );
7787 if ( minOverlap != - 1 )
7788 {
7789 if ( overlapValue >= minOverlap )
7790 {
7791 testResult = true;
7792 }
7793 else
7794 {
7795 continue;
7796 }
7797 }
7798 }
7799
7800 // Check min inscribed circle radius for intersection (if set)
7801 if ( minInscribedCircleRadius != -1 || requireMeasures )
7802 {
7803 const QgsRectangle bbox = geom->boundingBox();
7804 const double width = bbox.width();
7805 const double height = bbox.height();
7806 const double size = width > height ? width : height;
7807 const double tolerance = size / 100.0;
7808 radiusValue = QgsGeos( geom ).maximumInscribedCircle( tolerance )->length();
7809 testResult = radiusValue >= minInscribedCircleRadius;
7810 radiusValues.append( radiusValues );
7811 }
7812 } // end for parts
7813
7814 // Get the max values
7815 if ( !radiusValues.isEmpty() )
7816 {
7817 radiusValue = *std::max_element( radiusValues.cbegin(), radiusValues.cend() );
7818 }
7819
7820 if ( ! overlapValues.isEmpty() )
7821 {
7822 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
7823 }
7824
7825 return testResult;
7826
7827 };
7828
7829
7830 bool found = false;
7831 int foundCount = 0;
7832 QVariantList results;
7833
7834 QListIterator<QgsFeature> i( features );
7835 while ( i.hasNext() && ( sortByMeasure || limit == -1 || foundCount < limit ) )
7836 {
7837
7838 QgsFeature feat2 = i.next();
7839
7840
7841 if ( ! relationFunction || ( geometry.*relationFunction )( feat2.geometry() ) ) // Calls the method provided as template argument for the function (e.g. QgsGeometry::intersects)
7842 {
7843
7844 double overlapValue = -1;
7845 double radiusValue = -1;
7846
7847 if ( isIntersectsFunc && ( requireMeasures || overlapOrRadiusFilter ) )
7848 {
7849 const QgsGeometry intersection { geometry.intersection( feat2.geometry() ) };
7850
7851 // Depending on the intersection geometry type and on the geometry type of
7852 // the tested geometry we can run different tests and collect different measures
7853 // that can be used for sorting (if required).
7854 switch ( intersection.type() )
7855 {
7856
7858 {
7859
7860 // Overlap and inscribed circle tests must be checked both (if the values are != -1)
7861 bool testResult { testPolygon( intersection, radiusValue, overlapValue ) };
7862
7863 if ( ! testResult && overlapOrRadiusFilter )
7864 {
7865 continue;
7866 }
7867
7868 break;
7869 }
7870
7872 {
7873
7874 // If the intersection is a linestring and a minimum circle is required
7875 // we can discard this result immediately.
7876 if ( minInscribedCircleRadius != -1 )
7877 {
7878 continue;
7879 }
7880
7881 // Otherwise a test for the overlap value is performed.
7882 const bool testResult { testLinestring( intersection, overlapValue ) };
7883
7884 if ( ! testResult && overlapOrRadiusFilter )
7885 {
7886 continue;
7887 }
7888
7889 break;
7890 }
7891
7893 {
7894
7895 // If the intersection is a point and a minimum circle is required
7896 // we can discard this result immediately.
7897 if ( minInscribedCircleRadius != -1 )
7898 {
7899 continue;
7900 }
7901
7902 bool testResult { false };
7903 if ( minOverlap != -1 || requireMeasures )
7904 {
7905 // Initially set this to 0 because it's a point intersection...
7906 overlapValue = 0;
7907 // ... but if the target geometry is not a point and the source
7908 // geometry is a point, we must record the length or the area
7909 // of the intersected geometry and use that as a measure for
7910 // sorting or reporting.
7911 if ( geometry.type() == Qgis::GeometryType::Point )
7912 {
7913 switch ( feat2.geometry().type() )
7914 {
7918 {
7919 break;
7920 }
7922 {
7923 testResult = testLinestring( feat2.geometry(), overlapValue );
7924 break;
7925 }
7927 {
7928 testResult = testPolygon( feat2.geometry(), radiusValue, overlapValue );
7929 break;
7930 }
7931 }
7932 }
7933
7934 if ( ! testResult && overlapOrRadiusFilter )
7935 {
7936 continue;
7937 }
7938
7939 }
7940 break;
7941 }
7942
7945 {
7946 continue;
7947 }
7948 }
7949 }
7950
7951 found = true;
7952 foundCount++;
7953
7954 // We just want a single boolean result if there is any intersect: finish and return true
7955 if ( testOnly )
7956 break;
7957
7958 if ( !invert )
7959 {
7960 // We want a list of attributes / geometries / other expression values, evaluate now
7961 subContext.setFeature( feat2 );
7962 const QVariant expResult = subExpression.evaluate( &subContext );
7963
7964 if ( requireMeasures )
7965 {
7966 QVariantMap resultRecord;
7967 resultRecord.insert( QStringLiteral( "id" ), feat2.id() );
7968 resultRecord.insert( QStringLiteral( "result" ), expResult );
7969 // Overlap is always added because return measures was set
7970 resultRecord.insert( QStringLiteral( "overlap" ), overlapValue );
7971 // Radius is only added when is different than -1 (because for linestrings is not set)
7972 if ( radiusValue != -1 )
7973 {
7974 resultRecord.insert( QStringLiteral( "radius" ), radiusValue );
7975 }
7976 results.append( resultRecord );
7977 }
7978 else
7979 {
7980 results.append( expResult );
7981 }
7982 }
7983 else
7984 {
7985 // If not, results is a list of found ids, which we'll inverse and evaluate below
7986 results.append( feat2.id() );
7987 }
7988 }
7989 }
7990
7991 if ( testOnly )
7992 {
7993 if ( invert )
7994 found = !found;//for disjoint condition
7995 return found;
7996 }
7997
7998 if ( !invert )
7999 {
8000 if ( requireMeasures )
8001 {
8002 if ( sortByMeasure )
8003 {
8004 std::sort( results.begin(), results.end(), [ sortAscending ]( const QVariant & recordA, const QVariant & recordB ) -> bool
8005 {
8006 return sortAscending ?
8007 recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble()
8008 : recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble();
8009 } );
8010 }
8011 // Resize
8012 if ( limit > 0 && results.size() > limit )
8013 {
8014 results.erase( results.begin() + limit );
8015 }
8016
8017 if ( ! returnDetails ) //#spellok
8018 {
8019 QVariantList expResults;
8020 for ( auto it = results.constBegin(); it != results.constEnd(); ++it )
8021 {
8022 expResults.append( it->toMap().value( QStringLiteral( "result" ) ) );
8023 }
8024 return expResults;
8025 }
8026 }
8027
8028 return results;
8029 }
8030
8031 // for disjoint condition returns the results for cached layers not intersected feats
8032 QVariantList disjoint_results;
8033 QgsFeature feat2;
8034 QgsFeatureRequest request2;
8035 request2.setLimit( limit );
8036 if ( context )
8037 request2.setFeedback( context->feedback() );
8038 QgsFeatureIterator fi = targetLayer->getFeatures( request2 );
8039 while ( fi.nextFeature( feat2 ) )
8040 {
8041 if ( !results.contains( feat2.id() ) )
8042 {
8043 subContext.setFeature( feat2 );
8044 disjoint_results.append( subExpression.evaluate( &subContext ) );
8045 }
8046 }
8047 return disjoint_results;
8048
8049}
8050
8051// Intersect functions:
8052
8053static QVariant fcnGeomOverlayIntersects( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8054{
8055 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, false, 0, false, true );
8056}
8057
8058static QVariant fcnGeomOverlayContains( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8059{
8060 return executeGeomOverlay( values, context, parent, &QgsGeometry::contains );
8061}
8062
8063static QVariant fcnGeomOverlayCrosses( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8064{
8065 return executeGeomOverlay( values, context, parent, &QgsGeometry::crosses );
8066}
8067
8068static QVariant fcnGeomOverlayEquals( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8069{
8070 return executeGeomOverlay( values, context, parent, &QgsGeometry::equals, false, 0.01 ); //grow amount should adapt to current units
8071}
8072
8073static QVariant fcnGeomOverlayTouches( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8074{
8075 return executeGeomOverlay( values, context, parent, &QgsGeometry::touches, false, 0.01 ); //grow amount should adapt to current units
8076}
8077
8078static QVariant fcnGeomOverlayWithin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8079{
8080 return executeGeomOverlay( values, context, parent, &QgsGeometry::within );
8081}
8083static QVariant fcnGeomOverlayDisjoint( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8084{
8085 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, true, 0, false, true );
8086}
8087
8088static QVariant fcnGeomOverlayNearest( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8089{
8090 return executeGeomOverlay( values, context, parent, nullptr, false, 0, true );
8091}
8092
8093const QList<QgsExpressionFunction *> &QgsExpression::Functions()
8094{
8095 // The construction of the list isn't thread-safe, and without the mutex,
8096 // crashes in the WFS provider may occur, since it can parse expressions
8097 // in parallel.
8098 // The mutex needs to be recursive.
8099 QMutexLocker locker( &sFunctionsMutex );
8100
8101 QList<QgsExpressionFunction *> &functions = *sFunctions();
8102
8103 if ( functions.isEmpty() )
8104 {
8106 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
8107 << QgsExpressionFunction::Parameter( QStringLiteral( "group_by" ), true )
8108 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true );
8109
8110 QgsExpressionFunction::ParameterList aggParamsConcat = aggParams;
8111 aggParamsConcat << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8112 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8113
8114 QgsExpressionFunction::ParameterList aggParamsArray = aggParams;
8115 aggParamsArray << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8116
8117 functions
8118 << new QgsStaticExpressionFunction( QStringLiteral( "sqrt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnSqrt, QStringLiteral( "Math" ) )
8119 << new QgsStaticExpressionFunction( QStringLiteral( "radians" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "degrees" ) ), fcnRadians, QStringLiteral( "Math" ) )
8120 << new QgsStaticExpressionFunction( QStringLiteral( "degrees" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "radians" ) ), fcnDegrees, QStringLiteral( "Math" ) )
8121 << new QgsStaticExpressionFunction( QStringLiteral( "azimuth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnAzimuth, QStringLiteral( "GeometryGroup" ) )
8122 << new QgsStaticExpressionFunction( QStringLiteral( "bearing" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "source_crs" ), true, QVariant() ) << QgsExpressionFunction::Parameter( QStringLiteral( "ellipsoid" ), true, QVariant() ), fcnBearing, QStringLiteral( "GeometryGroup" ) )
8123 << new QgsStaticExpressionFunction( QStringLiteral( "inclination" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnInclination, QStringLiteral( "GeometryGroup" ) )
8124 << new QgsStaticExpressionFunction( QStringLiteral( "project" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "elevation" ), true, M_PI_2 ), fcnProject, QStringLiteral( "GeometryGroup" ) )
8125 << new QgsStaticExpressionFunction( QStringLiteral( "abs" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAbs, QStringLiteral( "Math" ) )
8126 << new QgsStaticExpressionFunction( QStringLiteral( "cos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnCos, QStringLiteral( "Math" ) )
8127 << new QgsStaticExpressionFunction( QStringLiteral( "sin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnSin, QStringLiteral( "Math" ) )
8128 << new QgsStaticExpressionFunction( QStringLiteral( "tan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnTan, QStringLiteral( "Math" ) )
8129 << new QgsStaticExpressionFunction( QStringLiteral( "asin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAsin, QStringLiteral( "Math" ) )
8130 << new QgsStaticExpressionFunction( QStringLiteral( "acos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAcos, QStringLiteral( "Math" ) )
8131 << new QgsStaticExpressionFunction( QStringLiteral( "atan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAtan, QStringLiteral( "Math" ) )
8132 << new QgsStaticExpressionFunction( QStringLiteral( "atan2" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ), fcnAtan2, QStringLiteral( "Math" ) )
8133 << new QgsStaticExpressionFunction( QStringLiteral( "exp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnExp, QStringLiteral( "Math" ) )
8134 << new QgsStaticExpressionFunction( QStringLiteral( "ln" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLn, QStringLiteral( "Math" ) )
8135 << new QgsStaticExpressionFunction( QStringLiteral( "log10" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog10, QStringLiteral( "Math" ) )
8136 << new QgsStaticExpressionFunction( QStringLiteral( "log" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "base" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog, QStringLiteral( "Math" ) )
8137 << new QgsStaticExpressionFunction( QStringLiteral( "round" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 ), fcnRound, QStringLiteral( "Math" ) );
8138
8139 QgsStaticExpressionFunction *randFunc = new QgsStaticExpressionFunction( QStringLiteral( "rand" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true ), fcnRnd, QStringLiteral( "Math" ) );
8140 randFunc->setIsStatic( false );
8141 functions << randFunc;
8142
8143 QgsStaticExpressionFunction *randfFunc = new QgsStaticExpressionFunction( QStringLiteral( "randf" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ), true, 0.0 ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ), true, 1.0 ) << QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true ), fcnRndF, QStringLiteral( "Math" ) );
8144 randfFunc->setIsStatic( false );
8145 functions << randfFunc;
8146
8147 functions
8148 << new QgsStaticExpressionFunction( QStringLiteral( "max" ), -1, fcnMax, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8149 << new QgsStaticExpressionFunction( QStringLiteral( "min" ), -1, fcnMin, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8150 << new QgsStaticExpressionFunction( QStringLiteral( "clamp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ), fcnClamp, QStringLiteral( "Math" ) )
8151 << new QgsStaticExpressionFunction( QStringLiteral( "scale_linear" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_max" ) ), fcnLinearScale, QStringLiteral( "Math" ) )
8152 << new QgsStaticExpressionFunction( QStringLiteral( "scale_polynomial" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "exponent" ) ), fcnPolynomialScale, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "scale_exp" ) )
8153 << new QgsStaticExpressionFunction( QStringLiteral( "scale_exponential" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "domain_max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "range_max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "exponent" ) ), fcnExponentialScale, QStringLiteral( "Math" ) )
8154 << new QgsStaticExpressionFunction( QStringLiteral( "floor" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnFloor, QStringLiteral( "Math" ) )
8155 << new QgsStaticExpressionFunction( QStringLiteral( "ceil" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnCeil, QStringLiteral( "Math" ) )
8156 << new QgsStaticExpressionFunction( QStringLiteral( "pi" ), 0, fcnPi, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$pi" ) )
8157 << new QgsStaticExpressionFunction( QStringLiteral( "to_int" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToInt, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toint" ) )
8158 << new QgsStaticExpressionFunction( QStringLiteral( "to_real" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToReal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toreal" ) )
8159 << new QgsStaticExpressionFunction( QStringLiteral( "to_string" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToString, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "String" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "tostring" ) )
8160 << new QgsStaticExpressionFunction( QStringLiteral( "to_datetime" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "format" ), true, QVariant() ) << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() ), fcnToDateTime, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todatetime" ) )
8161 << new QgsStaticExpressionFunction( QStringLiteral( "to_date" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "format" ), true, QVariant() ) << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() ), fcnToDate, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todate" ) )
8162 << new QgsStaticExpressionFunction( QStringLiteral( "to_time" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "format" ), true, QVariant() ) << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() ), fcnToTime, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "totime" ) )
8163 << new QgsStaticExpressionFunction( QStringLiteral( "to_interval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToInterval, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "tointerval" ) )
8164 << new QgsStaticExpressionFunction( QStringLiteral( "to_dm" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "axis" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "precision" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "formatting" ), true ), fcnToDegreeMinute, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todm" ) )
8165 << new QgsStaticExpressionFunction( QStringLiteral( "to_dms" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "axis" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "precision" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "formatting" ), true ), fcnToDegreeMinuteSecond, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todms" ) )
8166 << new QgsStaticExpressionFunction( QStringLiteral( "to_decimal" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToDecimal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todecimal" ) )
8167 << new QgsStaticExpressionFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8168 << new QgsStaticExpressionFunction( QStringLiteral( "nullif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value2" ) ), fcnNullIf, QStringLiteral( "Conditionals" ) )
8169 << new QgsStaticExpressionFunction( QStringLiteral( "if" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "condition" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "result_when_true" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "result_when_false" ) ), fcnIf, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), true )
8170 << new QgsStaticExpressionFunction( QStringLiteral( "try" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "alternative" ), true, QVariant() ), fcnTry, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), true )
8171
8172 << new QgsStaticExpressionFunction( QStringLiteral( "aggregate" ),
8174 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8175 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8176 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8177 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8178 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8179 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8180 fcnAggregate,
8181 QStringLiteral( "Aggregates" ),
8182 QString(),
8183 []( const QgsExpressionNodeFunction * node )
8184 {
8185 // usesGeometry callback: return true if @parent variable is referenced
8186
8187 if ( !node )
8188 return true;
8189
8190 if ( !node->args() )
8191 return false;
8192
8193 QSet<QString> referencedVars;
8194 if ( node->args()->count() > 2 )
8195 {
8196 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8197 referencedVars = subExpressionNode->referencedVariables();
8198 }
8199
8200 if ( node->args()->count() > 3 )
8201 {
8202 QgsExpressionNode *filterNode = node->args()->at( 3 );
8203 referencedVars.unite( filterNode->referencedVariables() );
8204 }
8205 return referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() );
8206 },
8207 []( const QgsExpressionNodeFunction * node )
8208 {
8209 // referencedColumns callback: return AllAttributes if @parent variable is referenced
8210
8211 if ( !node )
8212 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8213
8214 if ( !node->args() )
8215 return QSet<QString>();
8216
8217 QSet<QString> referencedCols;
8218 QSet<QString> referencedVars;
8219
8220 if ( node->args()->count() > 2 )
8221 {
8222 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8223 referencedVars = subExpressionNode->referencedVariables();
8224 referencedCols = subExpressionNode->referencedColumns();
8225 }
8226 if ( node->args()->count() > 3 )
8227 {
8228 QgsExpressionNode *filterNode = node->args()->at( 3 );
8229 referencedVars = filterNode->referencedVariables();
8230 referencedCols.unite( filterNode->referencedColumns() );
8231 }
8232
8233 if ( referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() ) )
8234 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8235 else
8236 return referencedCols;
8237 },
8238 true
8239 )
8240
8241 << new QgsStaticExpressionFunction( QStringLiteral( "relation_aggregate" ), QgsExpressionFunction::ParameterList()
8242 << QgsExpressionFunction::Parameter( QStringLiteral( "relation" ) )
8243 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8244 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8245 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8246 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8247 fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true )
8248
8249 << new QgsStaticExpressionFunction( QStringLiteral( "count" ), aggParams, fcnAggregateCount, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8250 << new QgsStaticExpressionFunction( QStringLiteral( "count_distinct" ), aggParams, fcnAggregateCountDistinct, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8251 << new QgsStaticExpressionFunction( QStringLiteral( "count_missing" ), aggParams, fcnAggregateCountMissing, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8252 << new QgsStaticExpressionFunction( QStringLiteral( "minimum" ), aggParams, fcnAggregateMin, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8253 << new QgsStaticExpressionFunction( QStringLiteral( "maximum" ), aggParams, fcnAggregateMax, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8254 << new QgsStaticExpressionFunction( QStringLiteral( "sum" ), aggParams, fcnAggregateSum, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8255 << new QgsStaticExpressionFunction( QStringLiteral( "mean" ), aggParams, fcnAggregateMean, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8256 << new QgsStaticExpressionFunction( QStringLiteral( "median" ), aggParams, fcnAggregateMedian, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8257 << new QgsStaticExpressionFunction( QStringLiteral( "stdev" ), aggParams, fcnAggregateStdev, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8258 << new QgsStaticExpressionFunction( QStringLiteral( "range" ), aggParams, fcnAggregateRange, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8259 << new QgsStaticExpressionFunction( QStringLiteral( "minority" ), aggParams, fcnAggregateMinority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8260 << new QgsStaticExpressionFunction( QStringLiteral( "majority" ), aggParams, fcnAggregateMajority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8261 << new QgsStaticExpressionFunction( QStringLiteral( "q1" ), aggParams, fcnAggregateQ1, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8262 << new QgsStaticExpressionFunction( QStringLiteral( "q3" ), aggParams, fcnAggregateQ3, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8263 << new QgsStaticExpressionFunction( QStringLiteral( "iqr" ), aggParams, fcnAggregateIQR, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8264 << new QgsStaticExpressionFunction( QStringLiteral( "min_length" ), aggParams, fcnAggregateMinLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8265 << new QgsStaticExpressionFunction( QStringLiteral( "max_length" ), aggParams, fcnAggregateMaxLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8266 << new QgsStaticExpressionFunction( QStringLiteral( "collect" ), aggParams, fcnAggregateCollectGeometry, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8267 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate" ), aggParamsConcat, fcnAggregateStringConcat, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8268 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate_unique" ), aggParamsConcat, fcnAggregateStringConcatUnique, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8269 << new QgsStaticExpressionFunction( QStringLiteral( "array_agg" ), aggParamsArray, fcnAggregateArray, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8270
8271 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_match" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpMatch, QStringList() << QStringLiteral( "Conditionals" ) << QStringLiteral( "String" ) )
8272 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_matches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnRegexpMatches, QStringLiteral( "Arrays" ) )
8273
8274 << new QgsStaticExpressionFunction( QStringLiteral( "now" ), 0, fcnNow, QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$now" ) )
8275 << new QgsStaticExpressionFunction( QStringLiteral( "age" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime1" ) )
8276 << QgsExpressionFunction::Parameter( QStringLiteral( "datetime2" ) ),
8277 fcnAge, QStringLiteral( "Date and Time" ) )
8278 << new QgsStaticExpressionFunction( QStringLiteral( "year" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnYear, QStringLiteral( "Date and Time" ) )
8279 << new QgsStaticExpressionFunction( QStringLiteral( "month" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnMonth, QStringLiteral( "Date and Time" ) )
8280 << new QgsStaticExpressionFunction( QStringLiteral( "week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnWeek, QStringLiteral( "Date and Time" ) )
8281 << new QgsStaticExpressionFunction( QStringLiteral( "day" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDay, QStringLiteral( "Date and Time" ) )
8282 << new QgsStaticExpressionFunction( QStringLiteral( "hour" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnHour, QStringLiteral( "Date and Time" ) )
8283 << new QgsStaticExpressionFunction( QStringLiteral( "minute" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnMinute, QStringLiteral( "Date and Time" ) )
8284 << new QgsStaticExpressionFunction( QStringLiteral( "second" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnSeconds, QStringLiteral( "Date and Time" ) )
8285 << new QgsStaticExpressionFunction( QStringLiteral( "epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnEpoch, QStringLiteral( "Date and Time" ) )
8286 << new QgsStaticExpressionFunction( QStringLiteral( "datetime_from_epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "long" ) ), fcnDateTimeFromEpoch, QStringLiteral( "Date and Time" ) )
8287 << new QgsStaticExpressionFunction( QStringLiteral( "day_of_week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDayOfWeek, QStringLiteral( "Date and Time" ) )
8288 << new QgsStaticExpressionFunction( QStringLiteral( "make_date" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8289 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8290 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) ),
8291 fcnMakeDate, QStringLiteral( "Date and Time" ) )
8292 << new QgsStaticExpressionFunction( QStringLiteral( "make_time" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8293 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8294 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8295 fcnMakeTime, QStringLiteral( "Date and Time" ) )
8296 << new QgsStaticExpressionFunction( QStringLiteral( "make_datetime" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8297 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8298 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) )
8299 << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8300 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8301 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8302 fcnMakeDateTime, QStringLiteral( "Date and Time" ) )
8303 << new QgsStaticExpressionFunction( QStringLiteral( "make_interval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "years" ), true, 0 )
8304 << QgsExpressionFunction::Parameter( QStringLiteral( "months" ), true, 0 )
8305 << QgsExpressionFunction::Parameter( QStringLiteral( "weeks" ), true, 0 )
8306 << QgsExpressionFunction::Parameter( QStringLiteral( "days" ), true, 0 )
8307 << QgsExpressionFunction::Parameter( QStringLiteral( "hours" ), true, 0 )
8308 << QgsExpressionFunction::Parameter( QStringLiteral( "minutes" ), true, 0 )
8309 << QgsExpressionFunction::Parameter( QStringLiteral( "seconds" ), true, 0 ),
8310 fcnMakeInterval, QStringLiteral( "Date and Time" ) )
8311 << new QgsStaticExpressionFunction( QStringLiteral( "lower" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnLower, QStringLiteral( "String" ) )
8312 << new QgsStaticExpressionFunction( QStringLiteral( "upper" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnUpper, QStringLiteral( "String" ) )
8313 << new QgsStaticExpressionFunction( QStringLiteral( "title" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTitle, QStringLiteral( "String" ) )
8314 << new QgsStaticExpressionFunction( QStringLiteral( "trim" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTrim, QStringLiteral( "String" ) )
8315 << new QgsStaticExpressionFunction( QStringLiteral( "ltrim" ), QgsExpressionFunction::ParameterList()
8316 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8317 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnLTrim, QStringLiteral( "String" ) )
8318 << new QgsStaticExpressionFunction( QStringLiteral( "rtrim" ), QgsExpressionFunction::ParameterList()
8319 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8320 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnRTrim, QStringLiteral( "String" ) )
8321 << new QgsStaticExpressionFunction( QStringLiteral( "levenshtein" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLevenshtein, QStringLiteral( "Fuzzy Matching" ) )
8322 << new QgsStaticExpressionFunction( QStringLiteral( "longest_common_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLCS, QStringLiteral( "Fuzzy Matching" ) )
8323 << new QgsStaticExpressionFunction( QStringLiteral( "hamming_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnHamming, QStringLiteral( "Fuzzy Matching" ) )
8324 << new QgsStaticExpressionFunction( QStringLiteral( "soundex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnSoundex, QStringLiteral( "Fuzzy Matching" ) )
8325 << new QgsStaticExpressionFunction( QStringLiteral( "char" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "code" ) ), fcnChar, QStringLiteral( "String" ) )
8326 << new QgsStaticExpressionFunction( QStringLiteral( "ascii" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnAscii, QStringLiteral( "String" ) )
8327 << new QgsStaticExpressionFunction( QStringLiteral( "wordwrap" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "delimiter" ), true, "" ), fcnWordwrap, QStringLiteral( "String" ) )
8328 << new QgsStaticExpressionFunction( QStringLiteral( "length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ), true, "" ), fcnLength, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "GeometryGroup" ) )
8329 << new QgsStaticExpressionFunction( QStringLiteral( "length3D" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLength3D, QStringLiteral( "GeometryGroup" ) )
8330 << new QgsStaticExpressionFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) )
8331 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_replace" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) )
8332 << QgsExpressionFunction::Parameter( QStringLiteral( "replacement" ) ), fcnRegexpReplace, QStringLiteral( "String" ) )
8333 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpSubstr, QStringLiteral( "String" ) )
8334 << new QgsStaticExpressionFunction( QStringLiteral( "substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(),
8335 false, QSet< QString >(), false, QStringList(), true )
8336 << new QgsStaticExpressionFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8337 << new QgsStaticExpressionFunction( QStringLiteral( "strpos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "haystack" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "needle" ) ), fcnStrpos, QStringLiteral( "String" ) )
8338 << new QgsStaticExpressionFunction( QStringLiteral( "left" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnLeft, QStringLiteral( "String" ) )
8339 << new QgsStaticExpressionFunction( QStringLiteral( "right" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnRight, QStringLiteral( "String" ) )
8340 << new QgsStaticExpressionFunction( QStringLiteral( "rpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnRPad, QStringLiteral( "String" ) )
8341 << new QgsStaticExpressionFunction( QStringLiteral( "lpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnLPad, QStringLiteral( "String" ) )
8342 << new QgsStaticExpressionFunction( QStringLiteral( "format" ), -1, fcnFormatString, QStringLiteral( "String" ) )
8343 << new QgsStaticExpressionFunction( QStringLiteral( "format_number" ), QgsExpressionFunction::ParameterList()
8344 << QgsExpressionFunction::Parameter( QStringLiteral( "number" ) )
8345 << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 )
8346 << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() )
8347 << QgsExpressionFunction::Parameter( QStringLiteral( "omit_group_separators" ), true, false )
8348 << QgsExpressionFunction::Parameter( QStringLiteral( "trim_trailing_zeroes" ), true, false ), fcnFormatNumber, QStringLiteral( "String" ) )
8349 << new QgsStaticExpressionFunction( QStringLiteral( "format_date" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "format" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() ), fcnFormatDate, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "Date and Time" ) )
8350 << new QgsStaticExpressionFunction( QStringLiteral( "color_grayscale_average" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ), fcnColorGrayscaleAverage, QStringLiteral( "Color" ) )
8351 << new QgsStaticExpressionFunction( QStringLiteral( "color_mix_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color1" ) )
8352 << QgsExpressionFunction::Parameter( QStringLiteral( "color2" ) )
8353 << QgsExpressionFunction::Parameter( QStringLiteral( "ratio" ) ),
8354 fcnColorMixRgb, QStringLiteral( "Color" ) )
8355 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8356 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8357 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) ),
8358 fcnColorRgb, QStringLiteral( "Color" ) )
8359 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgba" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8360 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8361 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) )
8362 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8363 fncColorRgba, QStringLiteral( "Color" ) )
8364 << new QgsStaticExpressionFunction( QStringLiteral( "ramp_color" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "ramp_name" ) )
8365 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8366 fcnRampColor, QStringLiteral( "Color" ) )
8367 << new QgsStaticExpressionFunction( QStringLiteral( "create_ramp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
8368 << QgsExpressionFunction::Parameter( QStringLiteral( "discrete" ), true, false ),
8369 fcnCreateRamp, QStringLiteral( "Color" ) )
8370 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8371 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8372 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) ),
8373 fcnColorHsl, QStringLiteral( "Color" ) )
8374 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsla" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8375 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8376 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) )
8377 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8378 fncColorHsla, QStringLiteral( "Color" ) )
8379 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsv" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8380 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8381 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8382 fcnColorHsv, QStringLiteral( "Color" ) )
8383 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsva" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8384 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8385 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
8386 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8387 fncColorHsva, QStringLiteral( "Color" ) )
8388 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyk" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8389 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8390 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8391 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) ),
8392 fcnColorCmyk, QStringLiteral( "Color" ) )
8393 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyka" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8394 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8395 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8396 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) )
8397 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8398 fncColorCmyka, QStringLiteral( "Color" ) )
8399 << new QgsStaticExpressionFunction( QStringLiteral( "color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8400 << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ),
8401 fncColorPart, QStringLiteral( "Color" ) )
8402 << new QgsStaticExpressionFunction( QStringLiteral( "darker" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8403 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8404 fncDarker, QStringLiteral( "Color" ) )
8405 << new QgsStaticExpressionFunction( QStringLiteral( "lighter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8406 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8407 fncLighter, QStringLiteral( "Color" ) )
8408 << new QgsStaticExpressionFunction( QStringLiteral( "set_color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fncSetColorPart, QStringLiteral( "Color" ) )
8409
8410 // file info
8411 << new QgsStaticExpressionFunction( QStringLiteral( "base_file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8412 fcnBaseFileName, QStringLiteral( "Files and Paths" ) )
8413 << new QgsStaticExpressionFunction( QStringLiteral( "file_suffix" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8414 fcnFileSuffix, QStringLiteral( "Files and Paths" ) )
8415 << new QgsStaticExpressionFunction( QStringLiteral( "file_exists" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8416 fcnFileExists, QStringLiteral( "Files and Paths" ) )
8417 << new QgsStaticExpressionFunction( QStringLiteral( "file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8418 fcnFileName, QStringLiteral( "Files and Paths" ) )
8419 << new QgsStaticExpressionFunction( QStringLiteral( "is_file" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8420 fcnPathIsFile, QStringLiteral( "Files and Paths" ) )
8421 << new QgsStaticExpressionFunction( QStringLiteral( "is_directory" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8422 fcnPathIsDir, QStringLiteral( "Files and Paths" ) )
8423 << new QgsStaticExpressionFunction( QStringLiteral( "file_path" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8424 fcnFilePath, QStringLiteral( "Files and Paths" ) )
8425 << new QgsStaticExpressionFunction( QStringLiteral( "file_size" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8426 fcnFileSize, QStringLiteral( "Files and Paths" ) )
8427
8428 << new QgsStaticExpressionFunction( QStringLiteral( "exif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tag" ), true ),
8429 fcnExif, QStringLiteral( "Files and Paths" ) )
8430 << new QgsStaticExpressionFunction( QStringLiteral( "exif_geotag" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8431 fcnExifGeoTag, QStringLiteral( "GeometryGroup" ) )
8432
8433 // hash
8434 << new QgsStaticExpressionFunction( QStringLiteral( "hash" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "method" ) ),
8435 fcnGenericHash, QStringLiteral( "Conversions" ) )
8436 << new QgsStaticExpressionFunction( QStringLiteral( "md5" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8437 fcnHashMd5, QStringLiteral( "Conversions" ) )
8438 << new QgsStaticExpressionFunction( QStringLiteral( "sha256" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8439 fcnHashSha256, QStringLiteral( "Conversions" ) )
8440
8441 //base64
8442 << new QgsStaticExpressionFunction( QStringLiteral( "to_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8443 fcnToBase64, QStringLiteral( "Conversions" ) )
8444 << new QgsStaticExpressionFunction( QStringLiteral( "from_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8445 fcnFromBase64, QStringLiteral( "Conversions" ) )
8446
8447 // deprecated stuff - hidden from users
8448 << new QgsStaticExpressionFunction( QStringLiteral( "$scale" ), QgsExpressionFunction::ParameterList(), fcnMapScale, QStringLiteral( "deprecated" ) );
8449
8450 QgsStaticExpressionFunction *geomFunc = new QgsStaticExpressionFunction( QStringLiteral( "$geometry" ), 0, fcnGeometry, QStringLiteral( "GeometryGroup" ), QString(), true );
8451 geomFunc->setIsStatic( false );
8452 functions << geomFunc;
8453
8454 QgsStaticExpressionFunction *areaFunc = new QgsStaticExpressionFunction( QStringLiteral( "$area" ), 0, fcnGeomArea, QStringLiteral( "GeometryGroup" ), QString(), true );
8455 areaFunc->setIsStatic( false );
8456 functions << areaFunc;
8457
8458 functions << new QgsStaticExpressionFunction( QStringLiteral( "area" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnArea, QStringLiteral( "GeometryGroup" ) );
8459
8460 QgsStaticExpressionFunction *lengthFunc = new QgsStaticExpressionFunction( QStringLiteral( "$length" ), 0, fcnGeomLength, QStringLiteral( "GeometryGroup" ), QString(), true );
8461 lengthFunc->setIsStatic( false );
8462 functions << lengthFunc;
8463
8464 QgsStaticExpressionFunction *perimeterFunc = new QgsStaticExpressionFunction( QStringLiteral( "$perimeter" ), 0, fcnGeomPerimeter, QStringLiteral( "GeometryGroup" ), QString(), true );
8465 perimeterFunc->setIsStatic( false );
8466 functions << perimeterFunc;
8467
8468 functions << new QgsStaticExpressionFunction( QStringLiteral( "perimeter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPerimeter, QStringLiteral( "GeometryGroup" ) );
8469
8470 functions << new QgsStaticExpressionFunction( QStringLiteral( "roundness" ),
8472 fcnRoundness, QStringLiteral( "GeometryGroup" ) );
8473
8474 QgsStaticExpressionFunction *xFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x" ), 0, fcnX, QStringLiteral( "GeometryGroup" ), QString(), true );
8475 xFunc->setIsStatic( false );
8476 functions << xFunc;
8477
8478 QgsStaticExpressionFunction *yFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y" ), 0, fcnY, QStringLiteral( "GeometryGroup" ), QString(), true );
8479 yFunc->setIsStatic( false );
8480 functions << yFunc;
8481
8482 QgsStaticExpressionFunction *zFunc = new QgsStaticExpressionFunction( QStringLiteral( "$z" ), 0, fcnZ, QStringLiteral( "GeometryGroup" ), QString(), true );
8483 zFunc->setIsStatic( false );
8484 functions << zFunc;
8485
8486 QMap< QString, QgsExpressionFunction::FcnEval > geometry_overlay_definitions
8487 {
8488 { QStringLiteral( "overlay_intersects" ), fcnGeomOverlayIntersects },
8489 { QStringLiteral( "overlay_contains" ), fcnGeomOverlayContains },
8490 { QStringLiteral( "overlay_crosses" ), fcnGeomOverlayCrosses },
8491 { QStringLiteral( "overlay_equals" ), fcnGeomOverlayEquals },
8492 { QStringLiteral( "overlay_touches" ), fcnGeomOverlayTouches },
8493 { QStringLiteral( "overlay_disjoint" ), fcnGeomOverlayDisjoint },
8494 { QStringLiteral( "overlay_within" ), fcnGeomOverlayWithin },
8495 };
8496 QMapIterator< QString, QgsExpressionFunction::FcnEval > i( geometry_overlay_definitions );
8497 while ( i.hasNext() )
8498 {
8499 i.next();
8501 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8502 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8503 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8504 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( -1 ), true )
8505 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false )
8506 << QgsExpressionFunction::Parameter( QStringLiteral( "min_overlap" ), true, QVariant( -1 ), false )
8507 << QgsExpressionFunction::Parameter( QStringLiteral( "min_inscribed_circle_radius" ), true, QVariant( -1 ), false )
8508 << QgsExpressionFunction::Parameter( QStringLiteral( "return_details" ), true, false, false )
8509 << QgsExpressionFunction::Parameter( QStringLiteral( "sort_by_intersection_size" ), true, QString(), false ),
8510 i.value(), QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8511
8512 // The current feature is accessed for the geometry, so this should not be cached
8513 fcnGeomOverlayFunc->setIsStatic( false );
8514 functions << fcnGeomOverlayFunc;
8515 }
8516
8517 QgsStaticExpressionFunction *fcnGeomOverlayNearestFunc = new QgsStaticExpressionFunction( QStringLiteral( "overlay_nearest" ), QgsExpressionFunction::ParameterList()
8518 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8519 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8520 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8521 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( 1 ), true )
8522 << QgsExpressionFunction::Parameter( QStringLiteral( "max_distance" ), true, 0 )
8523 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false ),
8524 fcnGeomOverlayNearest, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8525 // The current feature is accessed for the geometry, so this should not be cached
8526 fcnGeomOverlayNearestFunc->setIsStatic( false );
8527 functions << fcnGeomOverlayNearestFunc;
8528
8529 functions
8530 << new QgsStaticExpressionFunction( QStringLiteral( "is_valid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomIsValid, QStringLiteral( "GeometryGroup" ) )
8531 << new QgsStaticExpressionFunction( QStringLiteral( "x" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomX, QStringLiteral( "GeometryGroup" ) )
8532 << new QgsStaticExpressionFunction( QStringLiteral( "y" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomY, QStringLiteral( "GeometryGroup" ) )
8533 << new QgsStaticExpressionFunction( QStringLiteral( "z" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomZ, QStringLiteral( "GeometryGroup" ) )
8534 << new QgsStaticExpressionFunction( QStringLiteral( "m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomM, QStringLiteral( "GeometryGroup" ) )
8535 << new QgsStaticExpressionFunction( QStringLiteral( "point_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ), fcnPointN, QStringLiteral( "GeometryGroup" ) )
8536 << new QgsStaticExpressionFunction( QStringLiteral( "start_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnStartPoint, QStringLiteral( "GeometryGroup" ) )
8537 << new QgsStaticExpressionFunction( QStringLiteral( "end_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnEndPoint, QStringLiteral( "GeometryGroup" ) )
8538 << new QgsStaticExpressionFunction( QStringLiteral( "nodes_to_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8539 << QgsExpressionFunction::Parameter( QStringLiteral( "ignore_closing_nodes" ), true, false ),
8540 fcnNodesToPoints, QStringLiteral( "GeometryGroup" ) )
8541 << new QgsStaticExpressionFunction( QStringLiteral( "segments_to_lines" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnSegmentsToLines, QStringLiteral( "GeometryGroup" ) )
8542 << new QgsStaticExpressionFunction( QStringLiteral( "collect_geometries" ), -1, fcnCollectGeometries, QStringLiteral( "GeometryGroup" ) )
8543 << new QgsStaticExpressionFunction( QStringLiteral( "make_point" ), -1, fcnMakePoint, QStringLiteral( "GeometryGroup" ) )
8544 << new QgsStaticExpressionFunction( QStringLiteral( "make_point_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
8545 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) )
8546 << QgsExpressionFunction::Parameter( QStringLiteral( "m" ) ),
8547 fcnMakePointM, QStringLiteral( "GeometryGroup" ) )
8548 << new QgsStaticExpressionFunction( QStringLiteral( "make_line" ), -1, fcnMakeLine, QStringLiteral( "GeometryGroup" ) )
8549 << new QgsStaticExpressionFunction( QStringLiteral( "make_polygon" ), -1, fcnMakePolygon, QStringLiteral( "GeometryGroup" ) )
8550 << new QgsStaticExpressionFunction( QStringLiteral( "make_triangle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8551 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8552 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) ),
8553 fcnMakeTriangle, QStringLiteral( "GeometryGroup" ) )
8554 << new QgsStaticExpressionFunction( QStringLiteral( "make_circle" ), QgsExpressionFunction::ParameterList()
8555 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8556 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8557 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8558 fcnMakeCircle, QStringLiteral( "GeometryGroup" ) )
8559 << new QgsStaticExpressionFunction( QStringLiteral( "make_ellipse" ), QgsExpressionFunction::ParameterList()
8560 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8561 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_major_axis" ) )
8562 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_minor_axis" ) )
8563 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
8564 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8565 fcnMakeEllipse, QStringLiteral( "GeometryGroup" ) )
8566 << new QgsStaticExpressionFunction( QStringLiteral( "make_regular_polygon" ), QgsExpressionFunction::ParameterList()
8567 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8568 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8569 << QgsExpressionFunction::Parameter( QStringLiteral( "number_sides" ) )
8570 << QgsExpressionFunction::Parameter( QStringLiteral( "circle" ), true, 0 ),
8571 fcnMakeRegularPolygon, QStringLiteral( "GeometryGroup" ) )
8572 << new QgsStaticExpressionFunction( QStringLiteral( "make_square" ), QgsExpressionFunction::ParameterList()
8573 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8574 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) ),
8575 fcnMakeSquare, QStringLiteral( "GeometryGroup" ) )
8576 << new QgsStaticExpressionFunction( QStringLiteral( "make_rectangle_3points" ), QgsExpressionFunction::ParameterList()
8577 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8578 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8579 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) )
8580 << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, 0 ),
8581 fcnMakeRectangleFrom3Points, QStringLiteral( "GeometryGroup" ) )
8582 << new QgsStaticExpressionFunction( QStringLiteral( "make_valid" ), QgsExpressionFunction::ParameterList
8583 {
8584 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8585#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
8586 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "linework" ) ),
8587#else
8588 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "structure" ) ),
8589#endif
8590 QgsExpressionFunction::Parameter( QStringLiteral( "keep_collapsed" ), true, false )
8591 }, fcnGeomMakeValid, QStringLiteral( "GeometryGroup" ) );
8592
8593 functions << new QgsStaticExpressionFunction( QStringLiteral( "x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnXat, QStringLiteral( "GeometryGroup" ) );
8594 functions << new QgsStaticExpressionFunction( QStringLiteral( "y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnYat, QStringLiteral( "GeometryGroup" ) );
8595 functions << new QgsStaticExpressionFunction( QStringLiteral( "z_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnZat, QStringLiteral( "GeometryGroup" ) );
8596 functions << new QgsStaticExpressionFunction( QStringLiteral( "m_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnMat, QStringLiteral( "GeometryGroup" ) );
8597
8598 QgsStaticExpressionFunction *xAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldXat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "xat" ) );
8599 xAtFunc->setIsStatic( false );
8600 functions << xAtFunc;
8601
8602
8603 QgsStaticExpressionFunction *yAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldYat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "yat" ) );
8604 yAtFunc->setIsStatic( false );
8605 functions << yAtFunc;
8606
8607 functions
8608 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_type" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeometryType, QStringLiteral( "GeometryGroup" ) )
8609 << new QgsStaticExpressionFunction( QStringLiteral( "x_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmin" ) )
8610 << new QgsStaticExpressionFunction( QStringLiteral( "x_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmax" ) )
8611 << new QgsStaticExpressionFunction( QStringLiteral( "y_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymin" ) )
8612 << new QgsStaticExpressionFunction( QStringLiteral( "y_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymax" ) )
8613 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ), fcnGeomFromWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromWKT" ) )
8614 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "binary" ) ), fcnGeomFromWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
8615 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_gml" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "gml" ) ), fcnGeomFromGML, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromGML" ) )
8616 << new QgsStaticExpressionFunction( QStringLiteral( "flip_coordinates" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnFlipCoordinates, QStringLiteral( "GeometryGroup" ) )
8617 << new QgsStaticExpressionFunction( QStringLiteral( "relate" ), -1, fcnRelate, QStringLiteral( "GeometryGroup" ) )
8618 << new QgsStaticExpressionFunction( QStringLiteral( "intersects_bbox" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ), fcnBbox, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "bbox" ) )
8619 << new QgsStaticExpressionFunction( QStringLiteral( "disjoint" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8620 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8621 fcnDisjoint, QStringLiteral( "GeometryGroup" ) )
8622 << new QgsStaticExpressionFunction( QStringLiteral( "intersects" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8623 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8624 fcnIntersects, QStringLiteral( "GeometryGroup" ) )
8625 << new QgsStaticExpressionFunction( QStringLiteral( "touches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8626 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8627 fcnTouches, QStringLiteral( "GeometryGroup" ) )
8628 << new QgsStaticExpressionFunction( QStringLiteral( "crosses" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8629 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8630 fcnCrosses, QStringLiteral( "GeometryGroup" ) )
8631 << new QgsStaticExpressionFunction( QStringLiteral( "contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8632 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8633 fcnContains, QStringLiteral( "GeometryGroup" ) )
8634 << new QgsStaticExpressionFunction( QStringLiteral( "overlaps" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8635 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8636 fcnOverlaps, QStringLiteral( "GeometryGroup" ) )
8637 << new QgsStaticExpressionFunction( QStringLiteral( "within" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8638 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8639 fcnWithin, QStringLiteral( "GeometryGroup" ) )
8640 << new QgsStaticExpressionFunction( QStringLiteral( "translate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8641 << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) )
8642 << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ),
8643 fcnTranslate, QStringLiteral( "GeometryGroup" ) )
8644 << new QgsStaticExpressionFunction( QStringLiteral( "rotate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8645 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation" ) )
8646 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true )
8647 << QgsExpressionFunction::Parameter( QStringLiteral( "per_part" ), true, false ),
8648 fcnRotate, QStringLiteral( "GeometryGroup" ) )
8649 << new QgsStaticExpressionFunction( QStringLiteral( "scale" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8650 << QgsExpressionFunction::Parameter( QStringLiteral( "x_scale" ) )
8651 << QgsExpressionFunction::Parameter( QStringLiteral( "y_scale" ) )
8652 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true ),
8653 fcnScale, QStringLiteral( "GeometryGroup" ) )
8654 << new QgsStaticExpressionFunction( QStringLiteral( "affine_transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8655 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_x" ) )
8656 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_y" ) )
8657 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation_z" ) )
8658 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_x" ) )
8659 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_y" ) )
8660 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_z" ), true, 0 )
8661 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_m" ), true, 0 )
8662 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_z" ), true, 1 )
8663 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_m" ), true, 1 ),
8664 fcnAffineTransform, QStringLiteral( "GeometryGroup" ) )
8665 << new QgsStaticExpressionFunction( QStringLiteral( "buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8666 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8667 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8 )
8668 << QgsExpressionFunction::Parameter( QStringLiteral( "cap" ), true, QStringLiteral( "round" ) )
8669 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, QStringLiteral( "round" ) )
8670 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2 ),
8671 fcnBuffer, QStringLiteral( "GeometryGroup" ) )
8672 << new QgsStaticExpressionFunction( QStringLiteral( "force_rhr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8673 fcnForceRHR, QStringLiteral( "GeometryGroup" ) )
8674 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_cw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8675 fcnForcePolygonCW, QStringLiteral( "GeometryGroup" ) )
8676 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_ccw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8677 fcnForcePolygonCCW, QStringLiteral( "GeometryGroup" ) )
8678 << new QgsStaticExpressionFunction( QStringLiteral( "wedge_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8679 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
8680 << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) )
8681 << QgsExpressionFunction::Parameter( QStringLiteral( "outer_radius" ) )
8682 << QgsExpressionFunction::Parameter( QStringLiteral( "inner_radius" ), true, 0.0 ), fcnWedgeBuffer, QStringLiteral( "GeometryGroup" ) )
8683 << new QgsStaticExpressionFunction( QStringLiteral( "tapered_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8684 << QgsExpressionFunction::Parameter( QStringLiteral( "start_width" ) )
8685 << QgsExpressionFunction::Parameter( QStringLiteral( "end_width" ) )
8686 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8687 , fcnTaperedBuffer, QStringLiteral( "GeometryGroup" ) )
8688 << new QgsStaticExpressionFunction( QStringLiteral( "buffer_by_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8689 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8690 , fcnBufferByM, QStringLiteral( "GeometryGroup" ) )
8691 << new QgsStaticExpressionFunction( QStringLiteral( "offset_curve" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8692 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8693 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8694 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
8695 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
8696 fcnOffsetCurve, QStringLiteral( "GeometryGroup" ) )
8697 << new QgsStaticExpressionFunction( QStringLiteral( "single_sided_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8698 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8699 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8700 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
8701 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
8702 fcnSingleSidedBuffer, QStringLiteral( "GeometryGroup" ) )
8703 << new QgsStaticExpressionFunction( QStringLiteral( "extend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8704 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) )
8705 << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ),
8706 fcnExtend, QStringLiteral( "GeometryGroup" ) )
8707 << new QgsStaticExpressionFunction( QStringLiteral( "centroid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCentroid, QStringLiteral( "GeometryGroup" ) )
8708 << new QgsStaticExpressionFunction( QStringLiteral( "point_on_surface" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) )
8709 << new QgsStaticExpressionFunction( QStringLiteral( "pole_of_inaccessibility" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8710 << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnPoleOfInaccessibility, QStringLiteral( "GeometryGroup" ) )
8711 << new QgsStaticExpressionFunction( QStringLiteral( "reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnReverse, QStringLiteral( "GeometryGroup" ) )
8712 << new QgsStaticExpressionFunction( QStringLiteral( "exterior_ring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnExteriorRing, QStringLiteral( "GeometryGroup" ) )
8713 << new QgsStaticExpressionFunction( QStringLiteral( "interior_ring_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8714 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
8715 fcnInteriorRingN, QStringLiteral( "GeometryGroup" ) )
8716 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8717 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
8718 fcnGeometryN, QStringLiteral( "GeometryGroup" ) )
8719 << new QgsStaticExpressionFunction( QStringLiteral( "boundary" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundary, QStringLiteral( "GeometryGroup" ) )
8720 << new QgsStaticExpressionFunction( QStringLiteral( "line_merge" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLineMerge, QStringLiteral( "GeometryGroup" ) )
8721 << new QgsStaticExpressionFunction( QStringLiteral( "shared_paths" ), QgsExpressionFunction::ParameterList
8722 {
8723 QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ),
8724 QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
8725 }, fcnSharedPaths, QStringLiteral( "GeometryGroup" ) )
8726 << new QgsStaticExpressionFunction( QStringLiteral( "bounds" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBounds, QStringLiteral( "GeometryGroup" ) )
8727 << new QgsStaticExpressionFunction( QStringLiteral( "simplify" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplify, QStringLiteral( "GeometryGroup" ) )
8728 << new QgsStaticExpressionFunction( QStringLiteral( "simplify_vw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplifyVW, QStringLiteral( "GeometryGroup" ) )
8729 << new QgsStaticExpressionFunction( QStringLiteral( "smooth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "iterations" ), true, 1 )
8730 << QgsExpressionFunction::Parameter( QStringLiteral( "offset" ), true, 0.25 )
8731 << QgsExpressionFunction::Parameter( QStringLiteral( "min_length" ), true, -1 )
8732 << QgsExpressionFunction::Parameter( QStringLiteral( "max_angle" ), true, 180 ), fcnSmooth, QStringLiteral( "GeometryGroup" ) )
8733 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave" ),
8734 {
8735 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8736 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8737 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8738 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8739 }, fcnTriangularWave, QStringLiteral( "GeometryGroup" ) )
8740 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave_randomized" ),
8741 {
8742 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8743 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8744 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8745 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8746 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8747 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8748 }, fcnTriangularWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8749 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave" ),
8750 {
8751 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8752 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8753 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8754 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8755 }, fcnSquareWave, QStringLiteral( "GeometryGroup" ) )
8756 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave_randomized" ),
8757 {
8758 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8759 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8760 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8761 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8762 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8763 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8764 }, fcnSquareWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8765 << new QgsStaticExpressionFunction( QStringLiteral( "wave" ),
8766 {
8767 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8768 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8769 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8770 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8771 }, fcnRoundWave, QStringLiteral( "GeometryGroup" ) )
8772 << new QgsStaticExpressionFunction( QStringLiteral( "wave_randomized" ),
8773 {
8774 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8775 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8776 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8777 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8778 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8779 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8780 }, fcnRoundWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8781 << new QgsStaticExpressionFunction( QStringLiteral( "apply_dash_pattern" ),
8782 {
8783 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8784 QgsExpressionFunction::Parameter( QStringLiteral( "pattern" ) ),
8785 QgsExpressionFunction::Parameter( QStringLiteral( "start_rule" ), true, QStringLiteral( "no_rule" ) ),
8786 QgsExpressionFunction::Parameter( QStringLiteral( "end_rule" ), true, QStringLiteral( "no_rule" ) ),
8787 QgsExpressionFunction::Parameter( QStringLiteral( "adjustment" ), true, QStringLiteral( "both" ) ),
8788 QgsExpressionFunction::Parameter( QStringLiteral( "pattern_offset" ), true, 0 ),
8789 }, fcnApplyDashPattern, QStringLiteral( "GeometryGroup" ) )
8790 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_count" ),
8791 {
8792 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8793 QgsExpressionFunction::Parameter( QStringLiteral( "vertices" ) )
8794 }, fcnDensifyByCount, QStringLiteral( "GeometryGroup" ) )
8795 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_distance" ),
8796 {
8797 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8798 QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8799 }, fcnDensifyByDistance, QStringLiteral( "GeometryGroup" ) )
8800 << new QgsStaticExpressionFunction( QStringLiteral( "num_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumPoints, QStringLiteral( "GeometryGroup" ) )
8801 << new QgsStaticExpressionFunction( QStringLiteral( "num_interior_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumInteriorRings, QStringLiteral( "GeometryGroup" ) )
8802 << new QgsStaticExpressionFunction( QStringLiteral( "num_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumRings, QStringLiteral( "GeometryGroup" ) )
8803 << new QgsStaticExpressionFunction( QStringLiteral( "num_geometries" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumGeometries, QStringLiteral( "GeometryGroup" ) )
8804 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_width" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsWidth, QStringLiteral( "GeometryGroup" ) )
8805 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_height" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsHeight, QStringLiteral( "GeometryGroup" ) )
8806 << new QgsStaticExpressionFunction( QStringLiteral( "is_closed" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsClosed, QStringLiteral( "GeometryGroup" ) )
8807 << new QgsStaticExpressionFunction( QStringLiteral( "close_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCloseLine, QStringLiteral( "GeometryGroup" ) )
8808 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmpty, QStringLiteral( "GeometryGroup" ) )
8809 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty_or_null" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmptyOrNull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8810 << new QgsStaticExpressionFunction( QStringLiteral( "convex_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnConvexHull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "convexHull" ) )
8811#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
8812 << new QgsStaticExpressionFunction( QStringLiteral( "concave_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8813 << QgsExpressionFunction::Parameter( QStringLiteral( "target_percent" ) )
8814 << QgsExpressionFunction::Parameter( QStringLiteral( "allow_holes" ), true, false ), fcnConcaveHull, QStringLiteral( "GeometryGroup" ) )
8815#endif
8816 << new QgsStaticExpressionFunction( QStringLiteral( "oriented_bbox" ), QgsExpressionFunction::ParameterList()
8817 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8818 fcnOrientedBBox, QStringLiteral( "GeometryGroup" ) )
8819 << new QgsStaticExpressionFunction( QStringLiteral( "main_angle" ), QgsExpressionFunction::ParameterList()
8820 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8821 fcnMainAngle, QStringLiteral( "GeometryGroup" ) )
8822 << new QgsStaticExpressionFunction( QStringLiteral( "minimal_circle" ), QgsExpressionFunction::ParameterList()
8823 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8824 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8825 fcnMinimalCircle, QStringLiteral( "GeometryGroup" ) )
8826 << new QgsStaticExpressionFunction( QStringLiteral( "difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8827 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8828 fcnDifference, QStringLiteral( "GeometryGroup" ) )
8829 << new QgsStaticExpressionFunction( QStringLiteral( "distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8830 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8831 fcnDistance, QStringLiteral( "GeometryGroup" ) )
8832 << new QgsStaticExpressionFunction( QStringLiteral( "hausdorff_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
8833 << QgsExpressionFunction::Parameter( QStringLiteral( "densify_fraction" ), true ),
8834 fcnHausdorffDistance, QStringLiteral( "GeometryGroup" ) )
8835 << new QgsStaticExpressionFunction( QStringLiteral( "intersection" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8836 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8837 fcnIntersection, QStringLiteral( "GeometryGroup" ) )
8838 << new QgsStaticExpressionFunction( QStringLiteral( "sym_difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8839 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8840 fcnSymDifference, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "symDifference" ) )
8841 << new QgsStaticExpressionFunction( QStringLiteral( "combine" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8842 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8843 fcnCombine, QStringLiteral( "GeometryGroup" ) )
8844 << new QgsStaticExpressionFunction( QStringLiteral( "union" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8845 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8846 fcnCombine, QStringLiteral( "GeometryGroup" ) )
8847 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8848 << QgsExpressionFunction::Parameter( QStringLiteral( "precision" ), true, 8.0 ),
8849 fcnGeomToWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomToWKT" ) )
8850 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8851 fcnGeomToWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
8852 << new QgsStaticExpressionFunction( QStringLiteral( "geometry" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetGeometry, QStringLiteral( "GeometryGroup" ), QString(), true )
8853 << new QgsStaticExpressionFunction( QStringLiteral( "transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8854 << QgsExpressionFunction::Parameter( QStringLiteral( "source_auth_id" ) )
8855 << QgsExpressionFunction::Parameter( QStringLiteral( "dest_auth_id" ) ),
8856 fcnTransformGeometry, QStringLiteral( "GeometryGroup" ) )
8857 << new QgsStaticExpressionFunction( QStringLiteral( "extrude" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8858 << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
8859 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) ),
8860 fcnExtrude, QStringLiteral( "GeometryGroup" ), QString() )
8861 << new QgsStaticExpressionFunction( QStringLiteral( "is_multipart" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8862 fcnGeomIsMultipart, QStringLiteral( "GeometryGroup" ) )
8863 << new QgsStaticExpressionFunction( QStringLiteral( "z_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8864 fcnZMax, QStringLiteral( "GeometryGroup" ) )
8865 << new QgsStaticExpressionFunction( QStringLiteral( "z_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8866 fcnZMin, QStringLiteral( "GeometryGroup" ) )
8867 << new QgsStaticExpressionFunction( QStringLiteral( "m_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8868 fcnMMax, QStringLiteral( "GeometryGroup" ) )
8869 << new QgsStaticExpressionFunction( QStringLiteral( "m_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8870 fcnMMin, QStringLiteral( "GeometryGroup" ) )
8871 << new QgsStaticExpressionFunction( QStringLiteral( "sinuosity" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8872 fcnSinuosity, QStringLiteral( "GeometryGroup" ) )
8873 << new QgsStaticExpressionFunction( QStringLiteral( "straight_distance_2d" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8874 fcnStraightDistance2d, QStringLiteral( "GeometryGroup" ) );
8875
8876
8877 QgsStaticExpressionFunction *orderPartsFunc = new QgsStaticExpressionFunction( QStringLiteral( "order_parts" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8878 << QgsExpressionFunction::Parameter( QStringLiteral( "orderby" ) )
8879 << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ),
8880 fcnOrderParts, QStringLiteral( "GeometryGroup" ), QString() );
8881
8882 orderPartsFunc->setIsStaticFunction(
8883 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
8884 {
8885 const QList< QgsExpressionNode *> argList = node->args()->list();
8886 for ( QgsExpressionNode *argNode : argList )
8887 {
8888 if ( !argNode->isStatic( parent, context ) )
8889 return false;
8890 }
8891
8892 if ( node->args()->count() > 1 )
8893 {
8894 QgsExpressionNode *argNode = node->args()->at( 1 );
8895
8896 QString expString = argNode->eval( parent, context ).toString();
8897
8898 QgsExpression e( expString );
8899
8900 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
8901 return true;
8902 }
8903
8904 return true;
8905 } );
8906
8907 orderPartsFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
8908 {
8909 if ( node->args()->count() > 1 )
8910 {
8911 QgsExpressionNode *argNode = node->args()->at( 1 );
8912 QString expression = argNode->eval( parent, context ).toString();
8914 e.prepare( context );
8915 context->setCachedValue( expression, QVariant::fromValue( e ) );
8916 }
8917 return true;
8918 }
8919 );
8920 functions << orderPartsFunc;
8921
8922 functions
8923 << new QgsStaticExpressionFunction( QStringLiteral( "closest_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8924 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8925 fcnClosestPoint, QStringLiteral( "GeometryGroup" ) )
8926 << new QgsStaticExpressionFunction( QStringLiteral( "shortest_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8927 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8928 fcnShortestLine, QStringLiteral( "GeometryGroup" ) )
8929 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8930 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolatePoint, QStringLiteral( "GeometryGroup" ) )
8931 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_angle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8932 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolateAngle, QStringLiteral( "GeometryGroup" ) )
8933 << new QgsStaticExpressionFunction( QStringLiteral( "line_locate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8934 << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnLineLocatePoint, QStringLiteral( "GeometryGroup" ) )
8935 << new QgsStaticExpressionFunction( QStringLiteral( "angle_at_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8936 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnAngleAtVertex, QStringLiteral( "GeometryGroup" ) )
8937 << new QgsStaticExpressionFunction( QStringLiteral( "distance_to_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8938 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnDistanceToVertex, QStringLiteral( "GeometryGroup" ) )
8939 << new QgsStaticExpressionFunction( QStringLiteral( "line_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8940 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ), fcnLineSubset, QStringLiteral( "GeometryGroup" ) );
8941
8942
8943 // **Record** functions
8944
8945 QgsStaticExpressionFunction *idFunc = new QgsStaticExpressionFunction( QStringLiteral( "$id" ), 0, fcnFeatureId, QStringLiteral( "Record and Attributes" ) );
8946 idFunc->setIsStatic( false );
8947 functions << idFunc;
8948
8949 QgsStaticExpressionFunction *currentFeatureFunc = new QgsStaticExpressionFunction( QStringLiteral( "$currentfeature" ), 0, fcnFeature, QStringLiteral( "Record and Attributes" ) );
8950 currentFeatureFunc->setIsStatic( false );
8951 functions << currentFeatureFunc;
8952
8953 QgsStaticExpressionFunction *uuidFunc = new QgsStaticExpressionFunction( QStringLiteral( "uuid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "format" ), true, QStringLiteral( "WithBraces" ) ), fcnUuid, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$uuid" ) );
8954 uuidFunc->setIsStatic( false );
8955 functions << uuidFunc;
8956
8957 functions
8958 << new QgsStaticExpressionFunction( QStringLiteral( "feature_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetFeatureId, QStringLiteral( "Record and Attributes" ), QString(), true )
8959 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8960 << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) )
8961 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ), true ),
8962 fcnGetFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "QgsExpressionUtils::getFeature" ) )
8963 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature_by_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8964 << QgsExpressionFunction::Parameter( QStringLiteral( "feature_id" ) ),
8965 fcnGetFeatureById, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false );
8966
8967 QgsStaticExpressionFunction *attributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true ),
8968 fcnAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8969 attributesFunc->setIsStatic( false );
8970 functions << attributesFunc;
8971 QgsStaticExpressionFunction *representAttributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_attributes" ), -1,
8972 fcnRepresentAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8973 representAttributesFunc->setIsStatic( false );
8974 functions << representAttributesFunc;
8975
8976 QgsStaticExpressionFunction *validateFeature = new QgsStaticExpressionFunction( QStringLiteral( "is_feature_valid" ),
8977 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
8978 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
8979 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
8980 fcnValidateFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8981 validateFeature->setIsStatic( false );
8982 functions << validateFeature;
8983
8984 QgsStaticExpressionFunction *validateAttribute = new QgsStaticExpressionFunction( QStringLiteral( "is_attribute_valid" ),
8985 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ), false )
8986 << QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
8987 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
8988 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
8989 fcnValidateAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8990 validateAttribute->setIsStatic( false );
8991 functions << validateAttribute;
8992
8994 QStringLiteral( "maptip" ),
8995 -1,
8996 fcnFeatureMaptip,
8997 QStringLiteral( "Record and Attributes" ),
8998 QString(),
8999 false,
9000 QSet<QString>()
9001 );
9002 maptipFunc->setIsStatic( false );
9003 functions << maptipFunc;
9004
9006 QStringLiteral( "display_expression" ),
9007 -1,
9008 fcnFeatureDisplayExpression,
9009 QStringLiteral( "Record and Attributes" ),
9010 QString(),
9011 false,
9012 QSet<QString>()
9013 );
9014 displayFunc->setIsStatic( false );
9015 functions << displayFunc;
9016
9018 QStringLiteral( "is_selected" ),
9019 -1,
9020 fcnIsSelected,
9021 QStringLiteral( "Record and Attributes" ),
9022 QString(),
9023 false,
9024 QSet<QString>()
9025 );
9026 isSelectedFunc->setIsStatic( false );
9027 functions << isSelectedFunc;
9028
9029 functions
9031 QStringLiteral( "num_selected" ),
9032 -1,
9033 fcnNumSelected,
9034 QStringLiteral( "Record and Attributes" ),
9035 QString(),
9036 false,
9037 QSet<QString>()
9038 );
9039
9040 functions
9042 QStringLiteral( "sqlite_fetch_and_increment" ),
9044 << QgsExpressionFunction::Parameter( QStringLiteral( "database" ) )
9045 << QgsExpressionFunction::Parameter( QStringLiteral( "table" ) )
9046 << QgsExpressionFunction::Parameter( QStringLiteral( "id_field" ) )
9047 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_attribute" ) )
9048 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_value" ) )
9049 << QgsExpressionFunction::Parameter( QStringLiteral( "default_values" ), true ),
9050 fcnSqliteFetchAndIncrement,
9051 QStringLiteral( "Record and Attributes" )
9052 );
9053
9054 // **Fields and Values** functions
9055 QgsStaticExpressionFunction *representValueFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "field_name" ), true ), fcnRepresentValue, QStringLiteral( "Record and Attributes" ) );
9056
9057 representValueFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9058 {
9059 Q_UNUSED( context )
9060 if ( node->args()->count() == 1 )
9061 {
9062 QgsExpressionNodeColumnRef *colRef = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
9063 if ( colRef )
9064 {
9065 return true;
9066 }
9067 else
9068 {
9069 parent->setEvalErrorString( tr( "If represent_value is called with 1 parameter, it must be an attribute." ) );
9070 return false;
9071 }
9072 }
9073 else if ( node->args()->count() == 2 )
9074 {
9075 return true;
9076 }
9077 else
9078 {
9079 parent->setEvalErrorString( tr( "represent_value must be called with exactly 1 or 2 parameters." ) );
9080 return false;
9081 }
9082 }
9083 );
9084
9085 functions << representValueFunc;
9086
9087 // **General** functions
9088 functions
9089 << new QgsStaticExpressionFunction( QStringLiteral( "layer_property" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9090 << QgsExpressionFunction::Parameter( QStringLiteral( "property" ) ),
9091 fcnGetLayerProperty, QStringLiteral( "Map Layers" ) )
9092 << new QgsStaticExpressionFunction( QStringLiteral( "decode_uri" ),
9094 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9095 << QgsExpressionFunction::Parameter( QStringLiteral( "part" ), true ),
9096 fcnDecodeUri, QStringLiteral( "Map Layers" ) )
9097 << new QgsStaticExpressionFunction( QStringLiteral( "mime_type" ),
9099 << QgsExpressionFunction::Parameter( QStringLiteral( "binary_data" ) ),
9100 fcnMimeType, QStringLiteral( "General" ) )
9101 << new QgsStaticExpressionFunction( QStringLiteral( "raster_statistic" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9102 << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) )
9103 << QgsExpressionFunction::Parameter( QStringLiteral( "statistic" ) ), fcnGetRasterBandStat, QStringLiteral( "Rasters" ) );
9104
9105 // **var** function
9106 QgsStaticExpressionFunction *varFunction = new QgsStaticExpressionFunction( QStringLiteral( "var" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnGetVariable, QStringLiteral( "General" ) );
9107 varFunction->setIsStaticFunction(
9108 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9109 {
9110 /* A variable node is static if it has a static name and the name can be found at prepare
9111 * time and is tagged with isStatic.
9112 * It is not static if a variable is set during iteration or not tagged isStatic.
9113 * (e.g. geom_part variable)
9114 */
9115 if ( node->args()->count() > 0 )
9116 {
9117 QgsExpressionNode *argNode = node->args()->at( 0 );
9118
9119 if ( !argNode->isStatic( parent, context ) )
9120 return false;
9121
9122 const QString varName = argNode->eval( parent, context ).toString();
9123 if ( varName == QLatin1String( "feature" ) || varName == QLatin1String( "id" ) || varName == QLatin1String( "geometry" ) )
9124 return false;
9125
9126 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
9127 return scope ? scope->isStatic( varName ) : false;
9128 }
9129 return false;
9130 }
9131 );
9132 varFunction->setUsesGeometryFunction(
9133 []( const QgsExpressionNodeFunction * node ) -> bool
9134 {
9135 if ( node && node->args()->count() > 0 )
9136 {
9137 QgsExpressionNode *argNode = node->args()->at( 0 );
9138 if ( QgsExpressionNodeLiteral *literal = dynamic_cast<QgsExpressionNodeLiteral *>( argNode ) )
9139 {
9140 if ( literal->value() == QLatin1String( "geometry" ) || literal->value() == QLatin1String( "feature" ) )
9141 return true;
9142 }
9143 }
9144 return false;
9145 }
9146 );
9147
9148 functions
9149 << varFunction;
9150
9151 functions << new QgsStaticExpressionFunction( QStringLiteral( "eval_template" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "template" ) ), fcnEvalTemplate, QStringLiteral( "General" ), QString(), true );
9152
9153 QgsStaticExpressionFunction *evalFunc = new QgsStaticExpressionFunction( QStringLiteral( "eval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ), fcnEval, QStringLiteral( "General" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9154 evalFunc->setIsStaticFunction(
9155 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9156 {
9157 if ( node->args()->count() > 0 )
9158 {
9159 QgsExpressionNode *argNode = node->args()->at( 0 );
9160
9161 if ( argNode->isStatic( parent, context ) )
9162 {
9163 QString expString = argNode->eval( parent, context ).toString();
9164
9165 QgsExpression e( expString );
9166
9167 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
9168 return true;
9169 }
9170 }
9171
9172 return false;
9173 } );
9174
9175 functions << evalFunc;
9176
9177 QgsStaticExpressionFunction *attributeFunc = new QgsStaticExpressionFunction( QStringLiteral( "attribute" ), -1, fcnAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9178 attributeFunc->setIsStaticFunction(
9179 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9180 {
9181 const QList< QgsExpressionNode *> argList = node->args()->list();
9182 for ( QgsExpressionNode *argNode : argList )
9183 {
9184 if ( !argNode->isStatic( parent, context ) )
9185 return false;
9186 }
9187
9188 if ( node->args()->count() == 1 )
9189 {
9190 // not static -- this is the variant which uses the current feature taken direct from the expression context
9191 return false;
9192 }
9193
9194 return true;
9195 } );
9196 functions << attributeFunc;
9197
9198 functions
9199 << new QgsStaticExpressionFunction( QStringLiteral( "env" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnEnvVar, QStringLiteral( "General" ), QString() )
9201 << new QgsStaticExpressionFunction( QStringLiteral( "raster_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterValue, QStringLiteral( "Rasters" ) )
9202 << new QgsStaticExpressionFunction( QStringLiteral( "raster_attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterAttributes, QStringLiteral( "Rasters" ) )
9203
9204 // functions for arrays
9207 << new QgsStaticExpressionFunction( QStringLiteral( "array" ), -1, fcnArray, QStringLiteral( "Arrays" ), QString(), false, QSet<QString>(), false, QStringList(), true )
9208 << new QgsStaticExpressionFunction( QStringLiteral( "array_sort" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ), fcnArraySort, QStringLiteral( "Arrays" ) )
9209 << new QgsStaticExpressionFunction( QStringLiteral( "array_length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLength, QStringLiteral( "Arrays" ) )
9210 << new QgsStaticExpressionFunction( QStringLiteral( "array_contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayContains, QStringLiteral( "Arrays" ) )
9211 << new QgsStaticExpressionFunction( QStringLiteral( "array_count" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayCount, QStringLiteral( "Arrays" ) )
9212 << new QgsStaticExpressionFunction( QStringLiteral( "array_all" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_b" ) ), fcnArrayAll, QStringLiteral( "Arrays" ) )
9213 << new QgsStaticExpressionFunction( QStringLiteral( "array_find" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayFind, QStringLiteral( "Arrays" ) )
9214 << new QgsStaticExpressionFunction( QStringLiteral( "array_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayGet, QStringLiteral( "Arrays" ) )
9215 << new QgsStaticExpressionFunction( QStringLiteral( "array_first" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayFirst, QStringLiteral( "Arrays" ) )
9216 << new QgsStaticExpressionFunction( QStringLiteral( "array_last" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLast, QStringLiteral( "Arrays" ) )
9217 << new QgsStaticExpressionFunction( QStringLiteral( "array_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMinimum, QStringLiteral( "Arrays" ) )
9218 << new QgsStaticExpressionFunction( QStringLiteral( "array_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMaximum, QStringLiteral( "Arrays" ) )
9219 << new QgsStaticExpressionFunction( QStringLiteral( "array_mean" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMean, QStringLiteral( "Arrays" ) )
9220 << new QgsStaticExpressionFunction( QStringLiteral( "array_median" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMedian, QStringLiteral( "Arrays" ) )
9221 << new QgsStaticExpressionFunction( QStringLiteral( "array_majority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMajority, QStringLiteral( "Arrays" ) )
9222 << new QgsStaticExpressionFunction( QStringLiteral( "array_minority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMinority, QStringLiteral( "Arrays" ) )
9223 << new QgsStaticExpressionFunction( QStringLiteral( "array_sum" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArraySum, QStringLiteral( "Arrays" ) )
9224 << new QgsStaticExpressionFunction( QStringLiteral( "array_append" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayAppend, QStringLiteral( "Arrays" ) )
9225 << new QgsStaticExpressionFunction( QStringLiteral( "array_prepend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayPrepend, QStringLiteral( "Arrays" ) )
9226 << new QgsStaticExpressionFunction( QStringLiteral( "array_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayInsert, QStringLiteral( "Arrays" ) )
9227 << new QgsStaticExpressionFunction( QStringLiteral( "array_remove_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayRemoveAt, QStringLiteral( "Arrays" ) )
9228 << new QgsStaticExpressionFunction( QStringLiteral( "array_remove_all" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayRemoveAll, QStringLiteral( "Arrays" ), QString(), false, QSet<QString>(), false, QStringList(), true )
9229 << new QgsStaticExpressionFunction( QStringLiteral( "array_replace" ), -1, fcnArrayReplace, QStringLiteral( "Arrays" ) )
9230 << new QgsStaticExpressionFunction( QStringLiteral( "array_prioritize" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_prioritize" ) ), fcnArrayPrioritize, QStringLiteral( "Arrays" ) )
9231 << new QgsStaticExpressionFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) )
9232 << new QgsStaticExpressionFunction( QStringLiteral( "array_slice" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start_pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_pos" ) ), fcnArraySlice, QStringLiteral( "Arrays" ) )
9233 << new QgsStaticExpressionFunction( QStringLiteral( "array_reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayReverse, QStringLiteral( "Arrays" ) )
9234 << new QgsStaticExpressionFunction( QStringLiteral( "array_intersect" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) )
9235 << new QgsStaticExpressionFunction( QStringLiteral( "array_distinct" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayDistinct, QStringLiteral( "Arrays" ) )
9236 << new QgsStaticExpressionFunction( QStringLiteral( "array_to_string" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "delimiter" ), true, "," ) << QgsExpressionFunction::Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnArrayToString, QStringLiteral( "Arrays" ) )
9237 << new QgsStaticExpressionFunction( QStringLiteral( "string_to_array" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "delimiter" ), true, "," ) << QgsExpressionFunction::Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnStringToArray, QStringLiteral( "Arrays" ) )
9238 << new QgsStaticExpressionFunction( QStringLiteral( "generate_series" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "start" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "stop" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "step" ), true, 1.0 ), fcnGenerateSeries, QStringLiteral( "Arrays" ) )
9239 << new QgsStaticExpressionFunction( QStringLiteral( "geometries_to_array" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometries" ) ), fcnGeometryCollectionAsArray, QStringLiteral( "Arrays" ) )
9240
9241 //functions for maps
9242 << new QgsStaticExpressionFunction( QStringLiteral( "from_json" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLoadJson, QStringLiteral( "Maps" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "json_to_map" ) )
9243 << new QgsStaticExpressionFunction( QStringLiteral( "to_json" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "json_string" ) ), fcnWriteJson, QStringLiteral( "Maps" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "map_to_json" ) )
9244 << new QgsStaticExpressionFunction( QStringLiteral( "hstore_to_map" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnHstoreToMap, QStringLiteral( "Maps" ) )
9245 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_hstore" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapToHstore, QStringLiteral( "Maps" ) )
9246 << new QgsStaticExpressionFunction( QStringLiteral( "map" ), -1, fcnMap, QStringLiteral( "Maps" ) )
9247 << new QgsStaticExpressionFunction( QStringLiteral( "map_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapGet, QStringLiteral( "Maps" ) )
9248 << new QgsStaticExpressionFunction( QStringLiteral( "map_exist" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapExist, QStringLiteral( "Maps" ) )
9249 << new QgsStaticExpressionFunction( QStringLiteral( "map_delete" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapDelete, QStringLiteral( "Maps" ) )
9250 << new QgsStaticExpressionFunction( QStringLiteral( "map_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnMapInsert, QStringLiteral( "Maps" ) )
9251 << new QgsStaticExpressionFunction( QStringLiteral( "map_concat" ), -1, fcnMapConcat, QStringLiteral( "Maps" ) )
9252 << new QgsStaticExpressionFunction( QStringLiteral( "map_akeys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAKeys, QStringLiteral( "Maps" ) )
9253 << new QgsStaticExpressionFunction( QStringLiteral( "map_avals" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAVals, QStringLiteral( "Maps" ) )
9254 << new QgsStaticExpressionFunction( QStringLiteral( "map_prefix_keys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
9255 << QgsExpressionFunction::Parameter( QStringLiteral( "prefix" ) ),
9256 fcnMapPrefixKeys, QStringLiteral( "Maps" ) )
9257 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_table" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9258 fcnMapToHtmlTable, QStringLiteral( "Maps" ) )
9259 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_dl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9260 fcnMapToHtmlDefinitionList, QStringLiteral( "Maps" ) )
9261 << new QgsStaticExpressionFunction( QStringLiteral( "url_encode" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9262 fcnToFormUrlEncode, QStringLiteral( "Maps" ) )
9263
9264 ;
9265
9267
9268 //QgsExpression has ownership of all built-in functions
9269 for ( QgsExpressionFunction *func : std::as_const( functions ) )
9270 {
9271 *sOwnedFunctions() << func;
9272 *sBuiltinFunctions() << func->name();
9273 sBuiltinFunctions()->append( func->aliases() );
9274 }
9275 }
9276 return functions;
9277}
9278
9279bool QgsExpression::registerFunction( QgsExpressionFunction *function, bool transferOwnership )
9280{
9281 int fnIdx = functionIndex( function->name() );
9282 if ( fnIdx != -1 )
9283 {
9284 return false;
9285 }
9286
9287 QMutexLocker locker( &sFunctionsMutex );
9288 sFunctions()->append( function );
9289 if ( transferOwnership )
9290 sOwnedFunctions()->append( function );
9291
9292 return true;
9293}
9294
9295bool QgsExpression::unregisterFunction( const QString &name )
9296{
9297 // You can never override the built in functions.
9298 if ( QgsExpression::BuiltinFunctions().contains( name ) )
9299 {
9300 return false;
9301 }
9302 int fnIdx = functionIndex( name );
9303 if ( fnIdx != -1 )
9304 {
9305 QMutexLocker locker( &sFunctionsMutex );
9306 sFunctions()->removeAt( fnIdx );
9307 sFunctionIndexMap.clear();
9308 return true;
9309 }
9310 return false;
9311}
9312
9314{
9315 qDeleteAll( *sOwnedFunctions() );
9316 sOwnedFunctions()->clear();
9317}
9319const QStringList &QgsExpression::BuiltinFunctions()
9320{
9321 if ( sBuiltinFunctions()->isEmpty() )
9322 {
9323 Functions(); // this method builds the gmBuiltinFunctions as well
9324 }
9325 return *sBuiltinFunctions();
9326}
9328
9330 : QgsExpressionFunction( QStringLiteral( "array_foreach" ), QgsExpressionFunction::ParameterList() // skip-keyword-check
9331 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9332 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9333 QStringLiteral( "Arrays" ) )
9334{
9335
9336}
9337
9339{
9340 bool isStatic = false;
9341
9342 QgsExpressionNode::NodeList *args = node->args();
9344 if ( args->count() < 2 )
9345 return false;
9346
9347 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9348 {
9349 isStatic = true;
9350 }
9351 return isStatic;
9352}
9353
9355{
9356 Q_UNUSED( node )
9357 QVariantList result;
9358
9359 if ( args->count() < 2 )
9360 // error
9361 return result;
9362
9363 QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9364
9365 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9366 std::unique_ptr< QgsExpressionContext > tempContext;
9367 if ( !subContext )
9368 {
9369 tempContext = std::make_unique< QgsExpressionContext >();
9370 subContext = tempContext.get();
9371 }
9372
9374 subContext->appendScope( subScope );
9375
9376 int i = 0;
9377 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it, ++i )
9378 {
9379 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), *it, true ) );
9380 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "counter" ), i, true ) );
9381 result << args->at( 1 )->eval( parent, subContext );
9382 }
9383
9384 if ( context )
9385 delete subContext->popScope();
9386
9387 return result;
9388}
9389
9390QVariant QgsArrayForeachExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9392 // This is a dummy function, all the real handling is in run
9393 Q_UNUSED( values )
9394 Q_UNUSED( context )
9395 Q_UNUSED( parent )
9396 Q_UNUSED( node )
9397
9398 Q_ASSERT( false );
9399 return QVariant();
9400}
9401
9403{
9404 QgsExpressionNode::NodeList *args = node->args();
9405
9406 if ( args->count() < 2 )
9407 // error
9408 return false;
9409
9410 args->at( 0 )->prepare( parent, context );
9411
9412 QgsExpressionContext subContext;
9413 if ( context )
9414 subContext = *context;
9417 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9418 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "counter" ), QVariant(), true ) );
9419 subContext.appendScope( subScope );
9420
9421 args->at( 1 )->prepare( parent, &subContext );
9422
9423 return true;
9424}
9427 : QgsExpressionFunction( QStringLiteral( "array_filter" ), QgsExpressionFunction::ParameterList()
9428 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9429 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
9430 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, 0 ),
9431 QStringLiteral( "Arrays" ) )
9432{
9433
9434}
9435
9437{
9438 bool isStatic = false;
9439
9440 QgsExpressionNode::NodeList *args = node->args();
9442 if ( args->count() < 2 )
9443 return false;
9444
9445 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9446 {
9447 isStatic = true;
9448 }
9449 return isStatic;
9450}
9451
9453{
9454 Q_UNUSED( node )
9455 QVariantList result;
9456
9457 if ( args->count() < 2 )
9458 // error
9459 return result;
9460
9461 const QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9462
9463 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9464 std::unique_ptr< QgsExpressionContext > tempContext;
9465 if ( !subContext )
9466 {
9467 tempContext = std::make_unique< QgsExpressionContext >();
9468 subContext = tempContext.get();
9469 }
9470
9472 subContext->appendScope( subScope );
9473
9474 int limit = 0;
9475 if ( args->count() >= 3 )
9476 {
9477 const QVariant limitVar = args->at( 2 )->eval( parent, context );
9478
9479 if ( QgsExpressionUtils::isIntSafe( limitVar ) )
9480 {
9481 limit = limitVar.toInt();
9482 }
9483 else
9484 {
9485 return result;
9486 }
9487 }
9488
9489 for ( const QVariant &value : array )
9490 {
9491 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), value, true ) );
9492 if ( args->at( 1 )->eval( parent, subContext ).toBool() )
9493 {
9494 result << value;
9495
9496 if ( limit > 0 && limit == result.size() )
9497 break;
9498 }
9499 }
9500
9501 if ( context )
9502 delete subContext->popScope();
9503
9504 return result;
9505}
9506
9507QVariant QgsArrayFilterExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9509 // This is a dummy function, all the real handling is in run
9510 Q_UNUSED( values )
9511 Q_UNUSED( context )
9512 Q_UNUSED( parent )
9513 Q_UNUSED( node )
9514
9515 Q_ASSERT( false );
9516 return QVariant();
9517}
9518
9520{
9521 QgsExpressionNode::NodeList *args = node->args();
9522
9523 if ( args->count() < 2 )
9524 // error
9525 return false;
9526
9527 args->at( 0 )->prepare( parent, context );
9528
9529 QgsExpressionContext subContext;
9530 if ( context )
9531 subContext = *context;
9532
9534 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9535 subContext.appendScope( subScope );
9536
9537 args->at( 1 )->prepare( parent, &subContext );
9538
9539 return true;
9542 : QgsExpressionFunction( QStringLiteral( "with_variable" ), QgsExpressionFunction::ParameterList() <<
9543 QgsExpressionFunction::Parameter( QStringLiteral( "name" ) )
9544 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
9545 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9546 QStringLiteral( "General" ) )
9547{
9548
9549}
9550
9552{
9553 bool isStatic = false;
9554
9555 QgsExpressionNode::NodeList *args = node->args();
9556
9557 if ( args->count() < 3 )
9558 return false;
9559
9560 // We only need to check if the node evaluation is static, if both - name and value - are static.
9561 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9562 {
9563 QVariant name = args->at( 0 )->eval( parent, context );
9564 QVariant value = args->at( 1 )->eval( parent, context );
9566 // Temporarily append a new scope to provide the variable
9567 appendTemporaryVariable( context, name.toString(), value );
9568 if ( args->at( 2 )->isStatic( parent, context ) )
9569 isStatic = true;
9570 popTemporaryVariable( context );
9571 }
9572
9573 return isStatic;
9574}
9575
9577{
9578 Q_UNUSED( node )
9579 QVariant result;
9580
9581 if ( args->count() < 3 )
9582 // error
9583 return result;
9584
9585 QVariant name = args->at( 0 )->eval( parent, context );
9586 QVariant value = args->at( 1 )->eval( parent, context );
9587
9588 const QgsExpressionContext *updatedContext = context;
9589 std::unique_ptr< QgsExpressionContext > tempContext;
9590 if ( !updatedContext )
9591 {
9592 tempContext = std::make_unique< QgsExpressionContext >();
9593 updatedContext = tempContext.get();
9595
9596 appendTemporaryVariable( updatedContext, name.toString(), value );
9597 result = args->at( 2 )->eval( parent, updatedContext );
9598
9599 if ( context )
9600 popTemporaryVariable( updatedContext );
9601
9602 return result;
9603}
9604
9605QVariant QgsWithVariableExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9607 // This is a dummy function, all the real handling is in run
9608 Q_UNUSED( values )
9609 Q_UNUSED( context )
9610 Q_UNUSED( parent )
9611 Q_UNUSED( node )
9612
9613 Q_ASSERT( false );
9614 return QVariant();
9615}
9616
9618{
9619 QgsExpressionNode::NodeList *args = node->args();
9620
9621 if ( args->count() < 3 )
9622 // error
9623 return false;
9624
9625 QVariant name = args->at( 0 )->prepare( parent, context );
9626 QVariant value = args->at( 1 )->prepare( parent, context );
9627
9628 const QgsExpressionContext *updatedContext = context;
9629 std::unique_ptr< QgsExpressionContext > tempContext;
9630 if ( !updatedContext )
9631 {
9632 tempContext = std::make_unique< QgsExpressionContext >();
9633 updatedContext = tempContext.get();
9634 }
9635
9636 appendTemporaryVariable( updatedContext, name.toString(), value );
9637 args->at( 2 )->prepare( parent, updatedContext );
9638
9639 if ( context )
9640 popTemporaryVariable( updatedContext );
9641
9642 return true;
9643}
9644
9645void QgsWithVariableExpressionFunction::popTemporaryVariable( const QgsExpressionContext *context ) const
9646{
9647 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
9648 delete updatedContext->popScope();
9649}
9650
9651void QgsWithVariableExpressionFunction::appendTemporaryVariable( const QgsExpressionContext *context, const QString &name, const QVariant &value ) const
9652{
9655
9656 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
9657 updatedContext->appendScope( scope );
9658}
@ Left
Buffer to left of line.
DashPatternSizeAdjustment
Dash pattern size adjustment options.
Definition qgis.h:2817
@ ScaleDashOnly
Only dash lengths are adjusted.
@ ScaleBothDashAndGap
Both the dash and gap lengths are adjusted equally.
@ ScaleGapOnly
Only gap lengths are adjusted.
@ Success
Operation succeeded.
@ Visvalingam
The simplification gives each point in a line an importance weighting, so that least important points...
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ Polygon
Polygons.
@ Unknown
Unknown types.
@ Null
No geometry.
JoinStyle
Join styles for buffers.
Definition qgis.h:1791
@ Bevel
Use beveled joins.
@ Round
Use rounded joins.
@ Miter
Use mitered joins.
RasterBandStatistic
Available raster band statistics.
Definition qgis.h:5092
@ StdDev
Standard deviation.
@ NoStatistic
No statistic.
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ Vector
Vector layer.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ Raster
Raster layer.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
EndCapStyle
End cap styles for buffers.
Definition qgis.h:1778
@ Flat
Flat cap (in line with start/end of line)
@ Round
Round cap.
@ Square
Square cap (extends past start/end of line by buffer distance)
Aggregate
Available aggregates to calculate.
Definition qgis.h:4969
@ StringMinimumLength
Minimum length of string (string fields only)
@ FirstQuartile
First quartile (numeric fields only)
@ Mean
Mean of values (numeric fields only)
@ Median
Median of values (numeric fields only)
@ Max
Max of values.
@ Min
Min of values.
@ StringMaximumLength
Maximum length of string (string fields only)
@ Range
Range of values (max - min) (numeric and datetime fields only)
@ StringConcatenateUnique
Concatenate unique values with a joining string (string fields only). Specify the delimiter using set...
@ Sum
Sum of values.
@ Minority
Minority of values.
@ CountMissing
Number of missing (null) values.
@ ArrayAggregate
Create an array of values.
@ Majority
Majority of values.
@ StDevSample
Sample standard deviation of values (numeric fields only)
@ ThirdQuartile
Third quartile (numeric fields only)
@ CountDistinct
Number of distinct values.
@ StringConcatenate
Concatenate values with a joining string (string fields only). Specify the delimiter using setDelimit...
@ GeometryCollect
Create a multipart geometry from aggregated geometries.
@ InterQuartileRange
Inter quartile range (IQR) (numeric fields only)
DashPatternLineEndingRule
Dash pattern line ending rules.
Definition qgis.h:2802
@ HalfDash
Start or finish the pattern with a half length dash.
@ HalfGap
Start or finish the pattern with a half length gap.
@ FullGap
Start or finish the pattern with a full gap.
@ FullDash
Start or finish the pattern with a full dash.
MakeValidMethod
Algorithms to use when repairing invalid geometries.
Definition qgis.h:1817
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
@ Structure
Structured method, first makes all rings valid and then merges shells and subtracts holes from shells...
@ PointM
PointM.
@ PointZ
PointZ.
@ PointZM
PointZM.
Abstract base class for all geometries.
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
virtual QgsAbstractGeometry * boundary() const =0
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
bool isMeasure() const
Returns true if the geometry contains m values.
virtual QgsRectangle boundingBox() const
Returns the minimal bounding box for the geometry.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
virtual bool addMValue(double mValue=0)=0
Adds a measure to the geometry, initialized to a preset value.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
part_iterator parts_end()
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
virtual double length() const
Returns the planar, 2-dimensional length of the geometry.
virtual QgsCoordinateSequence coordinateSequence() const =0
Retrieves the sequence of geometries, rings and nodes.
virtual int partCount() const =0
Returns count of parts contained in the geometry.
part_iterator parts_begin()
Returns STL-style iterator pointing to the first part of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
static Qgis::Aggregate stringToAggregate(const QString &string, bool *ok=nullptr)
Converts a string to a aggregate type.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
Handles the array_filter(array, expression) expression function.
QVariant func(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Returns result of evaluating the function.
bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
This will be called during the prepare step() of an expression if it is not static.
bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
Will be called during prepare to determine if the function is static.
QVariant run(QgsExpressionNode::NodeList *args, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Evaluates the function, first evaluating all required arguments before passing them to the function's...
Handles the array loopingarray_Foreach(array, expression) expression function.
QVariant func(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Returns result of evaluating the function.
bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
Will be called during prepare to determine if the function is static.
QVariant run(QgsExpressionNode::NodeList *args, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Evaluates the function, first evaluating all required arguments before passing them to the function's...
bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
This will be called during the prepare step() of an expression if it is not static.
Circle geometry type.
Definition qgscircle.h:43
Abstract base class for color ramps.
virtual QColor color(double value) const =0
Returns the color corresponding to a specified value.
Format
Available formats for displaying coordinates.
@ FormatDegreesMinutes
Degrees and decimal minutes, eg 30degrees 45.55'.
@ FormatDegreesMinutesSeconds
Degrees, minutes and seconds, eg 30 degrees 45'30".
static QString formatY(double y, Format format, int precision=12, FormatFlags flags=FlagDegreesUseStringSuffix)
Formats a y coordinate value according to the specified parameters.
QFlags< FormatFlag > FormatFlags
@ FlagDegreesUseStringSuffix
Include a direction suffix (eg 'N', 'E', 'S' or 'W'), otherwise a "-" prefix is used for west and sou...
@ FlagDegreesPadMinutesSeconds
Pad minute and second values with leading zeros, eg '05' instead of '5'.
static QString formatX(double x, Format format, int precision=12, FormatFlags flags=FlagDegreesUseStringSuffix)
Formats an x coordinate value according to the specified parameters.
This class represents a coordinate reference system (CRS).
static QgsCoordinateReferenceSystem fromOgcWmsCrs(const QString &ogcCrs)
Creates a CRS from a given OGC WMS-format Coordinate Reference System string.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toProj() const
Returns a Proj string representation of this CRS.
QString ellipsoidAcronym() const
Returns the ellipsoid acronym for the ellipsoid used by the CRS.
Contains information about the context in which a coordinate transform is executed.
Class for doing transforms between two map coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Curve polygon geometry type.
int numInteriorRings() const
Returns the number of interior rings contained with the curve polygon.
const QgsCurve * exteriorRing() const
Returns the curve polygon's exterior ring.
bool isEmpty() const override
Returns true if the geometry is empty.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
double area() const override
Returns the planar, 2-dimensional area of the geometry.
double roundness() const
Returns the roundness of the curve polygon.
int ringCount(int part=0) const override
Returns the number of rings of which this geometry is built.
Abstract base class for curved geometry type.
Definition qgscurve.h:35
double sinuosity() const
Returns the curve sinuosity, which is the ratio of the curve length() to curve straightDistance2d().
Definition qgscurve.cpp:277
QgsCurve * segmentize(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const override
Returns a geometry without curves.
Definition qgscurve.cpp:175
virtual QgsCurve * curveSubstring(double startDistance, double endDistance) const =0
Returns a new curve representing a substring of this curve.
virtual bool isClosed() const
Returns true if the curve is closed.
Definition qgscurve.cpp:53
QgsCurve * clone() const override=0
Clones the geometry by performing a deep copy.
double straightDistance2d() const
Returns the straight distance of the curve, i.e.
Definition qgscurve.cpp:272
virtual QgsCurve * reversed() const =0
Returns a reversed copy of the curve, where the direction of the curve has been flipped.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double measureArea(const QgsGeometry &geometry) const
Measures the area of a geometry.
double convertLengthMeasurement(double length, Qgis::DistanceUnit toUnits) const
Takes a length measurement calculated by this QgsDistanceArea object and converts it to a different d...
double measurePerimeter(const QgsGeometry &geometry) const
Measures the perimeter of a polygon geometry.
double measureLength(const QgsGeometry &geometry) const
Measures the length of a geometry.
double bearing(const QgsPointXY &p1, const QgsPointXY &p2) const
Computes the bearing (in radians) between two points.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
double convertAreaMeasurement(double area, Qgis::AreaUnit toUnits) const
Takes an area measurement calculated by this QgsDistanceArea object and converts it to a different ar...
Holder for the widget type and its configuration for a field.
QVariantMap config() const
Ellipse geometry type.
Definition qgsellipse.h:39
QString what() const
Contains utilities for working with EXIF tags in images.
static QgsPoint getGeoTag(const QString &imagePath, bool &ok)
Returns the geotagged coordinate stored in the image at imagePath.
static QVariant readTag(const QString &imagePath, const QString &key)
Returns the value of of an exif tag key stored in the image at imagePath.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
bool isStatic(const QString &name) const
Tests whether the variable with the specified name is static and can be cached.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
static void registerContextFunctions()
Registers all known core functions provided by QgsExpressionContextScope objects.
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...
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void setCachedValue(const QString &key, const QVariant &value) const
Sets a value to cache within the expression context.
QgsGeometry geometry() const
Convenience function for retrieving the geometry for the context, if set.
QgsFeature feature() const
Convenience function for retrieving the feature for the context, if set.
QgsExpressionContextScope * activeScopeForVariable(const QString &name)
Returns the currently active scope from the context for a specified variable name.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly by the expression to check if evaluation sh...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
bool hasGeometry() const
Returns true if the context has a geometry associated with it.
bool hasCachedValue(const QString &key) const
Returns true if the expression context contains a cached value with a matching key.
QVariant variable(const QString &name) const
Fetches a matching variable from the context.
QVariant cachedValue(const QString &key) const
Returns the matching cached value, if set.
bool hasFeature() const
Returns true if the context has a feature associated with it.
QgsFields fields() const
Convenience function for retrieving the fields for the context, if set.
Represents a single parameter passed to a function.
A abstract base class for defining QgsExpression functions.
QList< QgsExpressionFunction::Parameter > ParameterList
List of parameters, used for function definition.
bool operator==(const QgsExpressionFunction &other) const
virtual bool isDeprecated() const
Returns true if the function is deprecated and should not be presented as a valid option to users in ...
virtual bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const
Will be called during prepare to determine if the function is static.
virtual QStringList aliases() const
Returns a list of possible aliases for the function.
bool lazyEval() const
true if this function should use lazy evaluation.
static bool allParamsStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context)
This will return true if all the params for the provided function node are static within the constrai...
QString name() const
The name of the function.
virtual QVariant run(QgsExpressionNode::NodeList *args, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node)
Evaluates the function, first evaluating all required arguments before passing them to the function's...
virtual QVariant func(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node)=0
Returns result of evaluating the function.
virtual QSet< QString > referencedColumns(const QgsExpressionNodeFunction *node) const
Returns a set of field names which are required for this function.
virtual bool handlesNull() const
Returns true if the function handles NULL values in arguments by itself, and the default NULL value h...
virtual bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const
This will be called during the prepare step() of an expression if it is not static.
virtual bool usesGeometry(const QgsExpressionNodeFunction *node) const
Does this function use a geometry object.
An expression node which takes it value from a feature's field.
QString name() const
The name of the column.
An expression node for expression functions.
QgsExpressionNode::NodeList * args() const
Returns a list of arguments specified for the function.
An expression node for literal values.
A list of expression nodes.
QList< QgsExpressionNode * > list()
Gets a list of all the nodes.
QgsExpressionNode * at(int i)
Gets the node at position i in the list.
int count() const
Returns the number of nodes in the list.
Abstract base class for all nodes that can appear in an expression.
virtual QString dump() const =0
Dump this node into a serialized (part) of an expression.
QVariant eval(QgsExpression *parent, const QgsExpressionContext *context)
Evaluate this node with the given context and parent.
virtual bool isStatic(QgsExpression *parent, const QgsExpressionContext *context) const =0
Returns true if this node can be evaluated for a static value.
bool prepare(QgsExpression *parent, const QgsExpressionContext *context)
Prepare this node for evaluation.
virtual QSet< QString > referencedColumns() const =0
Abstract virtual method which returns a list of columns required to evaluate this node.
virtual QSet< QString > referencedVariables() const =0
Returns a set of all variables which are used in this expression.
A set of expression-related functions.
Class for parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
static const QList< QgsExpressionFunction * > & Functions()
QString expression() const
Returns the original, unmodified expression string.
static void cleanRegisteredFunctions()
Deletes all registered functions whose ownership have been transferred to the expression engine.
Qgis::DistanceUnit distanceUnits() const
Returns the desired distance units for calculations involving geomCalculator(), e....
static bool registerFunction(QgsExpressionFunction *function, bool transferOwnership=false)
Registers a function to the expression engine.
static int functionIndex(const QString &name)
Returns index of the function in Functions array.
static const QStringList & BuiltinFunctions()
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
static PRIVATE QString helpText(QString name)
Returns the help text for a specified function.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QMetaType::Type fieldType=QMetaType::Type::UnknownType)
Create an expression allowing to evaluate if a field is equal to a value.
static bool unregisterFunction(const QString &name)
Unregisters a function from the expression engine.
Qgis::AreaUnit areaUnits() const
Returns the desired areal units for calculations involving geomCalculator(), e.g.,...
void setEvalErrorString(const QString &str)
Sets evaluation error (used internally by evaluation functions)
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
bool needsGeometry() const
Returns true if the expression uses feature geometry for some computation.
QVariant evaluate()
Evaluate the feature and return the result.
QgsDistanceArea * geomCalculator()
Returns calculator used for distance and area calculations (used by $length, $area and $perimeter fun...
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.
The OrderByClause class represents an order by clause for a QgsFeatureRequest.
Represents a list of OrderByClauses, with the most important first and the least important last.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
QgsFeatureRequest & setRequestMayBeNested(bool requestMayBeNested)
In case this request may be run nested within another already running iteration on the same connectio...
QgsFeatureRequest & setTimeout(int timeout)
Sets the timeout (in milliseconds) for the maximum time we should wait during feature requests before...
static const QString ALL_ATTRIBUTES
A special attribute that if set matches all attributes.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
QgsFeatureRequest & setFilterFid(QgsFeatureId fid)
Sets the feature ID that should be fetched.
QgsVectorLayer * materialize(const QgsFeatureRequest &request, QgsFeedback *feedback=nullptr)
Materializes a request (query) made against this feature source, by running it over the source and re...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFields fields
Definition qgsfeature.h:68
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
ConstraintStrength
Strength of constraints.
@ ConstraintStrengthNotSet
Constraint is not set.
@ ConstraintStrengthSoft
User is warned if constraint is violated but feature can still be accepted.
@ ConstraintStrengthHard
Constraint must be honored before feature can be accepted.
QgsFieldFormatter * fieldFormatter(const QString &id) const
Gets a field formatter by its id.
A field formatter helps to handle and display values for a field.
virtual QVariant createCache(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config) const
Create a cache for a given field.
virtual QString representValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const
Create a pretty String representation of the value.
QString name
Definition qgsfield.h:62
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
Definition qgsfield.cpp:739
Container of fields for a vector layer.
Definition qgsfields.h:46
int count
Definition qgsfields.h:50
Q_INVOKABLE int indexFromName(const QString &fieldName) const
Gets the field index from the field name.
int size() const
Returns number of items.
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.
virtual bool removeGeometry(int nr)
Removes a geometry from the collection.
QgsGeometryCollection * createEmptyWithSameType() const override
Creates a new geometry with the same class and same WKB type as the original and transfers ownership.
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
int partCount() const override
Returns count of parts contained in the geometry.
int numGeometries() const
Returns the number of geometries within the collection.
const QgsAbstractGeometry * geometryN(int n) const
Returns a const reference to a geometry from within the collection.
static QVector< QgsLineString * > extractLineStrings(const QgsAbstractGeometry *geom)
Returns list of linestrings extracted from the passed geometry.
A geometry is the spatial representation of a feature.
double hausdorffDistanceDensify(const QgsGeometry &geom, double densifyFraction) const
Returns the Hausdorff distance between this geometry and geom.
QgsGeometry densifyByCount(int extraNodesPerSegment) const
Returns a copy of the geometry which has been densified by adding the specified number of extra nodes...
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
double lineLocatePoint(const QgsGeometry &point) const
Returns a distance representing the location along this linestring of the closest point on this lines...
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
double length() const
Returns the planar, 2-dimensional length of geometry.
QgsGeometry offsetCurve(double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit) const
Returns an offset line at a given distance and side from an input line.
QgsGeometry densifyByDistance(double distance) const
Densifies the geometry by adding regularly placed extra nodes inside each segment so that the maximum...
QgsGeometry poleOfInaccessibility(double precision, double *distanceToBoundary=nullptr) const
Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal ...
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
QgsGeometry squareWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs square waves along the boundary of the geometry, with the specified wavelength and amplitu...
QgsGeometry triangularWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs triangular waves along the boundary of the geometry, with the specified wavelength and amp...
bool vertexIdFromVertexNr(int number, QgsVertexId &id) const
Calculates the vertex ID from a vertex number.
QgsGeometry pointOnSurface() const
Returns a point guaranteed to lie on the surface of a geometry.
bool touches(const QgsGeometry &geometry) const
Returns true if the geometry touches another geometry.
QgsGeometry applyDashPattern(const QVector< double > &pattern, Qgis::DashPatternLineEndingRule startRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternLineEndingRule endRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternSizeAdjustment adjustment=Qgis::DashPatternSizeAdjustment::ScaleBothDashAndGap, double patternOffset=0) const
Applies a dash pattern to a geometry, returning a MultiLineString geometry which is the input geometr...
QgsGeometry roundWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified wavelengt...
QgsGeometry nearestPoint(const QgsGeometry &other) const
Returns the nearest (closest) point on this geometry to another geometry.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
QgsGeometry makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false) const
Attempts to make an invalid geometry valid without losing vertices.
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry combine(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing all the points in this geometry and other (a union geometry operation...
QgsGeometry variableWidthBufferByM(int segments) const
Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is ...
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.
QgsMultiPointXY asMultiPoint() const
Returns the contents of the geometry as a multi-point.
QgsPoint vertexAt(int atVertex) const
Returns coordinates of a vertex.
bool disjoint(const QgsGeometry &geometry) const
Returns true if the geometry is disjoint of another geometry.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
QgsGeometry roundWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized rounded (sine-like) waves along the boundary of the geometry,...
double distance(const QgsGeometry &geom) const
Returns the minimum distance between this geometry and another geometry.
QgsGeometry interpolate(double distance) const
Returns an interpolated point on the geometry at the specified distance.
QgsGeometry extrude(double x, double y)
Returns an extruded version of this geometry.
QgsGeometry singleSidedBuffer(double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle=Qgis::JoinStyle::Round, double miterLimit=2.0) const
Returns a single sided buffer for a (multi)line geometry.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static Q_INVOKABLE QgsGeometry fromWkt(const QString &wkt)
Creates a new geometry from a WKT string.
bool contains(const QgsPointXY *p) const
Returns true if the geometry contains the point p.
QgsGeometry forceRHR() const
Forces geometries to respect the Right-Hand-Rule, in which the area that is bounded by a polygon is t...
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
bool equals(const QgsGeometry &geometry) const
Test if this geometry is exactly equal to another geometry.
bool isGeosValid(Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
Checks validity of the geometry using GEOS.
Qgis::GeometryType type
QgsGeometry taperedBuffer(double startWidth, double endWidth, int segments) const
Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.
bool within(const QgsGeometry &geometry) const
Returns true if the geometry is completely within another geometry.
QgsGeometry orientedMinimumBoundingBox(double &area, double &angle, double &width, double &height) const
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated r...
double area() const
Returns the planar, 2-dimensional area of the geometry.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
bool crosses(const QgsGeometry &geometry) const
Returns true if the geometry crosses another geometry.
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
QgsGeometry concaveHull(double targetPercent, bool allowHoles=false) const
Returns a possibly concave polygon that contains all the points in the geometry.
QgsGeometry convexHull() const
Returns the smallest convex polygon that contains all the points in the geometry.
QgsGeometry sharedPaths(const QgsGeometry &other) const
Find paths shared between the two given lineal geometries (this and other).
void fromWkb(unsigned char *wkb, int length)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
QgsGeometry symDifference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
QgsGeometry minimalEnclosingCircle(QgsPointXY &center, double &radius, unsigned int segments=36) const
Returns the minimal enclosing circle for the geometry.
QgsGeometry mergeLines() const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
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...
double distanceToVertex(int vertex) const
Returns the distance along this geometry from its first vertex to the specified vertex.
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
QgsAbstractGeometry::vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
QgsGeometry forcePolygonClockwise() const
Forces geometries to respect the exterior ring is clockwise, interior rings are counter-clockwise con...
static QgsGeometry createWedgeBuffer(const QgsPoint &center, double azimuth, double angularWidth, double outerRadius, double innerRadius=0)
Creates a wedge shaped buffer from a center point.
QgsGeometry extendLine(double startDistance, double endDistance) const
Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified dista...
QgsGeometry triangularWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelen...
QgsGeometry squareWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized square waves along the boundary of the geometry, with the specified wavelength ...
QgsGeometry simplify(double tolerance) const
Returns a simplified version of this geometry using a specified tolerance value.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::GeometryOperationResult rotate(double rotation, const QgsPointXY &center)
Rotate this geometry around the Z axis.
Qgis::GeometryOperationResult translate(double dx, double dy, double dz=0.0, double dm=0.0)
Translates this geometry by dx, dy, dz and dm.
double interpolateAngle(double distance) const
Returns the angle parallel to the linestring or polygon boundary at the specified distance along the ...
double angleAtVertex(int vertex) const
Returns the bisector angle for this geometry at the specified vertex.
QgsGeometry smooth(unsigned int iterations=1, double offset=0.25, double minimumDistance=-1.0, double maxAngle=180.0) const
Smooths a geometry by rounding off corners using the Chaikin algorithm.
QgsGeometry forcePolygonCounterClockwise() const
Forces geometries to respect the exterior ring is counter-clockwise, interior rings are clockwise con...
Q_INVOKABLE QString asWkt(int precision=17) const
Exports the geometry to WKT.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
bool intersects(const QgsRectangle &rectangle) const
Returns true if this geometry exactly intersects with a rectangle.
QgsAbstractGeometry::vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
bool overlaps(const QgsGeometry &geometry) const
Returns true if the geometry overlaps another geometry.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Does vector analysis using the geos library and handles import, export, exception handling*.
Definition qgsgeos.h:137
std::unique_ptr< QgsAbstractGeometry > maximumInscribedCircle(double tolerance, QString *errorMsg=nullptr) const
Returns the maximum inscribed circle.
Definition qgsgeos.cpp:2679
Gradient color ramp, which smoothly interpolates between two colors and also supports optional extra ...
Represents a color stop within a QgsGradientColorRamp color ramp.
A representation of the interval between two datetime values.
Definition qgsinterval.h:46
bool isValid() const
Returns true if the interval is valid.
double days() const
Returns the interval duration in days.
double weeks() const
Returns the interval duration in weeks.
double months() const
Returns the interval duration in months (based on a 30 day month).
double seconds() const
Returns the interval duration in seconds.
double years() const
Returns the interval duration in years (based on an average year length)
double hours() const
Returns the interval duration in hours.
double minutes() const
Returns the interval duration in minutes.
QStringList rights() const
Returns a list of attribution or copyright strings associated with the resource.
Line string geometry type, with support for z-dimension and m-values.
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
QString dataUrl() const
Returns the DataUrl of the layer used by QGIS Server in GetCapabilities request.
QString attributionUrl() const
Returns the attribution URL of the layer used by QGIS Server in GetCapabilities request.
Base class for all map layer types.
Definition qgsmaplayer.h:75
QString name
Definition qgsmaplayer.h:79
virtual QgsRectangle extent() const
Returns the extent of the layer.
QString source() const
Returns the source for the layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:82
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
QString id
Definition qgsmaplayer.h:78
QgsLayerMetadata metadata
Definition qgsmaplayer.h:81
Qgis::LayerType type
Definition qgsmaplayer.h:85
QString publicSource(bool hidePassword=false) const
Gets a version of the internal layer definition that has sensitive bits removed (for example,...
virtual bool isEditable() const
Returns true if the layer can be edited.
double minimumScale() const
Returns the minimum map scale (i.e.
virtual Q_INVOKABLE QgsDataProvider * dataProvider()
Returns the layer's data provider, it may be nullptr.
double maximumScale() const
Returns the maximum map scale (i.e.
QString mapTipTemplate
Definition qgsmaplayer.h:88
Implementation of GeometrySimplifier using the "MapToPixel" algorithm.
@ SimplifyGeometry
The geometries can be simplified using the current map2pixel context state.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Multi line string geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi point geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Custom exception class which is raised when an operation is not supported.
static QgsGeometry geometryFromGML(const QString &xmlString, const QgsOgcUtils::Context &context=QgsOgcUtils::Context())
Static method that creates geometry from GML.
A class to represent a 2D point.
Definition qgspointxy.h:60
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
bool isEmpty() const
Returns true if the geometry is empty.
Definition qgspointxy.h:243
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
double inclination(const QgsPoint &other) const
Calculates Cartesian inclination between this point and other one (starting from zenith = 0 to nadir ...
Definition qgspoint.cpp:693
bool isValid(QString &error, Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const override
Checks validity of the geometry, and returns true if the geometry is valid.
Definition qgspoint.cpp:425
double z
Definition qgspoint.h:54
double x
Definition qgspoint.h:52
double m
Definition qgspoint.h:55
QgsPoint project(double distance, double azimuth, double inclination=90.0) const
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition qgspoint.cpp:705
double y
Definition qgspoint.h:53
QgsRelationManager * relationManager
Definition qgsproject.h:117
static QgsProject * instance()
Returns the QgsProject singleton instance.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
Quadrilateral geometry type.
static QgsQuadrilateral squareFromDiagonal(const QgsPoint &p1, const QgsPoint &p2)
Construct a QgsQuadrilateral as a square from a diagonal.
QgsPolygon * toPolygon(bool force2D=false) const
Returns the quadrilateral as a new polygon.
static QgsQuadrilateral rectangleFrom3Points(const QgsPoint &p1, const QgsPoint &p2, const QgsPoint &p3, ConstructionOption mode)
Construct a QgsQuadrilateral as a Rectangle from 3 points.
ConstructionOption
A quadrilateral can be constructed from 3 points where the second distance can be determined by the t...
@ Distance
Second distance is equal to the distance between 2nd and 3rd point.
@ Projected
Second distance is equal to the distance of the perpendicular projection of the 3rd point on the segm...
The Field class represents a Raster Attribute Table field, including its name, usage and type.
The RasterBandStats struct is a container for statistics about a single raster band.
double mean
The mean cell value for the band. NO_DATA values are excluded.
double stdDev
The standard deviation of the cell values.
double minimumValue
The minimum cell value in the raster band.
double sum
The sum of all cells in the band. NO_DATA values are excluded.
double maximumValue
The maximum cell value in the raster band.
double range
The range is the distance between min & max.
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double width() const
Returns the width of the rectangle.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
QgsPointXY center() const
Returns the center point of the rectangle.
void grow(double delta)
Grows the rectangle in place by the specified amount.
double height() const
Returns the height of the rectangle.
Regular Polygon geometry type.
ConstructionOption
A regular polygon can be constructed inscribed in a circle or circumscribed about a circle.
@ CircumscribedCircle
Circumscribed about a circle (the radius is the distance from the center to the midpoints of the side...
@ InscribedCircle
Inscribed in a circle (the radius is the distance between the center and vertices)
QgsPolygon * toPolygon() const
Returns as a polygon.
QList< QgsRelation > relationsByName(const QString &name) const
Returns a list of relations with matching names.
Q_INVOKABLE QgsRelation relation(const QString &id) const
Gets access to a relation by its id.
QgsVectorLayer * referencedLayer
Definition qgsrelation.h:47
QgsVectorLayer * referencingLayer
Definition qgsrelation.h:46
QString getRelatedFeaturesFilter(const QgsFeature &feature) const
Returns a filter expression which returns all the features on the referencing (child) layer which hav...
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
QList< QgsFeatureId > nearestNeighbor(const QgsPointXY &point, int neighbors=1, double maxDistance=0) const
Returns nearest neighbors to a point.
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
static QString quotedIdentifier(const QString &identifier)
Returns a properly quoted version of identifier.
static QString quotedValue(const QVariant &value)
Returns a properly quoted and escaped version of value for use in SQL strings.
c++ helper class for defining QgsExpression functions.
bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
This will be called during the prepare step() of an expression if it is not static.
void setIsStaticFunction(const std::function< bool(const QgsExpressionNodeFunction *, QgsExpression *, const QgsExpressionContext *) > &isStatic)
Set a function that will be called in the prepare step to determine if the function is static or not.
QStringList aliases() const override
Returns a list of possible aliases for the function.
void setPrepareFunction(const std::function< bool(const QgsExpressionNodeFunction *, QgsExpression *, const QgsExpressionContext *)> &prepareFunc)
Set a function that will be called in the prepare step to determine if the function is static or not.
void setUsesGeometryFunction(const std::function< bool(const QgsExpressionNodeFunction *node)> &usesGeometry)
Set a function that will be called when determining if the function requires feature geometry or not.
bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
Will be called during prepare to determine if the function is static.
void setIsStatic(bool isStatic)
Tag this function as either static or not static.
QgsStaticExpressionFunction(const QString &fnname, int params, FcnEval fcn, const QString &group, const QString &helpText=QString(), bool usesGeometry=false, const QSet< QString > &referencedColumns=QSet< QString >(), bool lazyEval=false, const QStringList &aliases=QStringList(), bool handlesNull=false)
Static function for evaluation against a QgsExpressionContext, using an unnamed list of parameter val...
QSet< QString > referencedColumns(const QgsExpressionNodeFunction *node) const override
Returns a set of field names which are required for this function.
bool usesGeometry(const QgsExpressionNodeFunction *node) const override
Does this function use a geometry object.
Utility functions for working with strings.
static int hammingDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Hamming distance between two strings.
static QString soundex(const QString &string)
Returns the Soundex representation of a string.
static int levenshteinDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Levenshtein edit distance between two strings.
static QString longestCommonSubstring(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the longest common substring between two strings.
static QString wordWrap(const QString &string, int length, bool useMaxLineLength=true, const QString &customDelimiter=QString())
Automatically wraps a string by inserting new line characters at appropriate locations in the string.
const QgsColorRamp * colorRampRef(const QString &name) const
Returns a const pointer to a symbol (doesn't create new instance)
Definition qgsstyle.cpp:500
static QgsStyle * defaultStyle(bool initialize=true)
Returns the default application-wide style.
Definition qgsstyle.cpp:145
static QColor decodeColor(const QString &str)
static QString encodeColor(const QColor &color)
static bool runOnMainThread(const Func &func, QgsFeedback *feedback=nullptr)
Guarantees that func is executed on the main thread.
This class allows including a set of layers in a database-side transaction, provided the layer data p...
virtual bool executeSql(const QString &sql, QString &error, bool isDirty=false, const QString &name=QString())=0
Execute the sql string.
Triangle geometry type.
Definition qgstriangle.h:33
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
virtual QgsTransaction * transaction() const
Returns the transaction this data provider is included in, if any.
static bool validateAttribute(const QgsVectorLayer *layer, const QgsFeature &feature, int attributeIndex, QStringList &errors, QgsFieldConstraints::ConstraintStrength strength=QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin=QgsFieldConstraints::ConstraintOriginNotSet)
Tests a feature attribute value to check whether it passes all constraints which are present on the c...
Represents a vector layer which manages a vector based data sets.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QVariant aggregate(Qgis::Aggregate aggregate, const QString &fieldOrExpression, const QgsAggregateCalculator::AggregateParameters &parameters=QgsAggregateCalculator::AggregateParameters(), QgsExpressionContext *context=nullptr, bool *ok=nullptr, QgsFeatureIds *fids=nullptr, QgsFeedback *feedback=nullptr, QString *error=nullptr) const
Calculates an aggregated value from the layer's features.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
QString displayExpression
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
QgsEditorWidgetSetup editorWidgetSetup(int index) const
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
Q_INVOKABLE QgsFeature getFeature(QgsFeatureId fid) const
Queries the layer for the feature with the given id.
Handles the with_variable(name, value, node) expression function.
bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
Will be called during prepare to determine if the function is static.
QVariant run(QgsExpressionNode::NodeList *args, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Evaluates the function, first evaluating all required arguments before passing them to the function's...
QVariant func(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node) override
Returns result of evaluating the function.
bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const override
This will be called during the prepare step() of an expression if it is not static.
static QString geometryDisplayString(Qgis::GeometryType type)
Returns a display string for a geometry type.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
Unique pointer for sqlite3 databases, which automatically closes the database when the pointer goes o...
sqlite3_statement_unique_ptr prepare(const QString &sql, int &resultCode) const
Prepares a sql statement, returning the result.
QString errorMessage() const
Returns the most recent error message encountered by the database.
int open_v2(const QString &path, int flags, const char *zVfs)
Opens the database at the specified file path.
int exec(const QString &sql, QString &errorMessage) const
Executes the sql command in the database.
Unique pointer for sqlite3 prepared statements, which automatically finalizes the statement when the ...
int step()
Steps to the next record in the statement, returning the sqlite3 result code.
qlonglong columnAsInt64(int column) const
Gets column value from the current statement row as a long long integer (64 bits).
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
CORE_EXPORT QString build(const QVariantMap &map)
Build a hstore-formatted string from a QVariantMap.
CORE_EXPORT QVariantMap parse(const QString &string)
Returns a QVariantMap object containing the key and values from a hstore-formatted string.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
uint qHash(const QVariant &variant)
Hash for QVariant.
Definition qgis.cpp:198
#define str(x)
Definition qgis.cpp:38
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition qgis.cpp:120
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6042
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6041
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
Definition qgis.h:5506
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5465
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
QList< QgsGradientStop > QgsGradientStopsList
List of gradient stops.
Q_DECLARE_METATYPE(QgsDatabaseQueryLogEntry)
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
QList< QgsExpressionFunction * > ExpressionFunctionList
#define ENSURE_GEOM_TYPE(f, g, geomtype)
QVariant fcnRampColor(const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction *)
bool(QgsGeometry::* RelationFunction)(const QgsGeometry &geometry) const
#define ENSURE_NO_EVAL_ERROR
#define FEAT_FROM_CONTEXT(c, f)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:80
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
QLineF segment(int index, QRectF rect, double radius)
int precision
A bundle of parameters controlling aggregate calculation.
QString filter
Optional filter for calculating aggregate over a subset of features, or an empty string to use all fe...
QString delimiter
Delimiter to use for joining values with the StringConcatenate aggregate.
QgsFeatureRequest::OrderBy orderBy
Optional order by clauses.
Single variable definition for use within a QgsExpressionContextScope.
The Context struct stores the current layer and coordinate transform context.
Definition qgsogcutils.h:62
const QgsMapLayer * layer
Definition qgsogcutils.h:72
QgsCoordinateTransformContext transformContext
Definition qgsogcutils.h:73
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30