QGIS API Documentation 3.41.0-Master (88383c3d16f)
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
6 email : matthias@opengis.ch
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16
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 const QSet< QString > filterVars = filterExp.referencedVariables();
718 const QSet< QString > subExpVars = subExp.referencedVariables();
719 QSet<QString> allVars = filterVars + subExpVars;
720
721 bool isStatic = true;
722 if ( filterVars.contains( QStringLiteral( "parent" ) )
723 || filterVars.contains( QString() )
724 || subExpVars.contains( QStringLiteral( "parent" ) )
725 || subExpVars.contains( QString() ) )
726 {
727 isStatic = false;
728 }
729 else
730 {
731 for ( const QString &varName : allVars )
732 {
733 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
734 if ( scope && !scope->isStatic( varName ) )
735 {
736 isStatic = false;
737 break;
738 }
739 }
740 }
741
742 if ( isStatic && ! parameters.orderBy.isEmpty() )
743 {
744 for ( const auto &orderByClause : std::as_const( parameters.orderBy ) )
745 {
746 const QgsExpression &orderByExpression { orderByClause.expression() };
747 if ( orderByExpression.referencedVariables().contains( QStringLiteral( "parent" ) ) || orderByExpression.referencedVariables().contains( QString() ) )
748 {
749 isStatic = false;
750 break;
751 }
752 }
753 }
754
755 if ( !isStatic )
756 {
757 bool ok = false;
758 const QString contextHash = context->uniqueHash( ok, allVars );
759 if ( ok )
760 {
761 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5:%6" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter,
762 orderBy, contextHash );
763 }
764 }
765 else
766 {
767 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter, orderBy );
768 }
769
770 if ( !cacheKey.isEmpty() && context->hasCachedValue( cacheKey ) )
771 {
772 return context->cachedValue( cacheKey );
773 }
774
775 QgsExpressionContext subContext( *context );
777 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
778 subContext.appendScope( subScope );
779 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &aggregateError );
780
781 if ( ok && !cacheKey.isEmpty() )
782 {
783 // important -- we should only store cached values when the expression is successfully calculated. Otherwise subsequent
784 // use of the expression context will happily grab the invalid QVariant cached value without realising that there was actually an error
785 // associated with it's calculation!
786 context->setCachedValue( cacheKey, result );
787 }
788 }
789 else
790 {
791 result = vl->aggregate( aggregate, subExpression, parameters, nullptr, &ok, nullptr, nullptr, &aggregateError );
792 }
793 if ( !ok )
794 {
795 if ( !aggregateError.isEmpty() )
796 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, aggregateError ) );
797 else
798 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
799 return QVariant();
800 }
801
802 return result;
803}
804
805static QVariant fcnAggregateRelation( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
806{
807 if ( !context )
808 {
809 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
810 return QVariant();
811 }
812
813 // first step - find current layer
814
815 // TODO this expression function is NOT thread safe
817 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
819 if ( !vl )
820 {
821 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
822 return QVariant();
823 }
824
825 //lazy eval, so we need to evaluate nodes now
826
827 //first node is relation name
828 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
830 QVariant value = node->eval( parent, context );
832 QString relationId = value.toString();
833 // check relation exists
834 QgsRelation relation = QgsProject::instance()->relationManager()->relation( relationId ); // skip-keyword-check
835 if ( !relation.isValid() || relation.referencedLayer() != vl )
836 {
837 // check for relations by name
838 QList< QgsRelation > relations = QgsProject::instance()->relationManager()->relationsByName( relationId ); // skip-keyword-check
839 if ( relations.isEmpty() || relations.at( 0 ).referencedLayer() != vl )
840 {
841 parent->setEvalErrorString( QObject::tr( "Cannot find relation with id '%1'" ).arg( relationId ) );
842 return QVariant();
843 }
844 else
845 {
846 relation = relations.at( 0 );
847 }
848 }
849
850 QgsVectorLayer *childLayer = relation.referencingLayer();
851
852 // second node is aggregate type
853 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
855 value = node->eval( parent, context );
857 bool ok = false;
858 Qgis::Aggregate aggregate = QgsAggregateCalculator::stringToAggregate( QgsExpressionUtils::getStringValue( value, parent ), &ok );
859 if ( !ok )
860 {
861 parent->setEvalErrorString( QObject::tr( "No such aggregate '%1'" ).arg( value.toString() ) );
862 return QVariant();
863 }
864
865 //third node is subexpression (or field name)
866 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
868 QString subExpression = node->dump();
869
870 //optional fourth node is concatenator
872 if ( values.count() > 3 )
873 {
874 node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
876 value = node->eval( parent, context );
878 parameters.delimiter = value.toString();
879 }
880
881 //optional fifth node is order by
882 QString orderBy;
883 if ( values.count() > 4 )
884 {
885 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
887 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
888 if ( !nl || nl->value().isValid() )
889 {
890 orderBy = node->dump();
891 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
892 }
893 }
894
895 if ( !context->hasFeature() )
896 return QVariant();
897 QgsFeature f = context->feature();
898
899 parameters.filter = relation.getRelatedFeaturesFilter( f );
900
901 const QString cacheKey = QStringLiteral( "relagg:%1%:%2:%3:%4:%5:%6" ).arg( relationId, vl->id(),
902 QString::number( static_cast< int >( aggregate ) ),
903 subExpression,
904 parameters.filter,
905 orderBy );
906 if ( context->hasCachedValue( cacheKey ) )
907 return context->cachedValue( cacheKey );
908
909 QVariant result;
910 ok = false;
911
912
913 QgsExpressionContext subContext( *context );
914 QString error;
915 result = childLayer->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
916
917 if ( !ok )
918 {
919 if ( !error.isEmpty() )
920 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
921 else
922 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
923 return QVariant();
924 }
925
926 // cache value
927 context->setCachedValue( cacheKey, result );
928 return result;
929}
930
931
932static QVariant fcnAggregateGeneric( Qgis::Aggregate aggregate, const QVariantList &values, QgsAggregateCalculator::AggregateParameters parameters, const QgsExpressionContext *context, QgsExpression *parent, int orderByPos = -1 )
933{
934 if ( !context )
935 {
936 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
937 return QVariant();
938 }
939
940 // first step - find current layer
941
942 // TODO this expression function is NOT thread safe
944 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
946 if ( !vl )
947 {
948 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
949 return QVariant();
950 }
951
952 //lazy eval, so we need to evaluate nodes now
953
954 //first node is subexpression (or field name)
955 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
957 QString subExpression = node->dump();
958
959 //optional second node is group by
960 QString groupBy;
961 if ( values.count() > 1 )
962 {
963 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
965 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
966 if ( !nl || nl->value().isValid() )
967 groupBy = node->dump();
968 }
969
970 //optional third node is filter
971 if ( values.count() > 2 )
972 {
973 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
975 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
976 if ( !nl || nl->value().isValid() )
977 parameters.filter = node->dump();
978 }
979
980 //optional order by node, if supported
981 QString orderBy;
982 if ( orderByPos >= 0 && values.count() > orderByPos )
983 {
984 node = QgsExpressionUtils::getNode( values.at( orderByPos ), parent );
986 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
987 if ( !nl || nl->value().isValid() )
988 {
989 orderBy = node->dump();
990 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
991 }
992 }
993
994 // build up filter with group by
995
996 // find current group by value
997 if ( !groupBy.isEmpty() )
998 {
999 QgsExpression groupByExp( groupBy );
1000 QVariant groupByValue = groupByExp.evaluate( context );
1001 QString groupByClause = QStringLiteral( "%1 %2 %3" ).arg( groupBy,
1002 QgsVariantUtils::isNull( groupByValue ) ? QStringLiteral( "is" ) : QStringLiteral( "=" ),
1003 QgsExpression::quotedValue( groupByValue ) );
1004 if ( !parameters.filter.isEmpty() )
1005 parameters.filter = QStringLiteral( "(%1) AND (%2)" ).arg( parameters.filter, groupByClause );
1006 else
1007 parameters.filter = groupByClause;
1008 }
1009
1010 QgsExpression subExp( subExpression );
1011 QgsExpression filterExp( parameters.filter );
1012
1013 bool isStatic = true;
1014 const QSet<QString> refVars = filterExp.referencedVariables() + subExp.referencedVariables();
1015 for ( const QString &varName : refVars )
1016 {
1017 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
1018 if ( scope && !scope->isStatic( varName ) )
1019 {
1020 isStatic = false;
1021 break;
1022 }
1023 }
1024
1025 QString cacheKey;
1026 if ( !isStatic )
1027 {
1028 bool ok = false;
1029 const QString contextHash = context->uniqueHash( ok, refVars );
1030 if ( ok )
1031 {
1032 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5:%6" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter,
1033 orderBy, contextHash );
1034 }
1035 }
1036 else
1037 {
1038 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter, orderBy );
1039 }
1040
1041 if ( context->hasCachedValue( cacheKey ) )
1042 return context->cachedValue( cacheKey );
1043
1044 QVariant result;
1045 bool ok = false;
1046
1047 QgsExpressionContext subContext( *context );
1049 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
1050 subContext.appendScope( subScope );
1051 QString error;
1052 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
1053
1054 if ( !ok )
1055 {
1056 if ( !error.isEmpty() )
1057 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
1058 else
1059 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
1060 return QVariant();
1061 }
1062
1063 // cache value
1064 context->setCachedValue( cacheKey, result );
1065 return result;
1066}
1067
1068
1069static QVariant fcnAggregateCount( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1070{
1071 return fcnAggregateGeneric( Qgis::Aggregate::Count, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1072}
1073
1074static QVariant fcnAggregateCountDistinct( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1075{
1076 return fcnAggregateGeneric( Qgis::Aggregate::CountDistinct, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1077}
1078
1079static QVariant fcnAggregateCountMissing( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1080{
1081 return fcnAggregateGeneric( Qgis::Aggregate::CountMissing, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1082}
1083
1084static QVariant fcnAggregateMin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1085{
1086 return fcnAggregateGeneric( Qgis::Aggregate::Min, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1087}
1088
1089static QVariant fcnAggregateMax( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1090{
1091 return fcnAggregateGeneric( Qgis::Aggregate::Max, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1092}
1093
1094static QVariant fcnAggregateSum( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1095{
1096 return fcnAggregateGeneric( Qgis::Aggregate::Sum, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1097}
1098
1099static QVariant fcnAggregateMean( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1100{
1101 return fcnAggregateGeneric( Qgis::Aggregate::Mean, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1102}
1103
1104static QVariant fcnAggregateMedian( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1105{
1106 return fcnAggregateGeneric( Qgis::Aggregate::Median, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1107}
1108
1109static QVariant fcnAggregateStdev( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1110{
1111 return fcnAggregateGeneric( Qgis::Aggregate::StDevSample, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1112}
1113
1114static QVariant fcnAggregateRange( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1115{
1116 return fcnAggregateGeneric( Qgis::Aggregate::Range, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1117}
1118
1119static QVariant fcnAggregateMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1120{
1121 return fcnAggregateGeneric( Qgis::Aggregate::Minority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1122}
1123
1124static QVariant fcnAggregateMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1125{
1126 return fcnAggregateGeneric( Qgis::Aggregate::Majority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1127}
1128
1129static QVariant fcnAggregateQ1( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1130{
1131 return fcnAggregateGeneric( Qgis::Aggregate::FirstQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1132}
1133
1134static QVariant fcnAggregateQ3( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1135{
1136 return fcnAggregateGeneric( Qgis::Aggregate::ThirdQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1137}
1138
1139static QVariant fcnAggregateIQR( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1140{
1141 return fcnAggregateGeneric( Qgis::Aggregate::InterQuartileRange, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1142}
1143
1144static QVariant fcnAggregateMinLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1145{
1146 return fcnAggregateGeneric( Qgis::Aggregate::StringMinimumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1147}
1148
1149static QVariant fcnAggregateMaxLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1150{
1151 return fcnAggregateGeneric( Qgis::Aggregate::StringMaximumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1152}
1153
1154static QVariant fcnAggregateCollectGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1155{
1156 return fcnAggregateGeneric( Qgis::Aggregate::GeometryCollect, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1157}
1158
1159static QVariant fcnAggregateStringConcat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1160{
1162
1163 //fourth node is concatenator
1164 if ( values.count() > 3 )
1165 {
1166 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1168 QVariant value = node->eval( parent, context );
1170 parameters.delimiter = value.toString();
1171 }
1172
1173 return fcnAggregateGeneric( Qgis::Aggregate::StringConcatenate, values, parameters, context, parent, 4 );
1174}
1175
1176static QVariant fcnAggregateStringConcatUnique( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1177{
1179
1180 //fourth node is concatenator
1181 if ( values.count() > 3 )
1182 {
1183 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1185 QVariant value = node->eval( parent, context );
1187 parameters.delimiter = value.toString();
1188 }
1189
1190 return fcnAggregateGeneric( Qgis::Aggregate::StringConcatenateUnique, values, parameters, context, parent, 4 );
1191}
1192
1193static QVariant fcnAggregateArray( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1194{
1195 return fcnAggregateGeneric( Qgis::Aggregate::ArrayAggregate, values, QgsAggregateCalculator::AggregateParameters(), context, parent, 3 );
1196}
1197
1198static QVariant fcnMapScale( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1199{
1200 if ( !context )
1201 return QVariant();
1202
1203 QVariant scale = context->variable( QStringLiteral( "map_scale" ) );
1204 bool ok = false;
1205 if ( QgsVariantUtils::isNull( scale ) )
1206 return QVariant();
1207
1208 const double v = scale.toDouble( &ok );
1209 if ( ok )
1210 return v;
1211 return QVariant();
1212}
1213
1214static QVariant fcnClamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1215{
1216 double minValue = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1217 double testValue = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1218 double maxValue = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1219
1220 // force testValue to sit inside the range specified by the min and max value
1221 if ( testValue <= minValue )
1222 {
1223 return QVariant( minValue );
1224 }
1225 else if ( testValue >= maxValue )
1226 {
1227 return QVariant( maxValue );
1228 }
1229 else
1230 {
1231 return QVariant( testValue );
1232 }
1233}
1234
1235static QVariant fcnFloor( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1236{
1237 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1238 return QVariant( std::floor( x ) );
1239}
1240
1241static QVariant fcnCeil( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1242{
1243 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1244 return QVariant( std::ceil( x ) );
1245}
1246
1247static QVariant fcnToBool( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1248{
1249 const QVariant value = values.at( 0 );
1250 if ( QgsExpressionUtils::isNull( value.isValid() ) )
1251 {
1252 return QVariant( false );
1253 }
1254 else if ( value.userType() == QMetaType::QString )
1255 {
1256 // Capture strings to avoid a '0' string value casted to 0 and wrongly returning false
1257 return QVariant( !value.toString().isEmpty() );
1258 }
1259 else if ( QgsExpressionUtils::isList( value ) )
1260 {
1261 return !value.toList().isEmpty();
1262 }
1263 return QVariant( value.toBool() );
1264}
1265static QVariant fcnToInt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1266{
1267 return QVariant( QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) );
1268}
1269static QVariant fcnToReal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1270{
1271 return QVariant( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) );
1272}
1273static QVariant fcnToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1274{
1275 return QVariant( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ) );
1276}
1277
1278static QVariant fcnToDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1279{
1280 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1281 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1282 if ( format.isEmpty() && !language.isEmpty() )
1283 {
1284 parent->setEvalErrorString( QObject::tr( "A format is required to convert to DateTime when the language is specified" ) );
1285 return QVariant( QDateTime() );
1286 }
1287
1288 if ( format.isEmpty() && language.isEmpty() )
1289 return QVariant( QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent ) );
1290
1291 QString datetimestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1292 QLocale locale = QLocale();
1293 if ( !language.isEmpty() )
1294 {
1295 locale = QLocale( language );
1296 }
1297
1298 QDateTime datetime = locale.toDateTime( datetimestring, format );
1299 if ( !datetime.isValid() )
1300 {
1301 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to DateTime" ).arg( datetimestring ) );
1302 datetime = QDateTime();
1303 }
1304 return QVariant( datetime );
1305}
1306
1307static QVariant fcnMakeDate( 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
1313 const QDate date( year, month, day );
1314 if ( !date.isValid() )
1315 {
1316 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1317 return QVariant();
1318 }
1319 return QVariant( date );
1320}
1321
1322static QVariant fcnMakeTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1323{
1324 const int hours = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1325 const int minutes = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1326 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1327
1328 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1329 if ( !time.isValid() )
1330 {
1331 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1332 return QVariant();
1333 }
1334 return QVariant( time );
1335}
1336
1337static QVariant fcnMakeDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1338{
1339 const int year = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1340 const int month = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1341 const int day = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
1342 const int hours = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
1343 const int minutes = QgsExpressionUtils::getIntValue( values.at( 4 ), parent );
1344 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1345
1346 const QDate date( year, month, day );
1347 if ( !date.isValid() )
1348 {
1349 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1350 return QVariant();
1351 }
1352 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1353 if ( !time.isValid() )
1354 {
1355 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1356 return QVariant();
1357 }
1358 return QVariant( QDateTime( date, time ) );
1359}
1360
1361static QVariant fcnMakeInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1362{
1363 const double years = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1364 const double months = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1365 const double weeks = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1366 const double days = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
1367 const double hours = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
1368 const double minutes = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1369 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
1370
1371 return QVariant::fromValue( QgsInterval( years, months, weeks, days, hours, minutes, seconds ) );
1372}
1373
1374static QVariant fcnCoalesce( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1375{
1376 for ( const QVariant &value : values )
1377 {
1378 if ( QgsVariantUtils::isNull( value ) )
1379 continue;
1380 return value;
1381 }
1382 return QVariant();
1383}
1384
1385static QVariant fcnNullIf( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1386{
1387 const QVariant val1 = values.at( 0 );
1388 const QVariant val2 = values.at( 1 );
1389
1390 if ( val1 == val2 )
1391 return QVariant();
1392 else
1393 return val1;
1394}
1395
1396static QVariant fcnLower( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1397{
1398 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1399 return QVariant( str.toLower() );
1400}
1401static QVariant fcnUpper( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1402{
1403 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1404 return QVariant( str.toUpper() );
1405}
1406static QVariant fcnTitle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1407{
1408 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1409 QStringList elems = str.split( ' ' );
1410 for ( int i = 0; i < elems.size(); i++ )
1411 {
1412 if ( elems[i].size() > 1 )
1413 elems[i] = elems[i].at( 0 ).toUpper() + elems[i].mid( 1 ).toLower();
1414 }
1415 return QVariant( elems.join( QLatin1Char( ' ' ) ) );
1416}
1417
1418static QVariant fcnTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1419{
1420 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1421 return QVariant( str.trimmed() );
1422}
1423
1424static QVariant fcnLTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1425{
1426 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1427
1428 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1429
1430 const QRegularExpression re( QStringLiteral( "^([%1]*)" ).arg( QRegularExpression::escape( characters ) ) );
1431 str.replace( re, QString() );
1432 return QVariant( str );
1433}
1434
1435static QVariant fcnRTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1436{
1437 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1438
1439 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1440
1441 const QRegularExpression re( QStringLiteral( "([%1]*)$" ).arg( QRegularExpression::escape( characters ) ) );
1442 str.replace( re, QString() );
1443 return QVariant( str );
1444}
1445
1446static QVariant fcnLevenshtein( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1447{
1448 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1449 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1450 return QVariant( QgsStringUtils::levenshteinDistance( string1, string2, true ) );
1451}
1452
1453static QVariant fcnLCS( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1454{
1455 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1456 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1457 return QVariant( QgsStringUtils::longestCommonSubstring( string1, string2, true ) );
1458}
1459
1460static QVariant fcnHamming( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1461{
1462 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1463 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1464 int dist = QgsStringUtils::hammingDistance( string1, string2 );
1465 return ( dist < 0 ? QVariant() : QVariant( QgsStringUtils::hammingDistance( string1, string2, true ) ) );
1466}
1467
1468static QVariant fcnSoundex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1469{
1470 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1471 return QVariant( QgsStringUtils::soundex( string ) );
1472}
1473
1474static QVariant fcnChar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1475{
1476 QChar character = QChar( QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent ) );
1477 return QVariant( QString( character ) );
1478}
1479
1480static QVariant fcnAscii( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1481{
1482 QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1483
1484 if ( value.isEmpty() )
1485 {
1486 return QVariant();
1487 }
1488
1489 int res = value.at( 0 ).unicode();
1490 return QVariant( res );
1491}
1492
1493static QVariant fcnWordwrap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1494{
1495 if ( values.length() == 2 || values.length() == 3 )
1496 {
1497 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1498 qlonglong wrap = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1499
1500 QString customdelimiter = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1501
1502 return QgsStringUtils::wordWrap( str, static_cast< int >( wrap ), wrap > 0, customdelimiter );
1503 }
1504
1505 return QVariant();
1506}
1507
1508static QVariant fcnLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1509{
1510 // two variants, one for geometry, one for string
1511
1512 //geometry variant
1513 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent, true );
1514 if ( !geom.isNull() )
1515 {
1516 if ( geom.type() == Qgis::GeometryType::Line )
1517 return QVariant( geom.length() );
1518 else
1519 return QVariant();
1520 }
1521
1522 //otherwise fall back to string variant
1523 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1524 return QVariant( str.length() );
1525}
1526
1527static QVariant fcnLength3D( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1528{
1529 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
1530
1531 if ( geom.type() != Qgis::GeometryType::Line )
1532 return QVariant();
1533
1534 double totalLength = 0;
1535 for ( auto it = geom.const_parts_begin(); it != geom.const_parts_end(); ++it )
1536 {
1537 if ( const QgsLineString *line = qgsgeometry_cast< const QgsLineString * >( *it ) )
1538 {
1539 totalLength += line->length3D();
1540 }
1541 else
1542 {
1543 std::unique_ptr< QgsLineString > segmentized( qgsgeometry_cast< const QgsCurve * >( *it )->curveToLine() );
1544 totalLength += segmentized->length3D();
1545 }
1546 }
1547
1548 return totalLength;
1549}
1550
1551static QVariant fcnReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1552{
1553 if ( values.count() == 2 && values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
1554 {
1555 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1556 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
1557 QVector< QPair< QString, QString > > mapItems;
1558
1559 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
1560 {
1561 mapItems.append( qMakePair( it.key(), it.value().toString() ) );
1562 }
1563
1564 // larger keys should be replaced first since they may contain whole smaller keys
1565 std::sort( mapItems.begin(),
1566 mapItems.end(),
1567 []( const QPair< QString, QString > &pair1,
1568 const QPair< QString, QString > &pair2 )
1569 {
1570 return ( pair1.first.length() > pair2.first.length() );
1571 } );
1572
1573 for ( auto it = mapItems.constBegin(); it != mapItems.constEnd(); ++it )
1574 {
1575 str = str.replace( it->first, it->second );
1576 }
1577
1578 return QVariant( str );
1579 }
1580 else if ( values.count() == 3 )
1581 {
1582 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1583 QVariantList before;
1584 QVariantList after;
1585 bool isSingleReplacement = false;
1586
1587 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).userType() != QMetaType::Type::QStringList )
1588 {
1589 before = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1590 }
1591 else
1592 {
1593 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
1594 }
1595
1596 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
1597 {
1598 after = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1599 isSingleReplacement = true;
1600 }
1601 else
1602 {
1603 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
1604 }
1605
1606 if ( !isSingleReplacement && before.length() != after.length() )
1607 {
1608 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
1609 return QVariant();
1610 }
1611
1612 for ( int i = 0; i < before.length(); i++ )
1613 {
1614 str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() );
1615 }
1616
1617 return QVariant( str );
1618 }
1619 else
1620 {
1621 parent->setEvalErrorString( QObject::tr( "Function replace requires 2 or 3 arguments" ) );
1622 return QVariant();
1623 }
1624}
1625
1626static QVariant fcnRegexpReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1627{
1628 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1629 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1630 QString after = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1631
1632 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1633 if ( !re.isValid() )
1634 {
1635 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1636 return QVariant();
1637 }
1638 return QVariant( str.replace( re, after ) );
1639}
1640
1641static QVariant fcnRegexpMatch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1642{
1643 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1644 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1645
1646 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1647 if ( !re.isValid() )
1648 {
1649 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1650 return QVariant();
1651 }
1652 return QVariant( ( str.indexOf( re ) + 1 ) );
1653}
1654
1655static QVariant fcnRegexpMatches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1656{
1657 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1658 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1659 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1660
1661 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1662 if ( !re.isValid() )
1663 {
1664 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1665 return QVariant();
1666 }
1667
1668 QRegularExpressionMatch matches = re.match( str );
1669 if ( matches.hasMatch() )
1670 {
1671 QVariantList array;
1672 QStringList list = matches.capturedTexts();
1673
1674 // Skip the first string to only return captured groups
1675 for ( QStringList::const_iterator it = ++list.constBegin(); it != list.constEnd(); ++it )
1676 {
1677 array += ( !( *it ).isEmpty() ) ? *it : empty;
1678 }
1679
1680 return QVariant( array );
1681 }
1682 else
1683 {
1684 return QVariant();
1685 }
1686}
1687
1688static QVariant fcnRegexpSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1689{
1690 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1691 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1692
1693 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1694 if ( !re.isValid() )
1695 {
1696 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1697 return QVariant();
1698 }
1699
1700 // extract substring
1701 QRegularExpressionMatch match = re.match( str );
1702 if ( match.hasMatch() )
1703 {
1704 // return first capture
1705 if ( match.lastCapturedIndex() > 0 )
1706 {
1707 // a capture group was present, so use that
1708 return QVariant( match.captured( 1 ) );
1709 }
1710 else
1711 {
1712 // no capture group, so using all match
1713 return QVariant( match.captured( 0 ) );
1714 }
1715 }
1716 else
1717 {
1718 return QVariant( "" );
1719 }
1720}
1721
1722static QVariant fcnUuid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1723{
1724 QString uuid = QUuid::createUuid().toString();
1725 if ( values.at( 0 ).toString().compare( QStringLiteral( "WithoutBraces" ), Qt::CaseInsensitive ) == 0 )
1726 uuid = QUuid::createUuid().toString( QUuid::StringFormat::WithoutBraces );
1727 else if ( values.at( 0 ).toString().compare( QStringLiteral( "Id128" ), Qt::CaseInsensitive ) == 0 )
1728 uuid = QUuid::createUuid().toString( QUuid::StringFormat::Id128 );
1729 return uuid;
1730}
1731
1732static QVariant fcnSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1733{
1734 if ( !values.at( 0 ).isValid() || !values.at( 1 ).isValid() )
1735 return QVariant();
1736
1737 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1738 int from = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1739
1740 int len = 0;
1741 if ( values.at( 2 ).isValid() )
1742 len = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
1743 else
1744 len = str.size();
1745
1746 if ( from < 0 )
1747 {
1748 from = str.size() + from;
1749 if ( from < 0 )
1750 {
1751 from = 0;
1752 }
1753 }
1754 else if ( from > 0 )
1755 {
1756 //account for the fact that substr() starts at 1
1757 from -= 1;
1758 }
1759
1760 if ( len < 0 )
1761 {
1762 len = str.size() + len - from;
1763 if ( len < 0 )
1764 {
1765 len = 0;
1766 }
1767 }
1768
1769 return QVariant( str.mid( from, len ) );
1770}
1771static QVariant fcnFeatureId( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1772{
1773 FEAT_FROM_CONTEXT( context, f )
1774 return QVariant( f.id() );
1775}
1776
1777static QVariant fcnRasterValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1778{
1779 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1780 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
1781 bool foundLayer = false;
1782 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, geom]( QgsMapLayer * mapLayer )
1783 {
1784 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer * >( mapLayer );
1785 if ( !layer || !layer->dataProvider() )
1786 {
1787 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1788 return QVariant();
1789 }
1790
1791 if ( bandNb < 1 || bandNb > layer->bandCount() )
1792 {
1793 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster band number." ) );
1794 return QVariant();
1795 }
1796
1797 if ( geom.isNull() || geom.type() != Qgis::GeometryType::Point )
1798 {
1799 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid point geometry." ) );
1800 return QVariant();
1801 }
1802
1803 QgsPointXY point = geom.asPoint();
1804 if ( geom.isMultipart() )
1805 {
1806 QgsMultiPointXY multiPoint = geom.asMultiPoint();
1807 if ( multiPoint.count() == 1 )
1808 {
1809 point = multiPoint[0];
1810 }
1811 else
1812 {
1813 // if the geometry contains more than one part, return an undefined value
1814 return QVariant();
1815 }
1816 }
1817
1818 double value = layer->dataProvider()->sample( point, bandNb );
1819 return std::isnan( value ) ? QVariant() : value;
1820 },
1821 foundLayer );
1822
1823 if ( !foundLayer )
1824 {
1825 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1826 return QVariant();
1827 }
1828 else
1829 {
1830 return res;
1831 }
1832}
1833
1834static QVariant fcnRasterAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1835{
1836 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1837 const double value = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1838
1839 bool foundLayer = false;
1840 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, value]( QgsMapLayer * mapLayer )-> QVariant
1841 {
1842 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer *>( mapLayer );
1843 if ( !layer || !layer->dataProvider() )
1844 {
1845 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1846 return QVariant();
1847 }
1848
1849 if ( bandNb < 1 || bandNb > layer->bandCount() )
1850 {
1851 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster band number." ) );
1852 return QVariant();
1853 }
1854
1855 if ( std::isnan( value ) )
1856 {
1857 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster value." ) );
1858 return QVariant();
1859 }
1860
1861 if ( ! layer->dataProvider()->attributeTable( bandNb ) )
1862 {
1863 return QVariant();
1864 }
1865
1866 const QVariantList data = layer->dataProvider()->attributeTable( bandNb )->row( value );
1867 if ( data.isEmpty() )
1868 {
1869 return QVariant();
1870 }
1871
1872 QVariantMap result;
1873 const QList<QgsRasterAttributeTable::Field> fields { layer->dataProvider()->attributeTable( bandNb )->fields() };
1874 for ( int idx = 0; idx < static_cast<int>( fields.count( ) ) && idx < static_cast<int>( data.count() ); ++idx )
1875 {
1876 const QgsRasterAttributeTable::Field field { fields.at( idx ) };
1877 if ( field.isColor() || field.isRamp() )
1878 {
1879 continue;
1880 }
1881 result.insert( fields.at( idx ).name, data.at( idx ) );
1882 }
1883
1884 return result;
1885 }, foundLayer );
1886
1887 if ( !foundLayer )
1888 {
1889 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1890 return QVariant();
1891 }
1892 else
1893 {
1894 return res;
1895 }
1896}
1897
1898static QVariant fcnFeature( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1899{
1900 if ( !context )
1901 return QVariant();
1902
1903 return context->feature();
1904}
1905
1906static QVariant fcnAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1907{
1908 QgsFeature feature;
1909 QString attr;
1910 if ( values.size() == 1 )
1911 {
1912 attr = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1913 feature = context->feature();
1914 }
1915 else if ( values.size() == 2 )
1916 {
1917 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
1918 attr = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1919 }
1920 else
1921 {
1922 parent->setEvalErrorString( QObject::tr( "Function `attribute` requires one or two parameters. %n given.", nullptr, values.length() ) );
1923 return QVariant();
1924 }
1925
1926 return feature.attribute( attr );
1927}
1928
1929static QVariant fcnMapToHtmlTable( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1930{
1931 QString table { R"html(
1932 <table>
1933 <thead>
1934 <tr><th>%1</th></tr>
1935 </thead>
1936 <tbody>
1937 <tr><td>%2</td></tr>
1938 </tbody>
1939 </table>)html" };
1940 QVariantMap dict;
1941 if ( values.size() == 1 )
1942 {
1943 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1944 }
1945 else
1946 {
1947 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_table` requires one parameter. %n given.", nullptr, values.length() ) );
1948 return QVariant();
1949 }
1950
1951 if ( dict.isEmpty() )
1952 {
1953 return QVariant();
1954 }
1955
1956 QStringList headers;
1957 QStringList cells;
1958
1959 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1960 {
1961 headers.push_back( it.key().toHtmlEscaped() );
1962 cells.push_back( it.value().toString( ).toHtmlEscaped() );
1963 }
1964
1965 return table.arg( headers.join( QLatin1String( "</th><th>" ) ), cells.join( QLatin1String( "</td><td>" ) ) );
1966}
1967
1968static QVariant fcnMapToHtmlDefinitionList( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1969{
1970 QString table { R"html(
1971 <dl>
1972 %1
1973 </dl>)html" };
1974 QVariantMap dict;
1975 if ( values.size() == 1 )
1976 {
1977 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1978 }
1979 else
1980 {
1981 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_dl` requires one parameter. %n given.", nullptr, values.length() ) );
1982 return QVariant();
1983 }
1984
1985 if ( dict.isEmpty() )
1986 {
1987 return QVariant();
1988 }
1989
1990 QString rows;
1991
1992 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1993 {
1994 rows.append( QStringLiteral( "<dt>%1</dt><dd>%2</dd>" ).arg( it.key().toHtmlEscaped(), it.value().toString().toHtmlEscaped() ) );
1995 }
1996
1997 return table.arg( rows );
1998}
1999
2000static QVariant fcnValidateFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2001{
2002 QVariant layer;
2003 if ( values.size() < 1 || QgsVariantUtils::isNull( values.at( 0 ) ) )
2004 {
2005 layer = context->variable( QStringLiteral( "layer" ) );
2006 }
2007 else
2008 {
2009 //first node is layer id or name
2010 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
2012 layer = node->eval( parent, context );
2014 }
2015
2016 QgsFeature feature;
2017 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
2018 {
2019 feature = context->feature();
2020 }
2021 else
2022 {
2023 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2024 }
2025
2027 const QString strength = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).toLower();
2028 if ( strength == QLatin1String( "hard" ) )
2029 {
2031 }
2032 else if ( strength == QLatin1String( "soft" ) )
2033 {
2035 }
2036
2037 bool foundLayer = false;
2038 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
2039 {
2040 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2041 if ( !layer )
2042 {
2043 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2044 return QVariant();
2045 }
2046
2047 const QgsFields fields = layer->fields();
2048 bool valid = true;
2049 for ( int i = 0; i < fields.size(); i++ )
2050 {
2051 QStringList errors;
2052 valid = QgsVectorLayerUtils::validateAttribute( layer, feature, i, errors, constraintStrength );
2053 if ( !valid )
2054 {
2055 break;
2056 }
2057 }
2058
2059 return valid;
2060 }, foundLayer );
2061
2062 if ( !foundLayer )
2063 {
2064 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2065 return QVariant();
2066 }
2067
2068 return res;
2069}
2070
2071static QVariant fcnValidateAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2072{
2073 QVariant layer;
2074 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
2075 {
2076 layer = context->variable( QStringLiteral( "layer" ) );
2077 }
2078 else
2079 {
2080 //first node is layer id or name
2081 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
2083 layer = node->eval( parent, context );
2085 }
2086
2087 QgsFeature feature;
2088 if ( values.size() < 3 || QgsVariantUtils::isNull( values.at( 2 ) ) )
2089 {
2090 feature = context->feature();
2091 }
2092 else
2093 {
2094 feature = QgsExpressionUtils::getFeature( values.at( 2 ), parent );
2095 }
2096
2098 const QString strength = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).toLower();
2099 if ( strength == QLatin1String( "hard" ) )
2100 {
2102 }
2103 else if ( strength == QLatin1String( "soft" ) )
2104 {
2106 }
2107
2108 const QString attributeName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2109
2110 bool foundLayer = false;
2111 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, attributeName, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
2112 {
2113 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2114 if ( !layer )
2115 {
2116 return QVariant();
2117 }
2118
2119 const int fieldIndex = layer->fields().indexFromName( attributeName );
2120 if ( fieldIndex == -1 )
2121 {
2122 parent->setEvalErrorString( QObject::tr( "The attribute name did not match any field for the given feature" ) );
2123 return QVariant();
2124 }
2125
2126 QStringList errors;
2127 bool valid = QgsVectorLayerUtils::validateAttribute( layer, feature, fieldIndex, errors, constraintStrength );
2128 return valid;
2129 }, foundLayer );
2130
2131 if ( !foundLayer )
2132 {
2133 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2134 return QVariant();
2135 }
2136
2137 return res;
2138}
2139
2140static QVariant fcnAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2141{
2142 QgsFeature feature;
2143 if ( values.size() == 0 || QgsVariantUtils::isNull( values.at( 0 ) ) )
2144 {
2145 feature = context->feature();
2146 }
2147 else
2148 {
2149 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2150 }
2151
2152 const QgsFields fields = feature.fields();
2153 QVariantMap result;
2154 for ( int i = 0; i < fields.count(); ++i )
2155 {
2156 result.insert( fields.at( i ).name(), feature.attribute( i ) );
2157 }
2158 return result;
2159}
2160
2161static QVariant fcnRepresentAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2162{
2163 QgsVectorLayer *layer = nullptr;
2164 QgsFeature feature;
2165
2166 // TODO this expression function is NOT thread safe
2168 if ( values.isEmpty() )
2169 {
2170 feature = context->feature();
2171 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2172 }
2173 else if ( values.size() == 1 )
2174 {
2175 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2176 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2177 }
2178 else if ( values.size() == 2 )
2179 {
2180 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2181 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2182 }
2183 else
2184 {
2185 parent->setEvalErrorString( QObject::tr( "Function `represent_attributes` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2186 return QVariant();
2187 }
2189
2190 if ( !layer )
2191 {
2192 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: layer could not be resolved." ) );
2193 return QVariant();
2194 }
2195
2196 if ( !feature.isValid() )
2197 {
2198 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: feature could not be resolved." ) );
2199 return QVariant();
2200 }
2201
2202 const QgsFields fields = feature.fields();
2203 QVariantMap result;
2204 for ( int fieldIndex = 0; fieldIndex < fields.count(); ++fieldIndex )
2205 {
2206 const QString fieldName { fields.at( fieldIndex ).name() };
2207 const QVariant attributeVal = feature.attribute( fieldIndex );
2208 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer->id(), fieldName, attributeVal.toString() );
2209 if ( context && context->hasCachedValue( cacheValueKey ) )
2210 {
2211 result.insert( fieldName, context->cachedValue( cacheValueKey ) );
2212 }
2213 else
2214 {
2215 const QgsEditorWidgetSetup setup = layer->editorWidgetSetup( fieldIndex );
2217 QVariant cache;
2218 if ( context )
2219 {
2220 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer->id(), fieldName );
2221
2222 if ( !context->hasCachedValue( cacheKey ) )
2223 {
2224 cache = fieldFormatter->createCache( layer, fieldIndex, setup.config() );
2225 context->setCachedValue( cacheKey, cache );
2226 }
2227 else
2228 {
2229 cache = context->cachedValue( cacheKey );
2230 }
2231 }
2232 QString value( fieldFormatter->representValue( layer, fieldIndex, setup.config(), cache, attributeVal ) );
2233
2234 result.insert( fields.at( fieldIndex ).name(), value );
2235
2236 if ( context )
2237 {
2238 context->setCachedValue( cacheValueKey, value );
2239 }
2240
2241 }
2242 }
2243 return result;
2244}
2245
2246static QVariant fcnCoreFeatureMaptipDisplay( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const bool isMaptip )
2247{
2248 QgsVectorLayer *layer = nullptr;
2249 QgsFeature feature;
2250 bool evaluate = true;
2251
2252 // TODO this expression function is NOT thread safe
2254 if ( values.isEmpty() )
2255 {
2256 feature = context->feature();
2257 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2258 }
2259 else if ( values.size() == 1 )
2260 {
2261 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2262 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2263 }
2264 else if ( values.size() == 2 )
2265 {
2266 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2267 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2268 }
2269 else if ( values.size() == 3 )
2270 {
2271 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2272 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2273 evaluate = values.value( 2 ).toBool();
2274 }
2275 else
2276 {
2277 if ( isMaptip )
2278 {
2279 parent->setEvalErrorString( QObject::tr( "Function `maptip` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2280 }
2281 else
2282 {
2283 parent->setEvalErrorString( QObject::tr( "Function `display` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2284 }
2285 return QVariant();
2286 }
2287
2288 if ( !layer )
2289 {
2290 parent->setEvalErrorString( QObject::tr( "The layer is not valid." ) );
2291 return QVariant( );
2292 }
2294
2295 if ( !feature.isValid() )
2296 {
2297 parent->setEvalErrorString( QObject::tr( "The feature is not valid." ) );
2298 return QVariant( );
2299 }
2300
2301 if ( ! evaluate )
2302 {
2303 if ( isMaptip )
2304 {
2305 return layer->mapTipTemplate();
2306 }
2307 else
2308 {
2309 return layer->displayExpression();
2310 }
2311 }
2312
2313 QgsExpressionContext subContext( *context );
2314 subContext.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( layer ) );
2315 subContext.setFeature( feature );
2316
2317 if ( isMaptip )
2318 {
2319 return QgsExpression::replaceExpressionText( layer->mapTipTemplate(), &subContext );
2320 }
2321 else
2322 {
2323 QgsExpression exp( layer->displayExpression() );
2324 exp.prepare( &subContext );
2325 return exp.evaluate( &subContext ).toString();
2326 }
2327}
2328
2329static QVariant fcnFeatureDisplayExpression( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2330{
2331 return fcnCoreFeatureMaptipDisplay( values, context, parent, false );
2332}
2333
2334static QVariant fcnFeatureMaptip( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2335{
2336 return fcnCoreFeatureMaptipDisplay( values, context, parent, true );
2337}
2338
2339static QVariant fcnIsSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2340{
2341 QgsFeature feature;
2342 QVariant layer;
2343 if ( values.isEmpty() )
2344 {
2345 feature = context->feature();
2346 layer = context->variable( QStringLiteral( "layer" ) );
2347 }
2348 else if ( values.size() == 1 )
2349 {
2350 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2351 layer = context->variable( QStringLiteral( "layer" ) );
2352 }
2353 else if ( values.size() == 2 )
2354 {
2355 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2356 layer = values.at( 0 );
2357 }
2358 else
2359 {
2360 parent->setEvalErrorString( QObject::tr( "Function `is_selected` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2361 return QVariant();
2362 }
2363
2364 bool foundLayer = false;
2365 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [feature]( QgsMapLayer * mapLayer ) -> QVariant
2366 {
2367 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2368 if ( !layer || !feature.isValid() )
2369 {
2370 return QgsVariantUtils::createNullVariant( QMetaType::Type::Bool );
2371 }
2372
2373 return layer->selectedFeatureIds().contains( feature.id() );
2374 }, foundLayer );
2375 if ( !foundLayer )
2376 return QgsVariantUtils::createNullVariant( QMetaType::Type::Bool );
2377 else
2378 return res;
2379}
2380
2381static QVariant fcnNumSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2382{
2383 QVariant layer;
2384
2385 if ( values.isEmpty() )
2386 layer = context->variable( QStringLiteral( "layer" ) );
2387 else if ( values.count() == 1 )
2388 layer = values.at( 0 );
2389 else
2390 {
2391 parent->setEvalErrorString( QObject::tr( "Function `num_selected` requires no more than one parameter. %n given.", nullptr, values.length() ) );
2392 return QVariant();
2393 }
2394
2395 bool foundLayer = false;
2396 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, []( QgsMapLayer * mapLayer ) -> QVariant
2397 {
2398 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2399 if ( !layer )
2400 {
2401 return QgsVariantUtils::createNullVariant( QMetaType::Type::LongLong );
2402 }
2403
2404 return layer->selectedFeatureCount();
2405 }, foundLayer );
2406 if ( !foundLayer )
2407 return QgsVariantUtils::createNullVariant( QMetaType::Type::LongLong );
2408 else
2409 return res;
2410}
2411
2412static QVariant fcnSqliteFetchAndIncrement( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2413{
2414 static QMap<QString, qlonglong> counterCache;
2415 QVariant functionResult;
2416
2417 auto fetchAndIncrementFunc = [ values, parent, &functionResult ]( QgsMapLayer * mapLayer, const QString & databaseArgument )
2418 {
2419 QString database;
2420
2421 const QgsVectorLayer *layer = qobject_cast< QgsVectorLayer *>( mapLayer );
2422
2423 if ( layer )
2424 {
2425 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
2426 database = decodedUri.value( QStringLiteral( "path" ) ).toString();
2427 if ( database.isEmpty() )
2428 {
2429 parent->setEvalErrorString( QObject::tr( "Could not extract file path from layer `%1`." ).arg( layer->name() ) );
2430 }
2431 }
2432 else
2433 {
2434 database = databaseArgument;
2435 }
2436
2437 const QString table = values.at( 1 ).toString();
2438 const QString idColumn = values.at( 2 ).toString();
2439 const QString filterAttribute = values.at( 3 ).toString();
2440 const QVariant filterValue = values.at( 4 ).toString();
2441 const QVariantMap defaultValues = values.at( 5 ).toMap();
2442
2443 // read from database
2445 sqlite3_statement_unique_ptr sqliteStatement;
2446
2447 if ( sqliteDb.open_v2( database, SQLITE_OPEN_READWRITE, nullptr ) != SQLITE_OK )
2448 {
2449 parent->setEvalErrorString( QObject::tr( "Could not open sqlite database %1. Error %2. " ).arg( database, sqliteDb.errorMessage() ) );
2450 functionResult = QVariant();
2451 return;
2452 }
2453
2454 QString errorMessage;
2455 QString currentValSql;
2456
2457 qlonglong nextId = 0;
2458 bool cachedMode = false;
2459 bool valueRetrieved = false;
2460
2461 QString cacheString = QStringLiteral( "%1:%2:%3:%4:%5" ).arg( database, table, idColumn, filterAttribute, filterValue.toString() );
2462
2463 // Running in transaction mode, check for cached value first
2464 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2465 {
2466 cachedMode = true;
2467
2468 auto cachedCounter = counterCache.find( cacheString );
2469
2470 if ( cachedCounter != counterCache.end() )
2471 {
2472 qlonglong &cachedValue = cachedCounter.value();
2473 nextId = cachedValue;
2474 nextId += 1;
2475 cachedValue = nextId;
2476 valueRetrieved = true;
2477 }
2478 }
2479
2480 // Either not in cached mode or no cached value found, obtain from DB
2481 if ( !cachedMode || !valueRetrieved )
2482 {
2483 int result = SQLITE_ERROR;
2484
2485 currentValSql = QStringLiteral( "SELECT %1 FROM %2" ).arg( QgsSqliteUtils::quotedIdentifier( idColumn ), QgsSqliteUtils::quotedIdentifier( table ) );
2486 if ( !filterAttribute.isNull() )
2487 {
2488 currentValSql += QStringLiteral( " WHERE %1 = %2" ).arg( QgsSqliteUtils::quotedIdentifier( filterAttribute ), QgsSqliteUtils::quotedValue( filterValue ) );
2489 }
2490
2491 sqliteStatement = sqliteDb.prepare( currentValSql, result );
2492
2493 if ( result == SQLITE_OK )
2494 {
2495 nextId = 0;
2496 if ( sqliteStatement.step() == SQLITE_ROW )
2497 {
2498 nextId = sqliteStatement.columnAsInt64( 0 ) + 1;
2499 }
2500
2501 // If in cached mode: add value to cache and connect to transaction
2502 if ( cachedMode && result == SQLITE_OK )
2503 {
2504 counterCache.insert( cacheString, nextId );
2505
2506 QObject::connect( layer->dataProvider()->transaction(), &QgsTransaction::destroyed, [cacheString]()
2507 {
2508 counterCache.remove( cacheString );
2509 } );
2510 }
2511 valueRetrieved = true;
2512 }
2513 }
2514
2515 if ( valueRetrieved )
2516 {
2517 QString upsertSql;
2518 upsertSql = QStringLiteral( "INSERT OR REPLACE INTO %1" ).arg( QgsSqliteUtils::quotedIdentifier( table ) );
2519 QStringList cols;
2520 QStringList vals;
2521 cols << QgsSqliteUtils::quotedIdentifier( idColumn );
2522 vals << QgsSqliteUtils::quotedValue( nextId );
2523
2524 if ( !filterAttribute.isNull() )
2525 {
2526 cols << QgsSqliteUtils::quotedIdentifier( filterAttribute );
2527 vals << QgsSqliteUtils::quotedValue( filterValue );
2528 }
2529
2530 for ( QVariantMap::const_iterator iter = defaultValues.constBegin(); iter != defaultValues.constEnd(); ++iter )
2531 {
2532 cols << QgsSqliteUtils::quotedIdentifier( iter.key() );
2533 vals << iter.value().toString();
2534 }
2535
2536 upsertSql += QLatin1String( " (" ) + cols.join( ',' ) + ')';
2537 upsertSql += QLatin1String( " VALUES " );
2538 upsertSql += '(' + vals.join( ',' ) + ')';
2539
2540 int result = SQLITE_ERROR;
2541 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2542 {
2543 QgsTransaction *transaction = layer->dataProvider()->transaction();
2544 if ( transaction->executeSql( upsertSql, errorMessage ) )
2545 {
2546 result = SQLITE_OK;
2547 }
2548 }
2549 else
2550 {
2551 result = sqliteDb.exec( upsertSql, errorMessage );
2552 }
2553 if ( result == SQLITE_OK )
2554 {
2555 functionResult = QVariant( nextId );
2556 return;
2557 }
2558 else
2559 {
2560 parent->setEvalErrorString( QStringLiteral( "Could not increment value: SQLite error: \"%1\" (%2)." ).arg( errorMessage, QString::number( result ) ) );
2561 functionResult = QVariant();
2562 return;
2563 }
2564 }
2565
2566 functionResult = QVariant();
2567 };
2568
2569 bool foundLayer = false;
2570 QgsExpressionUtils::executeLambdaForMapLayer( values.at( 0 ), context, parent, [&fetchAndIncrementFunc]( QgsMapLayer * layer )
2571 {
2572 fetchAndIncrementFunc( layer, QString() );
2573 }, foundLayer );
2574 if ( !foundLayer )
2575 {
2576 const QString databasePath = values.at( 0 ).toString();
2577 QgsThreadingUtils::runOnMainThread( [&fetchAndIncrementFunc, databasePath]
2578 {
2579 fetchAndIncrementFunc( nullptr, databasePath );
2580 } );
2581 }
2582
2583 return functionResult;
2584}
2585
2586static QVariant fcnCrsToAuthid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2587{
2588 const QgsCoordinateReferenceSystem crs = QgsExpressionUtils::getCrsValue( values.at( 0 ), parent );
2589 if ( !crs.isValid() )
2590 return QVariant();
2591 return crs.authid();
2592}
2593
2594static QVariant fcnCrsFromText( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2595{
2596 QString definition = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2597 QgsCoordinateReferenceSystem crs( definition );
2598
2599 if ( !crs.isValid() )
2600 {
2601 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to cordinate reference system" ).arg( definition ) );
2602 }
2603
2604 return QVariant::fromValue( crs );
2605}
2606
2607static QVariant fcnConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2608{
2609 QString concat;
2610 for ( const QVariant &value : values )
2611 {
2612 if ( !QgsVariantUtils::isNull( value ) )
2613 concat += QgsExpressionUtils::getStringValue( value, parent );
2614 }
2615 return concat;
2616}
2617
2618static QVariant fcnStrpos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2619{
2620 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2621 return string.indexOf( QgsExpressionUtils::getStringValue( values.at( 1 ), parent ) ) + 1;
2622}
2623
2624static QVariant fcnRight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2625{
2626 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2627 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2628 return string.right( pos );
2629}
2630
2631static QVariant fcnLeft( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2632{
2633 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2634 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2635 return string.left( pos );
2636}
2637
2638static QVariant fcnRPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2639{
2640 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2641 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2642 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2643 return string.leftJustified( length, fill.at( 0 ), true );
2644}
2645
2646static QVariant fcnLPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2647{
2648 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2649 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2650 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2651 return string.rightJustified( length, fill.at( 0 ), true );
2652}
2653
2654static QVariant fcnFormatString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2655{
2656 if ( values.size() < 1 )
2657 {
2658 parent->setEvalErrorString( QObject::tr( "Function format requires at least 1 argument" ) );
2659 return QVariant();
2660 }
2661
2662 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2663 for ( int n = 1; n < values.length(); n++ )
2664 {
2665 string = string.arg( QgsExpressionUtils::getStringValue( values.at( n ), parent ) );
2666 }
2667 return string;
2668}
2669
2670
2671static QVariant fcnNow( const QVariantList &, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
2672{
2673 return QVariant( QDateTime::currentDateTime() );
2674}
2675
2676static QVariant fcnToDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2677{
2678 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2679 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2680 if ( format.isEmpty() && !language.isEmpty() )
2681 {
2682 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Date when the language is specified" ) );
2683 return QVariant( QDate() );
2684 }
2685
2686 if ( format.isEmpty() && language.isEmpty() )
2687 return QVariant( QgsExpressionUtils::getDateValue( values.at( 0 ), parent ) );
2688
2689 QString datestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2690 QLocale locale = QLocale();
2691 if ( !language.isEmpty() )
2692 {
2693 locale = QLocale( language );
2694 }
2695
2696 QDate date = locale.toDate( datestring, format );
2697 if ( !date.isValid() )
2698 {
2699 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Date" ).arg( datestring ) );
2700 date = QDate();
2701 }
2702 return QVariant( date );
2703}
2704
2705static QVariant fcnToTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2706{
2707 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2708 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2709 if ( format.isEmpty() && !language.isEmpty() )
2710 {
2711 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Time when the language is specified" ) );
2712 return QVariant( QTime() );
2713 }
2714
2715 if ( format.isEmpty() && language.isEmpty() )
2716 return QVariant( QgsExpressionUtils::getTimeValue( values.at( 0 ), parent ) );
2717
2718 QString timestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2719 QLocale locale = QLocale();
2720 if ( !language.isEmpty() )
2721 {
2722 locale = QLocale( language );
2723 }
2724
2725 QTime time = locale.toTime( timestring, format );
2726 if ( !time.isValid() )
2727 {
2728 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Time" ).arg( timestring ) );
2729 time = QTime();
2730 }
2731 return QVariant( time );
2732}
2733
2734static QVariant fcnToInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2735{
2736 return QVariant::fromValue( QgsExpressionUtils::getInterval( values.at( 0 ), parent ) );
2737}
2738
2739/*
2740 * DMS functions
2741 */
2742
2743static QVariant floatToDegreeFormat( const QgsCoordinateFormatter::Format format, const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2744{
2745 double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
2746 QString axis = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2747 int precision = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
2748
2749 QString formatString;
2750 if ( values.count() > 3 )
2751 formatString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent );
2752
2754 if ( formatString.compare( QLatin1String( "suffix" ), Qt::CaseInsensitive ) == 0 )
2755 {
2757 }
2758 else if ( formatString.compare( QLatin1String( "aligned" ), Qt::CaseInsensitive ) == 0 )
2759 {
2761 }
2762 else if ( ! formatString.isEmpty() )
2763 {
2764 parent->setEvalErrorString( QObject::tr( "Invalid formatting parameter: '%1'. It must be empty, or 'suffix' or 'aligned'." ).arg( formatString ) );
2765 return QVariant();
2766 }
2767
2768 if ( axis.compare( QLatin1String( "x" ), Qt::CaseInsensitive ) == 0 )
2769 {
2770 return QVariant::fromValue( QgsCoordinateFormatter::formatX( value, format, precision, flags ) );
2771 }
2772 else if ( axis.compare( QLatin1String( "y" ), Qt::CaseInsensitive ) == 0 )
2773 {
2774 return QVariant::fromValue( QgsCoordinateFormatter::formatY( value, format, precision, flags ) );
2775 }
2776 else
2777 {
2778 parent->setEvalErrorString( QObject::tr( "Invalid axis name: '%1'. It must be either 'x' or 'y'." ).arg( axis ) );
2779 return QVariant();
2780 }
2781}
2782
2783static QVariant fcnToDegreeMinute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2784{
2786 return floatToDegreeFormat( format, values, context, parent, node );
2787}
2788
2789static QVariant fcnToDecimal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2790{
2791 double value = 0.0;
2792 bool ok = false;
2793 value = QgsCoordinateUtils::dmsToDecimal( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), &ok );
2794
2795 return ok ? QVariant( value ) : QVariant();
2796}
2797
2798static QVariant fcnToDegreeMinuteSecond( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2799{
2801 return floatToDegreeFormat( format, values, context, parent, node );
2802}
2803
2804static QVariant fcnAge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2805{
2806 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2807 QDateTime d2 = QgsExpressionUtils::getDateTimeValue( values.at( 1 ), parent );
2808 qint64 seconds = d2.secsTo( d1 );
2809 return QVariant::fromValue( QgsInterval( seconds ) );
2810}
2811
2812static QVariant fcnDayOfWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2813{
2814 if ( !values.at( 0 ).canConvert<QDate>() )
2815 return QVariant();
2816
2817 QDate date = QgsExpressionUtils::getDateValue( values.at( 0 ), parent );
2818 if ( !date.isValid() )
2819 return QVariant();
2820
2821 // return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
2822 // (to match PostgreSQL behavior)
2823 return date.dayOfWeek() % 7;
2824}
2825
2826static QVariant fcnDay( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2827{
2828 QVariant value = values.at( 0 );
2829 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2830 if ( inter.isValid() )
2831 {
2832 return QVariant( inter.days() );
2833 }
2834 else
2835 {
2836 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2837 return QVariant( d1.date().day() );
2838 }
2839}
2840
2841static QVariant fcnYear( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2842{
2843 QVariant value = values.at( 0 );
2844 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2845 if ( inter.isValid() )
2846 {
2847 return QVariant( inter.years() );
2848 }
2849 else
2850 {
2851 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2852 return QVariant( d1.date().year() );
2853 }
2854}
2855
2856static QVariant fcnMonth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2857{
2858 QVariant value = values.at( 0 );
2859 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2860 if ( inter.isValid() )
2861 {
2862 return QVariant( inter.months() );
2863 }
2864 else
2865 {
2866 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2867 return QVariant( d1.date().month() );
2868 }
2869}
2870
2871static QVariant fcnWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2872{
2873 QVariant value = values.at( 0 );
2874 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2875 if ( inter.isValid() )
2876 {
2877 return QVariant( inter.weeks() );
2878 }
2879 else
2880 {
2881 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2882 return QVariant( d1.date().weekNumber() );
2883 }
2884}
2885
2886static QVariant fcnHour( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2887{
2888 QVariant value = values.at( 0 );
2889 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2890 if ( inter.isValid() )
2891 {
2892 return QVariant( inter.hours() );
2893 }
2894 else
2895 {
2896 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2897 return QVariant( t1.hour() );
2898 }
2899}
2900
2901static QVariant fcnMinute( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2902{
2903 QVariant value = values.at( 0 );
2904 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2905 if ( inter.isValid() )
2906 {
2907 return QVariant( inter.minutes() );
2908 }
2909 else
2910 {
2911 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2912 return QVariant( t1.minute() );
2913 }
2914}
2915
2916static QVariant fcnSeconds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2917{
2918 QVariant value = values.at( 0 );
2919 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2920 if ( inter.isValid() )
2921 {
2922 return QVariant( inter.seconds() );
2923 }
2924 else
2925 {
2926 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2927 return QVariant( t1.second() );
2928 }
2929}
2930
2931static QVariant fcnEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2932{
2933 QDateTime dt = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2934 if ( dt.isValid() )
2935 {
2936 return QVariant( dt.toMSecsSinceEpoch() );
2937 }
2938 else
2939 {
2940 return QVariant();
2941 }
2942}
2943
2944static QVariant fcnDateTimeFromEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2945{
2946 long long millisecs_since_epoch = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
2947 // no sense to check for strange values, as Qt behavior is undefined anyway (see docs)
2948 return QVariant( QDateTime::fromMSecsSinceEpoch( millisecs_since_epoch ) );
2949}
2950
2951static QVariant fcnExif( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2952{
2953 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2954 if ( parent->hasEvalError() )
2955 {
2956 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif" ) ) );
2957 return QVariant();
2958 }
2959 QString tag = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2960 return !tag.isNull() ? QgsExifTools::readTag( filepath, tag ) : QVariant( QgsExifTools::readTags( filepath ) );
2961}
2962
2963static QVariant fcnExifGeoTag( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2965 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2966 if ( parent->hasEvalError() )
2967 {
2968 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif_geotag" ) ) );
2969 return QVariant();
2970 }
2971 bool ok;
2972 return QVariant::fromValue( QgsGeometry( new QgsPoint( QgsExifTools::getGeoTag( filepath, ok ) ) ) );
2973}
2974
2975#define ENSURE_GEOM_TYPE(f, g, geomtype) \
2976 if ( !(f).hasGeometry() ) \
2977 return QVariant(); \
2978 QgsGeometry g = (f).geometry(); \
2979 if ( (g).type() != (geomtype) ) \
2980 return QVariant();
2981
2982static QVariant fcnX( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2983{
2984 FEAT_FROM_CONTEXT( context, f )
2986 if ( g.isMultipart() )
2987 {
2988 return g.asMultiPoint().at( 0 ).x();
2989 }
2990 else
2991 {
2992 return g.asPoint().x();
2993 }
2994}
2995
2996static QVariant fcnY( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2997{
2998 FEAT_FROM_CONTEXT( context, f )
3000 if ( g.isMultipart() )
3001 {
3002 return g.asMultiPoint().at( 0 ).y();
3003 }
3004 else
3005 {
3006 return g.asPoint().y();
3007 }
3008}
3009
3010static QVariant fcnZ( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
3011{
3012 FEAT_FROM_CONTEXT( context, f )
3014
3015 if ( g.isEmpty() )
3016 return QVariant();
3017
3018 const QgsAbstractGeometry *abGeom = g.constGet();
3019
3020 if ( g.isEmpty() || !abGeom->is3D() )
3021 return QVariant();
3022
3023 if ( g.type() == Qgis::GeometryType::Point && !g.isMultipart() )
3024 {
3025 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( g.constGet() );
3026 if ( point )
3027 return point->z();
3028 }
3029 else if ( g.type() == Qgis::GeometryType::Point && g.isMultipart() )
3030 {
3031 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( g.constGet() ) )
3032 {
3033 if ( collection->numGeometries() > 0 )
3034 {
3035 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3036 return point->z();
3037 }
3038 }
3039 }
3040
3041 return QVariant();
3042}
3043
3044static QVariant fcnGeomIsValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3045{
3046 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3047 if ( geom.isNull() )
3048 return QVariant();
3049
3050 bool isValid = geom.isGeosValid();
3051
3052 return QVariant( isValid );
3053}
3054
3055static QVariant fcnGeomMakeValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3056{
3057 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3058 if ( geom.isNull() )
3059 return QVariant();
3060
3061 const QString methodString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).trimmed();
3062#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
3064#else
3066#endif
3067 if ( methodString.compare( QLatin1String( "linework" ), Qt::CaseInsensitive ) == 0 )
3069 else if ( methodString.compare( QLatin1String( "structure" ), Qt::CaseInsensitive ) == 0 )
3071
3072 const bool keepCollapsed = values.value( 2 ).toBool();
3073
3074 QgsGeometry valid;
3075 try
3076 {
3077 valid = geom.makeValid( method, keepCollapsed );
3078 }
3079 catch ( QgsNotSupportedException & )
3080 {
3081 parent->setEvalErrorString( QObject::tr( "The make_valid parameters require a newer GEOS library version" ) );
3082 return QVariant();
3083 }
3084
3085 return QVariant::fromValue( valid );
3086}
3087
3088static QVariant fcnGeometryCollectionAsArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3089{
3090 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3091 if ( geom.isNull() )
3092 return QVariant();
3093
3094 QVector<QgsGeometry> multiGeom = geom.asGeometryCollection();
3095 QVariantList array;
3096 for ( int i = 0; i < multiGeom.size(); ++i )
3097 {
3098 array += QVariant::fromValue( multiGeom.at( i ) );
3099 }
3100
3101 return array;
3102}
3103
3104static QVariant fcnGeomX( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3105{
3106 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3107 if ( geom.isNull() )
3108 return QVariant();
3109
3110 //if single point, return the point's x coordinate
3111 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3112 {
3113 return geom.asPoint().x();
3114 }
3115
3116 //otherwise return centroid x
3117 QgsGeometry centroid = geom.centroid();
3118 QVariant result( centroid.asPoint().x() );
3119 return result;
3120}
3121
3122static QVariant fcnGeomY( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3123{
3124 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3125 if ( geom.isNull() )
3126 return QVariant();
3127
3128 //if single point, return the point's y coordinate
3129 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3130 {
3131 return geom.asPoint().y();
3132 }
3133
3134 //otherwise return centroid y
3135 QgsGeometry centroid = geom.centroid();
3136 QVariant result( centroid.asPoint().y() );
3137 return result;
3138}
3139
3140static QVariant fcnGeomZ( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3141{
3142 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3143 if ( geom.isNull() )
3144 return QVariant(); //or 0?
3145
3146 if ( !geom.constGet()->is3D() )
3147 return QVariant();
3148
3149 //if single point, return the point's z coordinate
3150 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3151 {
3152 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3153 if ( point )
3154 return point->z();
3155 }
3156 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3157 {
3158 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3159 {
3160 if ( collection->numGeometries() == 1 )
3161 {
3162 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3163 return point->z();
3164 }
3165 }
3166 }
3167
3168 return QVariant();
3169}
3170
3171static QVariant fcnGeomM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3172{
3173 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3174 if ( geom.isNull() )
3175 return QVariant(); //or 0?
3176
3177 if ( !geom.constGet()->isMeasure() )
3178 return QVariant();
3179
3180 //if single point, return the point's m value
3181 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3182 {
3183 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3184 if ( point )
3185 return point->m();
3186 }
3187 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3188 {
3189 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3190 {
3191 if ( collection->numGeometries() == 1 )
3192 {
3193 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3194 return point->m();
3195 }
3196 }
3197 }
3198
3199 return QVariant();
3200}
3201
3202static QVariant fcnPointN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3203{
3204 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3205
3206 if ( geom.isNull() )
3207 return QVariant();
3208
3209 int idx = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
3210
3211 if ( idx < 0 )
3212 {
3213 //negative idx
3214 int count = geom.constGet()->nCoordinates();
3215 idx = count + idx;
3216 }
3217 else
3218 {
3219 //positive idx is 1 based
3220 idx -= 1;
3221 }
3222
3223 QgsVertexId vId;
3224 if ( idx < 0 || !geom.vertexIdFromVertexNr( idx, vId ) )
3225 {
3226 parent->setEvalErrorString( QObject::tr( "Point index is out of range" ) );
3227 return QVariant();
3228 }
3229
3230 QgsPoint point = geom.constGet()->vertexAt( vId );
3231 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3232}
3233
3234static QVariant fcnStartPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3235{
3236 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3237
3238 if ( geom.isNull() )
3239 return QVariant();
3240
3241 QgsVertexId vId;
3242 if ( !geom.vertexIdFromVertexNr( 0, vId ) )
3243 {
3244 return QVariant();
3245 }
3246
3247 QgsPoint point = geom.constGet()->vertexAt( vId );
3248 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3249}
3250
3251static QVariant fcnEndPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3252{
3253 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3254
3255 if ( geom.isNull() )
3256 return QVariant();
3257
3258 QgsVertexId vId;
3259 if ( !geom.vertexIdFromVertexNr( geom.constGet()->nCoordinates() - 1, vId ) )
3260 {
3261 return QVariant();
3262 }
3263
3264 QgsPoint point = geom.constGet()->vertexAt( vId );
3265 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3266}
3267
3268static QVariant fcnNodesToPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3269{
3270 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3271
3272 if ( geom.isNull() )
3273 return QVariant();
3274
3275 bool ignoreClosing = false;
3276 if ( values.length() > 1 )
3277 {
3278 ignoreClosing = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3279 }
3280
3281 QgsMultiPoint *mp = new QgsMultiPoint();
3282
3283 const QgsCoordinateSequence sequence = geom.constGet()->coordinateSequence();
3284 for ( const QgsRingSequence &part : sequence )
3285 {
3286 for ( const QgsPointSequence &ring : part )
3287 {
3288 bool skipLast = false;
3289 if ( ignoreClosing && ring.count() > 2 && ring.first() == ring.last() )
3290 {
3291 skipLast = true;
3292 }
3293
3294 for ( int i = 0; i < ( skipLast ? ring.count() - 1 : ring.count() ); ++ i )
3295 {
3296 mp->addGeometry( ring.at( i ).clone() );
3297 }
3298 }
3299 }
3300
3301 return QVariant::fromValue( QgsGeometry( mp ) );
3302}
3303
3304static QVariant fcnSegmentsToLines( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3305{
3306 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3307
3308 if ( geom.isNull() )
3309 return QVariant();
3310
3311 const QVector< QgsLineString * > linesToProcess = QgsGeometryUtils::extractLineStrings( geom.constGet() );
3312
3313 //OK, now we have a complete list of segmentized lines from the geometry
3315 for ( QgsLineString *line : linesToProcess )
3316 {
3317 for ( int i = 0; i < line->numPoints() - 1; ++i )
3318 {
3320 segment->setPoints( QgsPointSequence()
3321 << line->pointN( i )
3322 << line->pointN( i + 1 ) );
3323 ml->addGeometry( segment );
3324 }
3325 delete line;
3326 }
3327
3328 return QVariant::fromValue( QgsGeometry( ml ) );
3329}
3330
3331static QVariant fcnInteriorRingN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3332{
3333 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3334
3335 if ( geom.isNull() )
3336 return QVariant();
3337
3338 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
3339 if ( !curvePolygon && geom.isMultipart() )
3340 {
3341 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3342 {
3343 if ( collection->numGeometries() == 1 )
3344 {
3345 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
3346 }
3347 }
3348 }
3349
3350 if ( !curvePolygon )
3351 return QVariant();
3352
3353 //idx is 1 based
3354 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3355
3356 if ( idx >= curvePolygon->numInteriorRings() || idx < 0 )
3357 return QVariant();
3358
3359 QgsCurve *curve = static_cast< QgsCurve * >( curvePolygon->interiorRing( static_cast< int >( idx ) )->clone() );
3360 QVariant result = curve ? QVariant::fromValue( QgsGeometry( curve ) ) : QVariant();
3361 return result;
3362}
3363
3364static QVariant fcnGeometryN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3365{
3366 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3367
3368 if ( geom.isNull() )
3369 return QVariant();
3370
3371 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
3372 if ( !collection )
3373 return QVariant();
3374
3375 //idx is 1 based
3376 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3377
3378 if ( idx < 0 || idx >= collection->numGeometries() )
3379 return QVariant();
3380
3381 QgsAbstractGeometry *part = collection->geometryN( static_cast< int >( idx ) )->clone();
3382 QVariant result = part ? QVariant::fromValue( QgsGeometry( part ) ) : QVariant();
3383 return result;
3384}
3385
3386static QVariant fcnBoundary( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3387{
3388 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3389
3390 if ( geom.isNull() )
3391 return QVariant();
3392
3393 QgsAbstractGeometry *boundary = geom.constGet()->boundary();
3394 if ( !boundary )
3395 return QVariant();
3396
3397 return QVariant::fromValue( QgsGeometry( boundary ) );
3398}
3399
3400static QVariant fcnLineMerge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3401{
3402 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3403
3404 if ( geom.isNull() )
3405 return QVariant();
3406
3407 QgsGeometry merged = geom.mergeLines();
3408 if ( merged.isNull() )
3409 return QVariant();
3410
3411 return QVariant::fromValue( merged );
3412}
3413
3414static QVariant fcnSharedPaths( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3415{
3416 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3417 if ( geom.isNull() )
3418 return QVariant();
3419
3420 const QgsGeometry geom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
3421 if ( geom2.isNull() )
3422 return QVariant();
3423
3424 const QgsGeometry sharedPaths = geom.sharedPaths( geom2 );
3425 if ( sharedPaths.isNull() )
3426 return QVariant();
3427
3428 return QVariant::fromValue( sharedPaths );
3429}
3430
3431
3432static QVariant fcnSimplify( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3433{
3434 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3435
3436 if ( geom.isNull() )
3437 return QVariant();
3438
3439 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3440
3441 QgsGeometry simplified = geom.simplify( tolerance );
3442 if ( simplified.isNull() )
3443 return QVariant();
3444
3445 return simplified;
3446}
3447
3448static QVariant fcnSimplifyVW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3449{
3450 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3451
3452 if ( geom.isNull() )
3453 return QVariant();
3454
3455 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3456
3458
3459 QgsGeometry simplified = simplifier.simplify( geom );
3460 if ( simplified.isNull() )
3461 return QVariant();
3462
3463 return simplified;
3464}
3465
3466static QVariant fcnSmooth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3467{
3468 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3469
3470 if ( geom.isNull() )
3471 return QVariant();
3472
3473 int iterations = std::min( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), 10 );
3474 double offset = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0.0, 0.5 );
3475 double minLength = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3476 double maxAngle = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ), 0.0, 180.0 );
3477
3478 QgsGeometry smoothed = geom.smooth( static_cast<unsigned int>( iterations ), offset, minLength, maxAngle );
3479 if ( smoothed.isNull() )
3480 return QVariant();
3481
3482 return smoothed;
3483}
3484
3485static QVariant fcnTriangularWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3486{
3487 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3488
3489 if ( geom.isNull() )
3490 return QVariant();
3491
3492 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3493 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3494 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3495
3496 const QgsGeometry waved = geom.triangularWaves( wavelength, amplitude, strict );
3497 if ( waved.isNull() )
3498 return QVariant();
3499
3500 return waved;
3501}
3502
3503static QVariant fcnTriangularWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3504{
3505 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3506
3507 if ( geom.isNull() )
3508 return QVariant();
3509
3510 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3511 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3512 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3513 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3514 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3515
3516 const QgsGeometry waved = geom.triangularWavesRandomized( minWavelength, maxWavelength,
3517 minAmplitude, maxAmplitude, seed );
3518 if ( waved.isNull() )
3519 return QVariant();
3520
3521 return waved;
3522}
3523
3524static QVariant fcnSquareWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3525{
3526 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3527
3528 if ( geom.isNull() )
3529 return QVariant();
3530
3531 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3532 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3533 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3534
3535 const QgsGeometry waved = geom.squareWaves( wavelength, amplitude, strict );
3536 if ( waved.isNull() )
3537 return QVariant();
3538
3539 return waved;
3540}
3541
3542static QVariant fcnSquareWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3543{
3544 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3545
3546 if ( geom.isNull() )
3547 return QVariant();
3548
3549 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3550 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3551 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3552 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3553 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3554
3555 const QgsGeometry waved = geom.squareWavesRandomized( minWavelength, maxWavelength,
3556 minAmplitude, maxAmplitude, seed );
3557 if ( waved.isNull() )
3558 return QVariant();
3559
3560 return waved;
3561}
3562
3563static QVariant fcnRoundWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3564{
3565 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3566
3567 if ( geom.isNull() )
3568 return QVariant();
3569
3570 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3571 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3572 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3573
3574 const QgsGeometry waved = geom.roundWaves( wavelength, amplitude, strict );
3575 if ( waved.isNull() )
3576 return QVariant();
3577
3578 return waved;
3579}
3580
3581static QVariant fcnRoundWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3582{
3583 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3584
3585 if ( geom.isNull() )
3586 return QVariant();
3587
3588 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3589 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3590 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3591 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3592 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3593
3594 const QgsGeometry waved = geom.roundWavesRandomized( minWavelength, maxWavelength,
3595 minAmplitude, maxAmplitude, seed );
3596 if ( waved.isNull() )
3597 return QVariant();
3598
3599 return waved;
3600}
3601
3602static QVariant fcnApplyDashPattern( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3603{
3604 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3605
3606 if ( geom.isNull() )
3607 return QVariant();
3608
3609 const QVariantList pattern = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
3610 QVector< double > dashPattern;
3611 dashPattern.reserve( pattern.size() );
3612 for ( const QVariant &value : std::as_const( pattern ) )
3613 {
3614 bool ok = false;
3615 double v = value.toDouble( &ok );
3616 if ( ok )
3617 {
3618 dashPattern << v;
3619 }
3620 else
3621 {
3622 parent->setEvalErrorString( QStringLiteral( "Dash pattern must be an array of numbers" ) );
3623 return QgsGeometry();
3624 }
3625 }
3626
3627 if ( dashPattern.size() % 2 != 0 )
3628 {
3629 parent->setEvalErrorString( QStringLiteral( "Dash pattern must contain an even number of elements" ) );
3630 return QgsGeometry();
3631 }
3632
3633 const QString startRuleString = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).trimmed();
3635 if ( startRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3637 else if ( startRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3639 else if ( startRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3641 else if ( startRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3643 else if ( startRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3645 else
3646 {
3647 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( startRuleString ) );
3648 return QgsGeometry();
3649 }
3650
3651 const QString endRuleString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
3653 if ( endRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3655 else if ( endRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3657 else if ( endRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3659 else if ( endRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3661 else if ( endRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3663 else
3664 {
3665 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( endRuleString ) );
3666 return QgsGeometry();
3667 }
3668
3669 const QString adjustString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
3671 if ( adjustString.compare( QLatin1String( "both" ), Qt::CaseInsensitive ) == 0 )
3673 else if ( adjustString.compare( QLatin1String( "dash" ), Qt::CaseInsensitive ) == 0 )
3675 else if ( adjustString.compare( QLatin1String( "gap" ), Qt::CaseInsensitive ) == 0 )
3677 else
3678 {
3679 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern size adjustment" ).arg( adjustString ) );
3680 return QgsGeometry();
3681 }
3682
3683 const double patternOffset = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
3684
3685 const QgsGeometry result = geom.applyDashPattern( dashPattern, startRule, endRule, adjustment, patternOffset );
3686 if ( result.isNull() )
3687 return QVariant();
3688
3689 return result;
3690}
3691
3692static QVariant fcnDensifyByCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3693{
3694 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3695
3696 if ( geom.isNull() )
3697 return QVariant();
3698
3699 const long long count = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3700 const QgsGeometry densified = geom.densifyByCount( static_cast< int >( count ) );
3701 if ( densified.isNull() )
3702 return QVariant();
3703
3704 return densified;
3705}
3706
3707static QVariant fcnDensifyByDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3708{
3709 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3710
3711 if ( geom.isNull() )
3712 return QVariant();
3713
3714 const double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3715 const QgsGeometry densified = geom.densifyByDistance( distance );
3716 if ( densified.isNull() )
3717 return QVariant();
3718
3719 return densified;
3720}
3721
3722static QVariant fcnCollectGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3723{
3724 QVariantList list;
3725 if ( values.size() == 1 && QgsExpressionUtils::isList( values.at( 0 ) ) )
3726 {
3727 list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
3728 }
3729 else
3730 {
3731 list = values;
3732 }
3733
3734 QVector< QgsGeometry > parts;
3735 parts.reserve( list.size() );
3736 for ( const QVariant &value : std::as_const( list ) )
3737 {
3738 QgsGeometry part = QgsExpressionUtils::getGeometry( value, parent );
3739 if ( part.isNull() )
3740 return QgsGeometry();
3741 parts << part;
3742 }
3743
3744 return QgsGeometry::collectGeometry( parts );
3745}
3746
3747static QVariant fcnMakePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3748{
3749 if ( values.count() < 2 || values.count() > 4 )
3750 {
3751 parent->setEvalErrorString( QObject::tr( "Function make_point requires 2-4 arguments" ) );
3752 return QVariant();
3753 }
3754
3755 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3756 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3757 double z = values.count() >= 3 ? QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) : 0.0;
3758 double m = values.count() >= 4 ? QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) : 0.0;
3759 switch ( values.count() )
3760 {
3761 case 2:
3762 return QVariant::fromValue( QgsGeometry( new QgsPoint( x, y ) ) );
3763 case 3:
3764 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZ, x, y, z ) ) );
3765 case 4:
3766 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZM, x, y, z, m ) ) );
3767 }
3768 return QVariant(); //avoid warning
3769}
3770
3771static QVariant fcnMakePointM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3772{
3773 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3774 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3775 double m = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3776 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointM, x, y, 0.0, m ) ) );
3777}
3778
3779static QVariant fcnMakeLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3780{
3781 if ( values.empty() )
3782 {
3783 return QVariant();
3784 }
3785
3786 QVector<QgsPoint> points;
3787 points.reserve( values.count() );
3788
3789 auto addPoint = [&points]( const QgsGeometry & geom )
3790 {
3791 if ( geom.isNull() )
3792 return;
3793
3794 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3795 return;
3796
3797 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3798 if ( !point )
3799 return;
3800
3801 points << *point;
3802 };
3803
3804 for ( const QVariant &value : values )
3805 {
3806 if ( value.userType() == QMetaType::Type::QVariantList )
3807 {
3808 const QVariantList list = value.toList();
3809 for ( const QVariant &v : list )
3810 {
3811 addPoint( QgsExpressionUtils::getGeometry( v, parent ) );
3812 }
3813 }
3814 else
3815 {
3816 addPoint( QgsExpressionUtils::getGeometry( value, parent ) );
3817 }
3818 }
3819
3820 if ( points.count() < 2 )
3821 return QVariant();
3822
3823 return QgsGeometry( new QgsLineString( points ) );
3824}
3825
3826static QVariant fcnMakePolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3827{
3828 if ( values.count() < 1 )
3829 {
3830 parent->setEvalErrorString( QObject::tr( "Function make_polygon requires an argument" ) );
3831 return QVariant();
3832 }
3833
3834 QgsGeometry outerRing = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3835
3836 if ( outerRing.type() == Qgis::GeometryType::Polygon )
3837 return outerRing; // if it's already a polygon we have nothing to do
3838
3839 if ( outerRing.type() != Qgis::GeometryType::Line || outerRing.isNull() )
3840 return QVariant();
3841
3842 auto polygon = std::make_unique< QgsPolygon >();
3843
3844 const QgsCurve *exteriorRing = qgsgeometry_cast< QgsCurve * >( outerRing.constGet() );
3845 if ( !exteriorRing && outerRing.isMultipart() )
3846 {
3847 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( outerRing.constGet() ) )
3848 {
3849 if ( collection->numGeometries() == 1 )
3850 {
3851 exteriorRing = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3852 }
3853 }
3854 }
3855
3856 if ( !exteriorRing )
3857 return QVariant();
3858
3859 polygon->setExteriorRing( exteriorRing->segmentize() );
3860
3861
3862 for ( int i = 1; i < values.count(); ++i )
3863 {
3864 QgsGeometry ringGeom = QgsExpressionUtils::getGeometry( values.at( i ), parent );
3865 if ( ringGeom.isNull() )
3866 continue;
3867
3868 if ( ringGeom.type() != Qgis::GeometryType::Line || ringGeom.isNull() )
3869 continue;
3870
3871 const QgsCurve *ring = qgsgeometry_cast< QgsCurve * >( ringGeom.constGet() );
3872 if ( !ring && ringGeom.isMultipart() )
3873 {
3874 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( ringGeom.constGet() ) )
3875 {
3876 if ( collection->numGeometries() == 1 )
3877 {
3878 ring = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3879 }
3880 }
3881 }
3882
3883 if ( !ring )
3884 continue;
3885
3886 polygon->addInteriorRing( ring->segmentize() );
3887 }
3888
3889 return QVariant::fromValue( QgsGeometry( std::move( polygon ) ) );
3890}
3891
3892static QVariant fcnMakeTriangle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3893{
3894 auto tr = std::make_unique<QgsTriangle>();
3895 auto lineString = std::make_unique<QgsLineString>();
3896 lineString->clear();
3897
3898 for ( const QVariant &value : values )
3899 {
3900 QgsGeometry geom = QgsExpressionUtils::getGeometry( value, parent );
3901 if ( geom.isNull() )
3902 return QVariant();
3903
3904 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3905 return QVariant();
3906
3907 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3908 if ( !point && geom.isMultipart() )
3909 {
3910 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3911 {
3912 if ( collection->numGeometries() == 1 )
3913 {
3914 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3915 }
3916 }
3917 }
3918
3919 if ( !point )
3920 return QVariant();
3921
3922 lineString->addVertex( *point );
3923 }
3924
3925 tr->setExteriorRing( lineString.release() );
3926
3927 return QVariant::fromValue( QgsGeometry( tr.release() ) );
3928}
3929
3930static QVariant fcnMakeCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3931{
3932 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3933 if ( geom.isNull() )
3934 return QVariant();
3935
3936 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3937 return QVariant();
3938
3939 double radius = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3940 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
3941
3942 if ( segment < 3 )
3943 {
3944 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3945 return QVariant();
3946 }
3947 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3948 if ( !point && geom.isMultipart() )
3949 {
3950 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3951 {
3952 if ( collection->numGeometries() == 1 )
3953 {
3954 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3955 }
3956 }
3957 }
3958 if ( !point )
3959 return QVariant();
3960
3961 QgsCircle circ( *point, radius );
3962 return QVariant::fromValue( QgsGeometry( circ.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3963}
3964
3965static QVariant fcnMakeEllipse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3966{
3967 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3968 if ( geom.isNull() )
3969 return QVariant();
3970
3971 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3972 return QVariant();
3973
3974 double majorAxis = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3975 double minorAxis = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3976 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3977 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 4 ), parent );
3978 if ( segment < 3 )
3979 {
3980 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3981 return QVariant();
3982 }
3983 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3984 if ( !point && geom.isMultipart() )
3985 {
3986 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3987 {
3988 if ( collection->numGeometries() == 1 )
3989 {
3990 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3991 }
3992 }
3993 }
3994 if ( !point )
3995 return QVariant();
3996
3997 QgsEllipse elp( *point, majorAxis, minorAxis, azimuth );
3998 return QVariant::fromValue( QgsGeometry( elp.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3999}
4000
4001static QVariant fcnMakeRegularPolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4002{
4003
4004 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4005 if ( pt1.isNull() )
4006 return QVariant();
4007
4008 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4009 return QVariant();
4010
4011 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4012 if ( pt2.isNull() )
4013 return QVariant();
4014
4015 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4016 return QVariant();
4017
4018 unsigned int nbEdges = static_cast<unsigned int>( QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) );
4019 if ( nbEdges < 3 )
4020 {
4021 parent->setEvalErrorString( QObject::tr( "Number of edges/sides must be greater than 2" ) );
4022 return QVariant();
4023 }
4024
4025 QgsRegularPolygon::ConstructionOption option = static_cast< QgsRegularPolygon::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4027 {
4028 parent->setEvalErrorString( QObject::tr( "Option can be 0 (inscribed) or 1 (circumscribed)" ) );
4029 return QVariant();
4030 }
4031
4032 const QgsPoint *center = qgsgeometry_cast< const QgsPoint * >( pt1.constGet() );
4033 if ( !center && pt1.isMultipart() )
4034 {
4035 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt1.constGet() ) )
4036 {
4037 if ( collection->numGeometries() == 1 )
4038 {
4039 center = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4040 }
4041 }
4042 }
4043 if ( !center )
4044 return QVariant();
4045
4046 const QgsPoint *corner = qgsgeometry_cast< const QgsPoint * >( pt2.constGet() );
4047 if ( !corner && pt2.isMultipart() )
4048 {
4049 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt2.constGet() ) )
4050 {
4051 if ( collection->numGeometries() == 1 )
4052 {
4053 corner = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4054 }
4055 }
4056 }
4057 if ( !corner )
4058 return QVariant();
4059
4060 QgsRegularPolygon rp = QgsRegularPolygon( *center, *corner, nbEdges, option );
4061
4062 return QVariant::fromValue( QgsGeometry( rp.toPolygon() ) );
4063
4064}
4065
4066static QVariant fcnMakeSquare( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4067{
4068 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4069 if ( pt1.isNull() )
4070 return QVariant();
4071 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4072 return QVariant();
4073
4074 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4075 if ( pt2.isNull() )
4076 return QVariant();
4077 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4078 return QVariant();
4079
4080 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4081 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4082 QgsQuadrilateral square = QgsQuadrilateral::squareFromDiagonal( *point1, *point2 );
4083
4084 return QVariant::fromValue( QgsGeometry( square.toPolygon() ) );
4085}
4086
4087static QVariant fcnMakeRectangleFrom3Points( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4088{
4089 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4090 if ( pt1.isNull() )
4091 return QVariant();
4092 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4093 return QVariant();
4094
4095 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4096 if ( pt2.isNull() )
4097 return QVariant();
4098 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4099 return QVariant();
4100
4101 QgsGeometry pt3 = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
4102 if ( pt3.isNull() )
4103 return QVariant();
4104 if ( pt3.type() != Qgis::GeometryType::Point || pt3.isMultipart() )
4105 return QVariant();
4106
4107 QgsQuadrilateral::ConstructionOption option = static_cast< QgsQuadrilateral::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4108 if ( ( option < QgsQuadrilateral::Distance ) || ( option > QgsQuadrilateral::Projected ) )
4109 {
4110 parent->setEvalErrorString( QObject::tr( "Option can be 0 (distance) or 1 (projected)" ) );
4111 return QVariant();
4112 }
4113 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4114 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4115 const QgsPoint *point3 = qgsgeometry_cast< const QgsPoint *>( pt3.constGet() );
4116 QgsQuadrilateral rect = QgsQuadrilateral::rectangleFrom3Points( *point1, *point2, *point3, option );
4117 return QVariant::fromValue( QgsGeometry( rect.toPolygon() ) );
4118}
4119
4120static QVariant pointAt( const QgsGeometry &geom, int idx, QgsExpression *parent ) // helper function
4121{
4122 if ( geom.isNull() )
4123 return QVariant();
4124
4125 if ( idx < 0 )
4126 {
4127 idx += geom.constGet()->nCoordinates();
4128 }
4129 if ( idx < 0 || idx >= geom.constGet()->nCoordinates() )
4130 {
4131 parent->setEvalErrorString( QObject::tr( "Index is out of range" ) );
4132 return QVariant();
4133 }
4134 return QVariant::fromValue( geom.vertexAt( idx ) );
4135}
4136
4137// function used for the old $ style
4138static QVariant fcnOldXat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4139{
4140 FEAT_FROM_CONTEXT( context, feature )
4141 const QgsGeometry geom = feature.geometry();
4142 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4143
4144 const QVariant v = pointAt( geom, idx, parent );
4145
4146 if ( !v.isNull() )
4147 return QVariant( v.value<QgsPoint>().x() );
4148 else
4149 return QVariant();
4150}
4151static QVariant fcnXat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4152{
4153 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))
4154 {
4155 return fcnOldXat( values, f, parent, node );
4156 }
4157 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)
4158 {
4159 return fcnOldXat( QVariantList() << values[1], f, parent, node );
4160 }
4161
4162 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4163 if ( geom.isNull() )
4164 {
4165 return QVariant();
4166 }
4167
4168 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4169
4170 const QVariant v = pointAt( geom, vertexNumber, parent );
4171 if ( !v.isNull() )
4172 return QVariant( v.value<QgsPoint>().x() );
4173 else
4174 return QVariant();
4175}
4176
4177// function used for the old $ style
4178static QVariant fcnOldYat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4179{
4180 FEAT_FROM_CONTEXT( context, feature )
4181 const QgsGeometry geom = feature.geometry();
4182 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4183
4184 const QVariant v = pointAt( geom, idx, parent );
4185
4186 if ( !v.isNull() )
4187 return QVariant( v.value<QgsPoint>().y() );
4188 else
4189 return QVariant();
4190}
4191static QVariant fcnYat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4192{
4193 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))
4194 {
4195 return fcnOldYat( values, f, parent, node );
4196 }
4197 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)
4198 {
4199 return fcnOldYat( QVariantList() << values[1], f, parent, node );
4200 }
4201
4202 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4203 if ( geom.isNull() )
4204 {
4205 return QVariant();
4206 }
4207
4208 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4209
4210 const QVariant v = pointAt( geom, vertexNumber, parent );
4211 if ( !v.isNull() )
4212 return QVariant( v.value<QgsPoint>().y() );
4213 else
4214 return QVariant();
4215}
4216
4217static QVariant fcnZat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4218{
4219 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4220 if ( geom.isNull() )
4221 {
4222 return QVariant();
4223 }
4224
4225 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4226
4227 const QVariant v = pointAt( geom, vertexNumber, parent );
4228 if ( !v.isNull() && v.value<QgsPoint>().is3D() )
4229 return QVariant( v.value<QgsPoint>().z() );
4230 else
4231 return QVariant();
4232}
4233
4234static QVariant fcnMat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4235{
4236 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4237 if ( geom.isNull() )
4238 {
4239 return QVariant();
4240 }
4241
4242 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4243
4244 const QVariant v = pointAt( geom, vertexNumber, parent );
4245 if ( !v.isNull() && v.value<QgsPoint>().isMeasure() )
4246 return QVariant( v.value<QgsPoint>().m() );
4247 else
4248 return QVariant();
4249}
4250
4251
4252static QVariant fcnGeometry( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
4253{
4254 if ( !context )
4255 return QVariant();
4256
4257 // prefer geometry from context if it's present, otherwise fallback to context's feature's geometry
4258 if ( context->hasGeometry() )
4259 return context->geometry();
4260 else
4261 {
4262 FEAT_FROM_CONTEXT( context, f )
4263 QgsGeometry geom = f.geometry();
4264 if ( !geom.isNull() )
4265 return QVariant::fromValue( geom );
4266 else
4267 return QVariant();
4268 }
4269}
4270
4271static QVariant fcnGeomFromWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4272{
4273 QString wkt = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4274 QgsGeometry geom = QgsGeometry::fromWkt( wkt );
4275 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4276 return result;
4277}
4278
4279static QVariant fcnGeomFromWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4280{
4281 const QByteArray wkb = QgsExpressionUtils::getBinaryValue( values.at( 0 ), parent );
4282 if ( wkb.isNull() )
4283 return QVariant();
4284
4285 QgsGeometry geom;
4286 geom.fromWkb( wkb );
4287 return !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4288}
4289
4290static QVariant fcnGeomFromGML( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4291{
4292 QString gml = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4293 QgsOgcUtils::Context ogcContext;
4294 if ( context )
4295 {
4296 QgsWeakMapLayerPointer mapLayerPtr {context->variable( QStringLiteral( "layer" ) ).value<QgsWeakMapLayerPointer>() };
4297 if ( mapLayerPtr )
4298 {
4299 ogcContext.layer = mapLayerPtr.data();
4300 ogcContext.transformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
4301 }
4302 }
4303 QgsGeometry geom = QgsOgcUtils::geometryFromGML( gml, ogcContext );
4304 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4305 return result;
4306}
4307
4308static QVariant fcnGeomArea( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4309{
4310 FEAT_FROM_CONTEXT( context, f )
4312 QgsDistanceArea *calc = parent->geomCalculator();
4313 if ( calc )
4314 {
4315 try
4316 {
4317 double area = calc->measureArea( f.geometry() );
4318 area = calc->convertAreaMeasurement( area, parent->areaUnits() );
4319 return QVariant( area );
4320 }
4321 catch ( QgsCsException & )
4322 {
4323 parent->setEvalErrorString( QObject::tr( "An error occurred while calculating area" ) );
4324 return QVariant();
4325 }
4326 }
4327 else
4328 {
4329 return QVariant( f.geometry().area() );
4330 }
4331}
4332
4333static QVariant fcnArea( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4334{
4335 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4336
4337 if ( geom.type() != Qgis::GeometryType::Polygon )
4338 return QVariant();
4339
4340 return QVariant( geom.area() );
4341}
4342
4343static QVariant fcnGeomLength( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4344{
4345 FEAT_FROM_CONTEXT( context, f )
4347 QgsDistanceArea *calc = parent->geomCalculator();
4348 if ( calc )
4349 {
4350 try
4351 {
4352 double len = calc->measureLength( f.geometry() );
4353 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4354 return QVariant( len );
4355 }
4356 catch ( QgsCsException & )
4357 {
4358 parent->setEvalErrorString( QObject::tr( "An error occurred while calculating length" ) );
4359 return QVariant();
4360 }
4361 }
4362 else
4363 {
4364 return QVariant( f.geometry().length() );
4365 }
4366}
4367
4368static QVariant fcnGeomPerimeter( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4369{
4370 FEAT_FROM_CONTEXT( context, f )
4372 QgsDistanceArea *calc = parent->geomCalculator();
4373 if ( calc )
4374 {
4375 try
4376 {
4377 double len = calc->measurePerimeter( f.geometry() );
4378 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4379 return QVariant( len );
4380 }
4381 catch ( QgsCsException & )
4382 {
4383 parent->setEvalErrorString( QObject::tr( "An error occurred while calculating perimeter" ) );
4384 return QVariant();
4385 }
4386 }
4387 else
4388 {
4389 return f.geometry().isNull() ? QVariant( 0 ) : QVariant( f.geometry().constGet()->perimeter() );
4390 }
4391}
4392
4393static QVariant fcnPerimeter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4394{
4395 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4396
4397 if ( geom.type() != Qgis::GeometryType::Polygon )
4398 return QVariant();
4399
4400 //length for polygons = perimeter
4401 return QVariant( geom.length() );
4402}
4403
4404static QVariant fcnGeomNumPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4405{
4406 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4407 return QVariant( geom.isNull() ? 0 : geom.constGet()->nCoordinates() );
4408}
4409
4410static QVariant fcnGeomNumGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4411{
4412 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4413 if ( geom.isNull() )
4414 return QVariant();
4415
4416 return QVariant( geom.constGet()->partCount() );
4417}
4418
4419static QVariant fcnGeomIsMultipart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4420{
4421 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4422 if ( geom.isNull() )
4423 return QVariant();
4424
4425 return QVariant( geom.isMultipart() );
4426}
4427
4428static QVariant fcnGeomNumInteriorRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4429{
4430 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4431
4432 if ( geom.isNull() )
4433 return QVariant();
4434
4435 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4436 if ( curvePolygon )
4437 return QVariant( curvePolygon->numInteriorRings() );
4438
4439 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4440 if ( collection )
4441 {
4442 //find first CurvePolygon in collection
4443 for ( int i = 0; i < collection->numGeometries(); ++i )
4444 {
4445 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon *>( collection->geometryN( i ) );
4446 if ( !curvePolygon )
4447 continue;
4448
4449 return QVariant( curvePolygon->isEmpty() ? 0 : curvePolygon->numInteriorRings() );
4450 }
4451 }
4452
4453 return QVariant();
4454}
4455
4456static QVariant fcnGeomNumRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4457{
4458 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4459
4460 if ( geom.isNull() )
4461 return QVariant();
4462
4463 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4464 if ( curvePolygon )
4465 return QVariant( curvePolygon->ringCount() );
4466
4467 bool foundPoly = false;
4468 int ringCount = 0;
4469 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4470 if ( collection )
4471 {
4472 //find CurvePolygons in collection
4473 for ( int i = 0; i < collection->numGeometries(); ++i )
4474 {
4475 curvePolygon = qgsgeometry_cast< QgsCurvePolygon *>( collection->geometryN( i ) );
4476 if ( !curvePolygon )
4477 continue;
4478
4479 foundPoly = true;
4480 ringCount += curvePolygon->ringCount();
4481 }
4482 }
4483
4484 if ( !foundPoly )
4485 return QVariant();
4486
4487 return QVariant( ringCount );
4488}
4489
4490static QVariant fcnBounds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4491{
4492 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4493 QgsGeometry geomBounds = QgsGeometry::fromRect( geom.boundingBox() );
4494 QVariant result = !geomBounds.isNull() ? QVariant::fromValue( geomBounds ) : QVariant();
4495 return result;
4496}
4497
4498static QVariant fcnBoundsWidth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4499{
4500 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4501 return QVariant::fromValue( geom.boundingBox().width() );
4502}
4503
4504static QVariant fcnBoundsHeight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4505{
4506 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4507 return QVariant::fromValue( geom.boundingBox().height() );
4508}
4509
4510static QVariant fcnGeometryType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4511{
4512 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4513 if ( geom.isNull() )
4514 return QVariant();
4515
4517}
4518
4519static QVariant fcnXMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4520{
4521 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4522 return QVariant::fromValue( geom.boundingBox().xMinimum() );
4523}
4524
4525static QVariant fcnXMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4526{
4527 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4528 return QVariant::fromValue( geom.boundingBox().xMaximum() );
4529}
4530
4531static QVariant fcnYMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4532{
4533 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4534 return QVariant::fromValue( geom.boundingBox().yMinimum() );
4535}
4536
4537static QVariant fcnYMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4538{
4539 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4540 return QVariant::fromValue( geom.boundingBox().yMaximum() );
4541}
4542
4543static QVariant fcnZMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4544{
4545 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4546
4547 if ( geom.isNull() || geom.isEmpty( ) )
4548 return QVariant();
4549
4550 if ( !geom.constGet()->is3D() )
4551 return QVariant();
4552
4553 double max = std::numeric_limits< double >::lowest();
4554
4555 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4556 {
4557 double z = ( *it ).z();
4558
4559 if ( max < z )
4560 max = z;
4561 }
4562
4563 if ( max == std::numeric_limits< double >::lowest() )
4564 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4565
4566 return QVariant( max );
4567}
4568
4569static QVariant fcnZMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4570{
4571 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4572
4573 if ( geom.isNull() || geom.isEmpty() )
4574 return QVariant();
4575
4576 if ( !geom.constGet()->is3D() )
4577 return QVariant();
4578
4579 double min = std::numeric_limits< double >::max();
4580
4581 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4582 {
4583 double z = ( *it ).z();
4584
4585 if ( z < min )
4586 min = z;
4587 }
4588
4589 if ( min == std::numeric_limits< double >::max() )
4590 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4591
4592 return QVariant( min );
4593}
4594
4595static QVariant fcnMMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4596{
4597 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4598
4599 if ( geom.isNull() || geom.isEmpty() )
4600 return QVariant();
4601
4602 if ( !geom.constGet()->isMeasure() )
4603 return QVariant();
4604
4605 double min = std::numeric_limits< double >::max();
4606
4607 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4608 {
4609 double m = ( *it ).m();
4610
4611 if ( m < min )
4612 min = m;
4613 }
4614
4615 if ( min == std::numeric_limits< double >::max() )
4616 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4617
4618 return QVariant( min );
4619}
4620
4621static QVariant fcnMMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4622{
4623 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4624
4625 if ( geom.isNull() || geom.isEmpty() )
4626 return QVariant();
4627
4628 if ( !geom.constGet()->isMeasure() )
4629 return QVariant();
4630
4631 double max = std::numeric_limits< double >::lowest();
4632
4633 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4634 {
4635 double m = ( *it ).m();
4636
4637 if ( max < m )
4638 max = m;
4639 }
4640
4641 if ( max == std::numeric_limits< double >::lowest() )
4642 return QgsVariantUtils::createNullVariant( QMetaType::Type::Double );
4643
4644 return QVariant( max );
4645}
4646
4647static QVariant fcnSinuosity( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4648{
4649 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4650 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom.constGet() );
4651 if ( !curve )
4652 {
4653 parent->setEvalErrorString( QObject::tr( "Function `sinuosity` requires a line geometry." ) );
4654 return QVariant();
4655 }
4656
4657 return QVariant( curve->sinuosity() );
4658}
4659
4660static QVariant fcnStraightDistance2d( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4661{
4662 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4663 const QgsCurve *curve = geom.constGet() ? qgsgeometry_cast< const QgsCurve * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4664 if ( !curve )
4665 {
4666 parent->setEvalErrorString( QObject::tr( "Function `straight_distance_2d` requires a line geometry or a multi line geometry with a single part." ) );
4667 return QVariant();
4668 }
4669
4670 return QVariant( curve->straightDistance2d() );
4671}
4672
4673static QVariant fcnRoundness( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4674{
4675 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4676 const QgsCurvePolygon *poly = geom.constGet() ? qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4677
4678 if ( !poly )
4679 {
4680 parent->setEvalErrorString( QObject::tr( "Function `roundness` requires a polygon geometry or a multi polygon geometry with a single part." ) );
4681 return QVariant();
4682 }
4683
4684 return QVariant( poly->roundness() );
4685}
4686
4687
4688
4689static QVariant fcnFlipCoordinates( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4690{
4691 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4692 if ( geom.isNull() )
4693 return QVariant();
4694
4695 std::unique_ptr< QgsAbstractGeometry > flipped( geom.constGet()->clone() );
4696 flipped->swapXy();
4697 return QVariant::fromValue( QgsGeometry( std::move( flipped ) ) );
4698}
4699
4700static QVariant fcnIsClosed( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4701{
4702 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4703 if ( fGeom.isNull() )
4704 return QVariant();
4705
4706 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( fGeom.constGet() );
4707 if ( !curve && fGeom.isMultipart() )
4708 {
4709 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4710 {
4711 if ( collection->numGeometries() == 1 )
4712 {
4713 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
4714 }
4715 }
4716 }
4717
4718 if ( !curve )
4719 return QVariant();
4720
4721 return QVariant::fromValue( curve->isClosed() );
4722}
4723
4724static QVariant fcnCloseLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4725{
4726 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4727
4728 if ( geom.isNull() )
4729 return QVariant();
4730
4731 QVariant result;
4732 if ( !geom.isMultipart() )
4733 {
4734 const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( geom.constGet() );
4735
4736 if ( !line )
4737 return QVariant();
4738
4739 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4740 closedLine->close();
4741
4742 result = QVariant::fromValue( QgsGeometry( std::move( closedLine ) ) );
4743 }
4744 else
4745 {
4746 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( geom.constGet() );
4747
4748 std::unique_ptr< QgsGeometryCollection > closed( collection->createEmptyWithSameType() );
4749
4750 for ( int i = 0; i < collection->numGeometries(); ++i )
4751 {
4752 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( collection->geometryN( i ) ) )
4753 {
4754 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4755 closedLine->close();
4756
4757 closed->addGeometry( closedLine.release() );
4758 }
4759 }
4760 result = QVariant::fromValue( QgsGeometry( std::move( closed ) ) );
4761 }
4762
4763 return result;
4764}
4765
4766static QVariant fcnIsEmpty( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4767{
4768 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4769 if ( fGeom.isNull() )
4770 return QVariant();
4771
4772 return QVariant::fromValue( fGeom.isEmpty() );
4773}
4774
4775static QVariant fcnIsEmptyOrNull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4776{
4777 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
4778 return QVariant::fromValue( true );
4779
4780 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4781 return QVariant::fromValue( fGeom.isNull() || fGeom.isEmpty() );
4782}
4783
4784static QVariant fcnRelate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4785{
4786 if ( values.length() < 2 || values.length() > 3 )
4787 return QVariant();
4788
4789 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4790 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4791
4792 if ( fGeom.isNull() || sGeom.isNull() )
4793 return QVariant();
4794
4795 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( fGeom.constGet() ) );
4796
4797 if ( values.length() == 2 )
4798 {
4799 //two geometry arguments, return relation
4800 QString result = engine->relate( sGeom.constGet() );
4801 return QVariant::fromValue( result );
4802 }
4803 else
4804 {
4805 //three arguments, test pattern
4806 QString pattern = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
4807 bool result = engine->relatePattern( sGeom.constGet(), pattern );
4808 return QVariant::fromValue( result );
4809 }
4810}
4811
4812static QVariant fcnBbox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4813{
4814 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4815 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4816 return fGeom.intersects( sGeom.boundingBox() ) ? TVL_True : TVL_False;
4817}
4818static QVariant fcnDisjoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4819{
4820 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4821 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4822 return fGeom.disjoint( sGeom ) ? TVL_True : TVL_False;
4823}
4824static QVariant fcnIntersects( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4825{
4826 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4827 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4828 return fGeom.intersects( sGeom ) ? TVL_True : TVL_False;
4829}
4830static QVariant fcnTouches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4831{
4832 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4833 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4834 return fGeom.touches( sGeom ) ? TVL_True : TVL_False;
4835}
4836static QVariant fcnCrosses( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4837{
4838 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4839 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4840 return fGeom.crosses( sGeom ) ? TVL_True : TVL_False;
4841}
4842static QVariant fcnContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4843{
4844 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4845 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4846 return fGeom.contains( sGeom ) ? TVL_True : TVL_False;
4847}
4848static QVariant fcnOverlaps( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4849{
4850 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4851 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4852 return fGeom.overlaps( sGeom ) ? TVL_True : TVL_False;
4853}
4854static QVariant fcnWithin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4855{
4856 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4857 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4858 return fGeom.within( sGeom ) ? TVL_True : TVL_False;
4859}
4860
4861static QVariant fcnBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4862{
4863 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4864 const double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4865 const int seg = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4866 const QString endCapString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
4867 const QString joinString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
4868 const double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
4869
4871 if ( endCapString.compare( QLatin1String( "flat" ), Qt::CaseInsensitive ) == 0 )
4872 capStyle = Qgis::EndCapStyle::Flat;
4873 else if ( endCapString.compare( QLatin1String( "square" ), Qt::CaseInsensitive ) == 0 )
4874 capStyle = Qgis::EndCapStyle::Square;
4875
4877 if ( joinString.compare( QLatin1String( "miter" ), Qt::CaseInsensitive ) == 0 )
4878 joinStyle = Qgis::JoinStyle::Miter;
4879 else if ( joinString.compare( QLatin1String( "bevel" ), Qt::CaseInsensitive ) == 0 )
4880 joinStyle = Qgis::JoinStyle::Bevel;
4881
4882 QgsGeometry geom = fGeom.buffer( dist, seg, capStyle, joinStyle, miterLimit );
4883 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4884 return result;
4885}
4886
4887static QVariant fcnForceRHR( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4888{
4889 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4890 const QgsGeometry reoriented = fGeom.forceRHR();
4891 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4892}
4893
4894static QVariant fcnForcePolygonCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4895{
4896 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4897 const QgsGeometry reoriented = fGeom.forcePolygonClockwise();
4898 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4899}
4900
4901static QVariant fcnForcePolygonCCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4902{
4903 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4904 const QgsGeometry reoriented = fGeom.forcePolygonCounterClockwise();
4905 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4906}
4907
4908static QVariant fcnWedgeBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4909{
4910 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4911 const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( fGeom.constGet() );
4912 if ( !pt && fGeom.isMultipart() )
4913 {
4914 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4915 {
4916 if ( collection->numGeometries() == 1 )
4917 {
4918 pt = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4919 }
4920 }
4921 }
4922
4923 if ( !pt )
4924 {
4925 parent->setEvalErrorString( QObject::tr( "Function `wedge_buffer` requires a point value for the center." ) );
4926 return QVariant();
4927 }
4928
4929 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4930 double width = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4931 double outerRadius = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4932 double innerRadius = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
4933
4934 QgsGeometry geom = QgsGeometry::createWedgeBuffer( *pt, azimuth, width, outerRadius, innerRadius );
4935 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4936 return result;
4937}
4938
4939static QVariant fcnTaperedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4940{
4941 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4942 if ( fGeom.type() != Qgis::GeometryType::Line )
4943 {
4944 parent->setEvalErrorString( QObject::tr( "Function `tapered_buffer` requires a line geometry." ) );
4945 return QVariant();
4946 }
4947
4948 double startWidth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4949 double endWidth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4950 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4951
4952 QgsGeometry geom = fGeom.taperedBuffer( startWidth, endWidth, segments );
4953 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4954 return result;
4955}
4956
4957static QVariant fcnBufferByM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4958{
4959 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4960 if ( fGeom.type() != Qgis::GeometryType::Line )
4961 {
4962 parent->setEvalErrorString( QObject::tr( "Function `buffer_by_m` requires a line geometry." ) );
4963 return QVariant();
4964 }
4965
4966 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) );
4967
4968 QgsGeometry geom = fGeom.variableWidthBufferByM( segments );
4969 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4970 return result;
4971}
4972
4973static QVariant fcnOffsetCurve( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4974{
4975 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4976 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4977 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4978 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4979 if ( joinInt < 1 || joinInt > 3 )
4980 return QVariant();
4981 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
4982
4983 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4984
4985 QgsGeometry geom = fGeom.offsetCurve( dist, segments, join, miterLimit );
4986 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4987 return result;
4988}
4989
4990static QVariant fcnSingleSidedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4991{
4992 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4993 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4994 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4995
4996 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4997 if ( joinInt < 1 || joinInt > 3 )
4998 return QVariant();
4999 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
5000
5001 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5002
5003 QgsGeometry geom = fGeom.singleSidedBuffer( dist, segments, Qgis::BufferSide::Left, join, miterLimit );
5004 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5005 return result;
5006}
5007
5008static QVariant fcnExtend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5009{
5010 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5011 double distStart = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5012 double distEnd = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5013
5014 QgsGeometry geom = fGeom.extendLine( distStart, distEnd );
5015 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5016 return result;
5017}
5018
5019static QVariant fcnTranslate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5020{
5021 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5022 double dx = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5023 double dy = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5024 fGeom.translate( dx, dy );
5025 return QVariant::fromValue( fGeom );
5026}
5027
5028static QVariant fcnRotate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5029{
5030 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5031 const double rotation = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5032 const QgsGeometry center = values.at( 2 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 2 ), parent )
5033 : QgsGeometry();
5034 const bool perPart = values.value( 3 ).toBool();
5035
5036 if ( center.isNull() && perPart && fGeom.isMultipart() )
5037 {
5038 // no explicit center, rotating per part
5039 // (note that we only do this branch for multipart geometries -- for singlepart geometries
5040 // the result is equivalent to setting perPart as false anyway)
5041 std::unique_ptr< QgsGeometryCollection > collection( qgsgeometry_cast< QgsGeometryCollection * >( fGeom.constGet()->clone() ) );
5042 for ( auto it = collection->parts_begin(); it != collection->parts_end(); ++it )
5043 {
5044 const QgsPointXY partCenter = ( *it )->boundingBox().center();
5045 QTransform t = QTransform::fromTranslate( partCenter.x(), partCenter.y() );
5046 t.rotate( -rotation );
5047 t.translate( -partCenter.x(), -partCenter.y() );
5048 ( *it )->transform( t );
5049 }
5050 return QVariant::fromValue( QgsGeometry( std::move( collection ) ) );
5051 }
5052 else
5053 {
5054 QgsPointXY pt;
5055 if ( center.isEmpty() )
5056 {
5057 // if center wasn't specified, use bounding box centroid
5058 pt = fGeom.boundingBox().center();
5059 }
5061 {
5062 parent->setEvalErrorString( QObject::tr( "Function 'rotate' requires a point value for the center" ) );
5063 return QVariant();
5064 }
5065 else
5066 {
5067 pt = QgsPointXY( *qgsgeometry_cast< const QgsPoint * >( center.constGet()->simplifiedTypeRef() ) );
5068 }
5069
5070 fGeom.rotate( rotation, pt );
5071 return QVariant::fromValue( fGeom );
5072 }
5073}
5074
5075static QVariant fcnScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5076{
5077 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5078 const double xScale = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5079 const double yScale = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5080 const QgsGeometry center = values.at( 3 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 3 ), parent )
5081 : QgsGeometry();
5082
5083 QgsPointXY pt;
5084 if ( center.isNull() )
5085 {
5086 // if center wasn't specified, use bounding box centroid
5087 pt = fGeom.boundingBox().center();
5088 }
5090 {
5091 parent->setEvalErrorString( QObject::tr( "Function 'scale' requires a point value for the center" ) );
5092 return QVariant();
5093 }
5094 else
5095 {
5096 pt = center.asPoint();
5097 }
5098
5099 QTransform t = QTransform::fromTranslate( pt.x(), pt.y() );
5100 t.scale( xScale, yScale );
5101 t.translate( -pt.x(), -pt.y() );
5102 fGeom.transform( t );
5103 return QVariant::fromValue( fGeom );
5104}
5105
5106static QVariant fcnAffineTransform( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5107{
5108 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5109 if ( fGeom.isNull() )
5110 {
5111 return QVariant();
5112 }
5113
5114 const double deltaX = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5115 const double deltaY = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5116
5117 const double rotationZ = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5118
5119 const double scaleX = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
5120 const double scaleY = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
5121
5122 const double deltaZ = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
5123 const double deltaM = QgsExpressionUtils::getDoubleValue( values.at( 7 ), parent );
5124 const double scaleZ = QgsExpressionUtils::getDoubleValue( values.at( 8 ), parent );
5125 const double scaleM = QgsExpressionUtils::getDoubleValue( values.at( 9 ), parent );
5126
5127 if ( deltaZ != 0.0 && !fGeom.constGet()->is3D() )
5128 {
5129 fGeom.get()->addZValue( 0 );
5130 }
5131 if ( deltaM != 0.0 && !fGeom.constGet()->isMeasure() )
5132 {
5133 fGeom.get()->addMValue( 0 );
5134 }
5135
5136 QTransform transform;
5137 transform.translate( deltaX, deltaY );
5138 transform.rotate( rotationZ );
5139 transform.scale( scaleX, scaleY );
5140 fGeom.transform( transform, deltaZ, scaleZ, deltaM, scaleM );
5141
5142 return QVariant::fromValue( fGeom );
5143}
5144
5145
5146static QVariant fcnCentroid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5147{
5148 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5149 QgsGeometry geom = fGeom.centroid();
5150 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5151 return result;
5152}
5153static QVariant fcnPointOnSurface( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5154{
5155 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5156 QgsGeometry geom = fGeom.pointOnSurface();
5157 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5158 return result;
5159}
5160
5161static QVariant fcnPoleOfInaccessibility( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5162{
5163 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5164 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5165 QgsGeometry geom = fGeom.poleOfInaccessibility( tolerance );
5166 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5167 return result;
5168}
5169
5170static QVariant fcnConvexHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5171{
5172 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5173 QgsGeometry geom = fGeom.convexHull();
5174 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5175 return result;
5176}
5177
5178#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
5179static QVariant fcnConcaveHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5180{
5181 try
5182 {
5183 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5184 const double targetPercent = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5185 const bool allowHoles = values.value( 2 ).toBool();
5186 QgsGeometry geom = fGeom.concaveHull( targetPercent, allowHoles );
5187 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5188 return result;
5189 }
5190 catch ( QgsCsException &cse )
5191 {
5192 QgsMessageLog::logMessage( QObject::tr( "Error caught in concave_hull() function: %1" ).arg( cse.what() ) );
5193 return QVariant();
5194 }
5195}
5196#endif
5197
5198static QVariant fcnMinimalCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5199{
5200 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5201 int segments = 36;
5202 if ( values.length() == 2 )
5203 segments = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5204 if ( segments < 0 )
5205 {
5206 parent->setEvalErrorString( QObject::tr( "Parameter can not be negative." ) );
5207 return QVariant();
5208 }
5209
5210 QgsGeometry geom = fGeom.minimalEnclosingCircle( static_cast<unsigned int>( segments ) );
5211 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5212 return result;
5213}
5214
5215static QVariant fcnOrientedBBox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5216{
5217 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5219 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5220 return result;
5221}
5222
5223static QVariant fcnMainAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5224{
5225 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5226
5227 // we use the angle of the oriented minimum bounding box to calculate the polygon main angle.
5228 // While ArcGIS uses a different approach ("the angle of longest collection of segments that have similar orientation"), this
5229 // yields similar results to OMBB approach under the same constraints ("this tool is meant for primarily orthogonal polygons rather than organically shaped ones.")
5230
5231 double area, angle, width, height;
5232 const QgsGeometry geom = fGeom.orientedMinimumBoundingBox( area, angle, width, height );
5233
5234 if ( geom.isNull() )
5235 {
5236 parent->setEvalErrorString( QObject::tr( "Error calculating polygon main angle: %1" ).arg( geom.lastError() ) );
5237 return QVariant();
5238 }
5239 return angle;
5240}
5241
5242static QVariant fcnDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5243{
5244 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5245 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5246 QgsGeometry geom = fGeom.difference( sGeom );
5247 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5248 return result;
5249}
5250
5251static QVariant fcnReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5252{
5253 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5254 if ( fGeom.isNull() )
5255 return QVariant();
5256
5257 QVariant result;
5258 if ( !fGeom.isMultipart() )
5259 {
5260 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( fGeom.constGet() );
5261 if ( !curve )
5262 return QVariant();
5263
5264 QgsCurve *reversed = curve->reversed();
5265 result = reversed ? QVariant::fromValue( QgsGeometry( reversed ) ) : QVariant();
5266 }
5267 else
5268 {
5269 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( fGeom.constGet() );
5270 std::unique_ptr< QgsGeometryCollection > reversed( collection->createEmptyWithSameType() );
5271 for ( int i = 0; i < collection->numGeometries(); ++i )
5272 {
5273 if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( collection->geometryN( i ) ) )
5274 {
5275 reversed->addGeometry( curve->reversed() );
5276 }
5277 else
5278 {
5279 reversed->addGeometry( collection->geometryN( i )->clone() );
5280 }
5281 }
5282 result = reversed ? QVariant::fromValue( QgsGeometry( std::move( reversed ) ) ) : QVariant();
5283 }
5284 return result;
5285}
5286
5287static QVariant fcnExteriorRing( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5288{
5289 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5290 if ( fGeom.isNull() )
5291 return QVariant();
5292
5293 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( fGeom.constGet() );
5294 if ( !curvePolygon && fGeom.isMultipart() )
5295 {
5296 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
5297 {
5298 if ( collection->numGeometries() == 1 )
5299 {
5300 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
5301 }
5302 }
5303 }
5304
5305 if ( !curvePolygon || !curvePolygon->exteriorRing() )
5306 return QVariant();
5307
5308 QgsCurve *exterior = static_cast< QgsCurve * >( curvePolygon->exteriorRing()->clone() );
5309 QVariant result = exterior ? QVariant::fromValue( QgsGeometry( exterior ) ) : QVariant();
5310 return result;
5311}
5312
5313static QVariant fcnDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5314{
5315 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5316 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5317 return QVariant( fGeom.distance( sGeom ) );
5318}
5319
5320static QVariant fcnHausdorffDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5321{
5322 QgsGeometry g1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5323 QgsGeometry g2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5324
5325 double res = -1;
5326 if ( values.length() == 3 && values.at( 2 ).isValid() )
5327 {
5328 double densify = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5329 densify = std::clamp( densify, 0.0, 1.0 );
5330 res = g1.hausdorffDistanceDensify( g2, densify );
5331 }
5332 else
5333 {
5334 res = g1.hausdorffDistance( g2 );
5335 }
5336
5337 return res > -1 ? QVariant( res ) : QVariant();
5338}
5339
5340static QVariant fcnIntersection( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5341{
5342 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5343 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5344 QgsGeometry geom = fGeom.intersection( sGeom );
5345 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5346 return result;
5347}
5348static QVariant fcnSymDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5349{
5350 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5351 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5352 QgsGeometry geom = fGeom.symDifference( sGeom );
5353 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5354 return result;
5355}
5356static QVariant fcnCombine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5357{
5358 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5359 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5360 QgsGeometry geom = fGeom.combine( sGeom );
5361 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5362 return result;
5363}
5364
5365static QVariant fcnGeomToWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5366{
5367 if ( values.length() < 1 || values.length() > 2 )
5368 return QVariant();
5369
5370 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5371 int prec = 8;
5372 if ( values.length() == 2 )
5373 prec = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5374 QString wkt = fGeom.asWkt( prec );
5375 return QVariant( wkt );
5376}
5377
5378static QVariant fcnGeomToWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5379{
5380 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5381 return fGeom.isNull() ? QVariant() : QVariant( fGeom.asWkb() );
5382}
5383
5384static QVariant fcnAzimuth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5385{
5386 if ( values.length() != 2 )
5387 {
5388 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires exactly two parameters. %n given.", nullptr, values.length() ) );
5389 return QVariant();
5390 }
5391
5392 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5393 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5394
5395 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5396 if ( !pt1 && fGeom1.isMultipart() )
5397 {
5398 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5399 {
5400 if ( collection->numGeometries() == 1 )
5401 {
5402 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5403 }
5404 }
5405 }
5406
5407 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5408 if ( !pt2 && fGeom2.isMultipart() )
5409 {
5410 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5411 {
5412 if ( collection->numGeometries() == 1 )
5413 {
5414 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5415 }
5416 }
5417 }
5418
5419 if ( !pt1 || !pt2 )
5420 {
5421 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires two points as arguments." ) );
5422 return QVariant();
5423 }
5424
5425 // Code from PostGIS
5426 if ( qgsDoubleNear( pt1->x(), pt2->x() ) )
5427 {
5428 if ( pt1->y() < pt2->y() )
5429 return 0.0;
5430 else if ( pt1->y() > pt2->y() )
5431 return M_PI;
5432 else
5433 return 0;
5434 }
5435
5436 if ( qgsDoubleNear( pt1->y(), pt2->y() ) )
5437 {
5438 if ( pt1->x() < pt2->x() )
5439 return M_PI_2;
5440 else if ( pt1->x() > pt2->x() )
5441 return M_PI + ( M_PI_2 );
5442 else
5443 return 0;
5444 }
5445
5446 if ( pt1->x() < pt2->x() )
5447 {
5448 if ( pt1->y() < pt2->y() )
5449 {
5450 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) );
5451 }
5452 else /* ( pt1->y() > pt2->y() ) - equality case handled above */
5453 {
5454 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5455 + ( M_PI_2 );
5456 }
5457 }
5458
5459 else /* ( pt1->x() > pt2->x() ) - equality case handled above */
5460 {
5461 if ( pt1->y() > pt2->y() )
5462 {
5463 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) )
5464 + M_PI;
5465 }
5466 else /* ( pt1->y() < pt2->y() ) - equality case handled above */
5467 {
5468 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5469 + ( M_PI + ( M_PI_2 ) );
5470 }
5471 }
5472}
5473
5474static QVariant fcnBearing( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5475{
5476 const QgsGeometry geom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5477 const QgsGeometry geom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5478 QgsCoordinateReferenceSystem sourceCrs = QgsExpressionUtils::getCrsValue( values.at( 2 ), parent );
5479 QString ellipsoid = QgsExpressionUtils::getStringValue( values.at( 3 ), parent );
5480
5481 if ( geom1.isNull() || geom2.isNull() || geom1.type() != Qgis::GeometryType::Point || geom2.type() != Qgis::GeometryType::Point )
5482 {
5483 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires two valid point geometries." ) );
5484 return QVariant();
5485 }
5486
5487 const QgsPointXY point1 = geom1.asPoint();
5488 const QgsPointXY point2 = geom2.asPoint();
5489 if ( point1.isEmpty() || point2.isEmpty() )
5490 {
5491 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires point geometries or multi point geometries with a single part." ) );
5492 return QVariant();
5493 }
5494
5496 if ( context )
5497 {
5498 tContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
5499
5500 if ( !sourceCrs.isValid() )
5501 {
5502 sourceCrs = context->variable( QStringLiteral( "_layer_crs" ) ).value<QgsCoordinateReferenceSystem>();
5503 }
5504
5505 if ( ellipsoid.isEmpty() )
5506 {
5507 ellipsoid = context->variable( QStringLiteral( "project_ellipsoid" ) ).toString();
5508 }
5509 }
5510
5511 if ( !sourceCrs.isValid() )
5512 {
5513 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires a valid source CRS." ) );
5514 return QVariant();
5515 }
5516
5517 QgsDistanceArea da;
5518 da.setSourceCrs( sourceCrs, tContext );
5519 if ( !da.setEllipsoid( ellipsoid ) )
5520 {
5521 parent->setEvalErrorString( QObject::tr( "Function `bearing` requires a valid ellipsoid acronym or ellipsoid authority ID." ) );
5522 return QVariant();
5523 }
5524
5525 try
5526 {
5527 const double bearing = da.bearing( point1, point2 );
5528 if ( std::isfinite( bearing ) )
5529 {
5530 return std::fmod( bearing + 2 * M_PI, 2 * M_PI );
5531 }
5532 }
5533 catch ( QgsCsException &cse )
5534 {
5535 QgsMessageLog::logMessage( QObject::tr( "Error caught in bearing() function: %1" ).arg( cse.what() ) );
5536 return QVariant();
5537 }
5538 return QVariant();
5539}
5540
5541static QVariant fcnProject( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5542{
5543 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5544
5546 {
5547 parent->setEvalErrorString( QStringLiteral( "'project' requires a point geometry" ) );
5548 return QVariant();
5549 }
5550
5551 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5552 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5553 double inclination = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5554
5555 const QgsPoint *p = static_cast<const QgsPoint *>( geom.constGet()->simplifiedTypeRef( ) );
5556 QgsPoint newPoint = p->project( distance, 180.0 * azimuth / M_PI, 180.0 * inclination / M_PI );
5557
5558 return QVariant::fromValue( QgsGeometry( new QgsPoint( newPoint ) ) );
5559}
5560
5561static QVariant fcnInclination( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5562{
5563 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5564 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5565
5566 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5567 if ( !pt1 && fGeom1.isMultipart() )
5568 {
5569 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5570 {
5571 if ( collection->numGeometries() == 1 )
5572 {
5573 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5574 }
5575 }
5576 }
5577 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5578 if ( !pt2 && fGeom2.isMultipart() )
5579 {
5580 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5581 {
5582 if ( collection->numGeometries() == 1 )
5583 {
5584 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5585 }
5586 }
5587 }
5588
5589 if ( ( fGeom1.type() != Qgis::GeometryType::Point ) || ( fGeom2.type() != Qgis::GeometryType::Point ) ||
5590 !pt1 || !pt2 )
5591 {
5592 parent->setEvalErrorString( QStringLiteral( "Function 'inclination' requires two points as arguments." ) );
5593 return QVariant();
5594 }
5595
5596 return pt1->inclination( *pt2 );
5597
5598}
5599
5600static QVariant fcnExtrude( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5601{
5602 if ( values.length() != 3 )
5603 return QVariant();
5604
5605 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5606 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5607 double y = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5608
5609 QgsGeometry geom = fGeom.extrude( x, y );
5610
5611 QVariant result = geom.constGet() ? QVariant::fromValue( geom ) : QVariant();
5612 return result;
5613}
5614
5615static QVariant fcnOrderParts( const QVariantList &values, const QgsExpressionContext *ctx, QgsExpression *parent, const QgsExpressionNodeFunction * )
5616{
5617 if ( values.length() < 2 )
5618 return QVariant();
5619
5620 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5621
5622 if ( !fGeom.isMultipart() )
5623 return values.at( 0 );
5624
5625 QString expString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5626 QVariant cachedExpression;
5627 if ( ctx )
5628 cachedExpression = ctx->cachedValue( expString );
5629 QgsExpression expression;
5630
5631 if ( cachedExpression.isValid() )
5632 {
5633 expression = cachedExpression.value<QgsExpression>();
5634 }
5635 else
5636 expression = QgsExpression( expString );
5637
5638 bool asc = values.value( 2 ).toBool();
5639
5640 QgsExpressionContext *unconstedContext = nullptr;
5641 QgsFeature f;
5642 if ( ctx )
5643 {
5644 // ExpressionSorter wants a modifiable expression context, but it will return it in the same shape after
5645 // so no reason to worry
5646 unconstedContext = const_cast<QgsExpressionContext *>( ctx );
5647 f = ctx->feature();
5648 }
5649 else
5650 {
5651 // If there's no context provided, create a fake one
5652 unconstedContext = new QgsExpressionContext();
5653 }
5654
5655 const QgsGeometryCollection *collection = qgsgeometry_cast<const QgsGeometryCollection *>( fGeom.constGet() );
5656 Q_ASSERT( collection ); // Should have failed the multipart check above
5657
5659 orderBy.append( QgsFeatureRequest::OrderByClause( expression, asc ) );
5660 QgsExpressionSorter sorter( orderBy );
5661
5662 QList<QgsFeature> partFeatures;
5663 partFeatures.reserve( collection->partCount() );
5664 for ( int i = 0; i < collection->partCount(); ++i )
5665 {
5666 f.setGeometry( QgsGeometry( collection->geometryN( i )->clone() ) );
5667 partFeatures << f;
5668 }
5669
5670 sorter.sortFeatures( partFeatures, unconstedContext );
5671
5672 QgsGeometryCollection *orderedGeom = qgsgeometry_cast<QgsGeometryCollection *>( fGeom.constGet()->clone() );
5673
5674 Q_ASSERT( orderedGeom );
5675
5676 while ( orderedGeom->partCount() )
5677 orderedGeom->removeGeometry( 0 );
5678
5679 for ( const QgsFeature &feature : std::as_const( partFeatures ) )
5680 {
5681 orderedGeom->addGeometry( feature.geometry().constGet()->clone() );
5682 }
5683
5684 QVariant result = QVariant::fromValue( QgsGeometry( orderedGeom ) );
5685
5686 if ( !ctx )
5687 delete unconstedContext;
5688
5689 return result;
5690}
5691
5692static QVariant fcnClosestPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5693{
5694 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5695 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5696
5697 QgsGeometry geom = fromGeom.nearestPoint( toGeom );
5698
5699 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5700 return result;
5701}
5702
5703static QVariant fcnShortestLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5704{
5705 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5706 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5707
5708 QgsGeometry geom = fromGeom.shortestLine( toGeom );
5709
5710 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5711 return result;
5712}
5713
5714static QVariant fcnLineInterpolatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5715{
5716 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5717 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5718
5719 QgsGeometry geom = lineGeom.interpolate( distance );
5720
5721 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5722 return result;
5723}
5724
5725static QVariant fcnLineInterpolatePointByM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5726{
5727 const QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5728 const double m = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5729 const bool use3DDistance = values.at( 2 ).toBool();
5730
5731 double x, y, z, distance;
5732
5733 const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( lineGeom.constGet() );
5734 if ( !line )
5735 {
5736 return QVariant();
5737 }
5738
5739 if ( line->lineLocatePointByM( m, x, y, z, distance, use3DDistance ) )
5740 {
5741 QgsPoint point( x, y );
5742 if ( use3DDistance && QgsWkbTypes::hasZ( lineGeom.wkbType() ) )
5743 {
5744 point.addZValue( z );
5745 }
5746 return QVariant::fromValue( QgsGeometry( point.clone() ) );
5747 }
5748
5749 return QVariant();
5750}
5751
5752static QVariant fcnLineSubset( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5753{
5754 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5755 if ( lineGeom.type() != Qgis::GeometryType::Line )
5756 {
5757 parent->setEvalErrorString( QObject::tr( "line_substring requires a curve geometry input" ) );
5758 return QVariant();
5759 }
5760
5761 const QgsCurve *curve = nullptr;
5762 if ( !lineGeom.isMultipart() )
5763 curve = qgsgeometry_cast< const QgsCurve * >( lineGeom.constGet() );
5764 else
5765 {
5766 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( lineGeom.constGet() ) )
5767 {
5768 if ( collection->numGeometries() > 0 )
5769 {
5770 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
5771 }
5772 }
5773 }
5774 if ( !curve )
5775 return QVariant();
5776
5777 double startDistance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5778 double endDistance = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5779
5780 std::unique_ptr< QgsCurve > substring( curve->curveSubstring( startDistance, endDistance ) );
5781 QgsGeometry result( std::move( substring ) );
5782 return !result.isNull() ? QVariant::fromValue( result ) : QVariant();
5783}
5784
5785static QVariant fcnLineInterpolateAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5786{
5787 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5788 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5789
5790 return lineGeom.interpolateAngle( distance ) * 180.0 / M_PI;
5791}
5792
5793static QVariant fcnAngleAtVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5794{
5795 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5796 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5797 if ( vertex < 0 )
5798 {
5799 //negative idx
5800 int count = geom.constGet()->nCoordinates();
5801 vertex = count + vertex;
5802 }
5803
5804 return geom.angleAtVertex( vertex ) * 180.0 / M_PI;
5805}
5806
5807static QVariant fcnDistanceToVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5808{
5809 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5810 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5811 if ( vertex < 0 )
5812 {
5813 //negative idx
5814 int count = geom.constGet()->nCoordinates();
5815 vertex = count + vertex;
5816 }
5817
5818 return geom.distanceToVertex( vertex );
5819}
5820
5821static QVariant fcnLineLocatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5822{
5823 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5824 QgsGeometry pointGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5825
5826 double distance = lineGeom.lineLocatePoint( pointGeom );
5827
5828 return distance >= 0 ? distance : QVariant();
5829}
5830
5831static QVariant fcnLineLocateM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5832{
5833 const QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5834 const double m = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5835 const bool use3DDistance = values.at( 2 ).toBool();
5836
5837 double x, y, z, distance;
5838
5839 const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( lineGeom.constGet() );
5840 if ( !line )
5841 {
5842 return QVariant();
5843 }
5844
5845 const bool found = line->lineLocatePointByM( m, x, y, z, distance, use3DDistance );
5846 return found ? distance : QVariant();
5847}
5848
5849static QVariant fcnRound( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5850{
5851 if ( values.length() == 2 && values.at( 1 ).toInt() != 0 )
5852 {
5853 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5854 return qgsRound( number, QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
5855 }
5856
5857 if ( values.length() >= 1 )
5858 {
5859 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5860 return QVariant( qlonglong( std::round( number ) ) );
5861 }
5862
5863 return QVariant();
5864}
5865
5866static QVariant fcnPi( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5867{
5868 Q_UNUSED( values )
5869 Q_UNUSED( parent )
5870 return M_PI;
5871}
5872
5873static QVariant fcnFormatNumber( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5874{
5875 const double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5876 const int places = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5877 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5878 if ( places < 0 )
5879 {
5880 parent->setEvalErrorString( QObject::tr( "Number of places must be positive" ) );
5881 return QVariant();
5882 }
5883
5884 const bool omitGroupSeparator = values.value( 3 ).toBool();
5885 const bool trimTrailingZeros = values.value( 4 ).toBool();
5886
5887 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5888 if ( !omitGroupSeparator )
5889 locale.setNumberOptions( locale.numberOptions() & ~QLocale::NumberOption::OmitGroupSeparator );
5890 else
5891 locale.setNumberOptions( locale.numberOptions() | QLocale::NumberOption::OmitGroupSeparator );
5892
5893 QString res = locale.toString( value, 'f', places );
5894
5895 if ( trimTrailingZeros )
5896 {
5897#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5898 const QChar decimal = locale.decimalPoint();
5899 const QChar zeroDigit = locale.zeroDigit();
5900#else
5901 const QChar decimal = locale.decimalPoint().at( 0 );
5902 const QChar zeroDigit = locale.zeroDigit().at( 0 );
5903#endif
5904
5905 if ( res.contains( decimal ) )
5906 {
5907 int trimPoint = res.length() - 1;
5908
5909 while ( res.at( trimPoint ) == zeroDigit )
5910 trimPoint--;
5911
5912 if ( res.at( trimPoint ) == decimal )
5913 trimPoint--;
5914
5915 res.truncate( trimPoint + 1 );
5916 }
5917 }
5918
5919 return res;
5920}
5921
5922static QVariant fcnFormatDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5923{
5924 QDateTime datetime = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
5925 const QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5926 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5927
5928 // Convert to UTC if the format string includes a Z, as QLocale::toString() doesn't do it
5929 if ( format.indexOf( "Z" ) > 0 )
5930 datetime = datetime.toUTC();
5931
5932 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5933 return locale.toString( datetime, format );
5934}
5935
5936static QVariant fcnColorGrayscaleAverage( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5937{
5938 const QVariant variant = values.at( 0 );
5939 bool isQColor;
5940 QColor color = QgsExpressionUtils::getColorValue( variant, parent, isQColor );
5941 if ( !color.isValid() )
5942 return QVariant();
5943
5944 const float alpha = color.alphaF(); // NOLINT(bugprone-narrowing-conversions): TODO QGIS 4 remove the nolint instructions, QColor was qreal (double) and is now float
5945 if ( color.spec() == QColor::Spec::Cmyk )
5946 {
5947 const float avg = ( color.cyanF() + color.magentaF() + color.yellowF() ) / 3; // NOLINT(bugprone-narrowing-conversions): TODO QGIS 4 remove the nolint instructions, QColor was qreal (double) and is now float
5948 color = QColor::fromCmykF( avg, avg, avg, color.blackF(), alpha );
5949 }
5950 else
5951 {
5952 const float avg = ( color.redF() + color.greenF() + color.blueF() ) / 3; // NOLINT(bugprone-narrowing-conversions): TODO QGIS 4 remove the nolint instructions, QColor was qreal (double) and is now float
5953 color.setRgbF( avg, avg, avg, alpha );
5954 }
5955
5956 return isQColor ? QVariant( color ) : QVariant( QgsSymbolLayerUtils::encodeColor( color ) );
5957}
5958
5959static QVariant fcnColorMixRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5960{
5961 QColor color1 = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5962 QColor color2 = QgsSymbolLayerUtils::decodeColor( values.at( 1 ).toString() );
5963 double ratio = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5964 if ( ratio > 1 )
5965 {
5966 ratio = 1;
5967 }
5968 else if ( ratio < 0 )
5969 {
5970 ratio = 0;
5971 }
5972
5973 int red = static_cast<int>( color1.red() * ( 1 - ratio ) + color2.red() * ratio );
5974 int green = static_cast<int>( color1.green() * ( 1 - ratio ) + color2.green() * ratio );
5975 int blue = static_cast<int>( color1.blue() * ( 1 - ratio ) + color2.blue() * ratio );
5976 int alpha = static_cast<int>( color1.alpha() * ( 1 - ratio ) + color2.alpha() * ratio );
5977
5978 QColor newColor( red, green, blue, alpha );
5979
5980 return QgsSymbolLayerUtils::encodeColor( newColor );
5981}
5982
5983static QVariant fcnColorMix( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5984{
5985 const QVariant variant1 = values.at( 0 );
5986 const QVariant variant2 = values.at( 1 );
5987
5988 if ( variant1.userType() != variant2.userType() )
5989 {
5990 parent->setEvalErrorString( QObject::tr( "Both color arguments must have the same type (string or color object)" ) );
5991 return QVariant();
5992 }
5993
5994 bool isQColor;
5995 const QColor color1 = QgsExpressionUtils::getColorValue( variant1, parent, isQColor );
5996 if ( !color1.isValid() )
5997 return QVariant();
5998
5999 const QColor color2 = QgsExpressionUtils::getColorValue( variant2, parent, isQColor );
6000 if ( !color2.isValid() )
6001 return QVariant();
6002
6003 if ( ( color1.spec() == QColor::Cmyk ) != ( color2.spec() == QColor::Cmyk ) )
6004 {
6005 parent->setEvalErrorString( QObject::tr( "Both color arguments must have compatible color type (CMYK or RGB/HSV/HSL)" ) );
6006 return QVariant();
6007 }
6008
6009 const float ratio = static_cast<float>( std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0., 1. ) );
6010
6011 // TODO QGIS 4 remove the nolint instructions, QColor was qreal (double) and is now float
6012 // NOLINTBEGIN(bugprone-narrowing-conversions)
6013
6014 QColor newColor;
6015 const float alpha = color1.alphaF() * ( 1 - ratio ) + color2.alphaF() * ratio;
6016 if ( color1.spec() == QColor::Spec::Cmyk )
6017 {
6018 float cyan = color1.cyanF() * ( 1 - ratio ) + color2.cyanF() * ratio;
6019 float magenta = color1.magentaF() * ( 1 - ratio ) + color2.magentaF() * ratio;
6020 float yellow = color1.yellowF() * ( 1 - ratio ) + color2.yellowF() * ratio;
6021 float black = color1.blackF() * ( 1 - ratio ) + color2.blackF() * ratio;
6022 newColor = QColor::fromCmykF( cyan, magenta, yellow, black, alpha );
6023 }
6024 else
6025 {
6026 float red = color1.redF() * ( 1 - ratio ) + color2.redF() * ratio;
6027 float green = color1.greenF() * ( 1 - ratio ) + color2.greenF() * ratio;
6028 float blue = color1.blueF() * ( 1 - ratio ) + color2.blueF() * ratio;
6029 newColor = QColor::fromRgbF( red, green, blue, alpha );
6030 }
6031
6032 // NOLINTEND(bugprone-narrowing-conversions)
6033
6034 return isQColor ? QVariant( newColor ) : QVariant( QgsSymbolLayerUtils::encodeColor( newColor ) );
6035}
6036
6037static QVariant fcnColorRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6038{
6039 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
6040 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6041 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
6042 QColor color = QColor( red, green, blue );
6043 if ( ! color.isValid() )
6044 {
6045 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( red ).arg( green ).arg( blue ) );
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 fcnColorRgbF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6053{
6054 const float red = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) ), 0.f, 1.f );
6055 const float green = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent ) ), 0.f, 1.f );
6056 const float blue = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) ), 0.f, 1.f );
6057 const float alpha = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) ), 0.f, 1.f );
6058 QColor color = QColor::fromRgbF( red, green, blue, alpha );
6059 if ( ! color.isValid() )
6060 {
6061 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) );
6062 return QVariant();
6063 }
6064
6065 return color;
6066}
6067
6068static QVariant fcnTry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6069{
6070 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
6071 QVariant value = node->eval( parent, context );
6072 if ( parent->hasEvalError() )
6073 {
6074 parent->setEvalErrorString( QString() );
6075 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
6077 value = node->eval( parent, context );
6079 }
6080 return value;
6081}
6082
6083static QVariant fcnIf( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6084{
6085 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
6087 QVariant value = node->eval( parent, context );
6089 if ( value.toBool() )
6090 {
6091 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
6093 value = node->eval( parent, context );
6095 }
6096 else
6097 {
6098 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
6100 value = node->eval( parent, context );
6102 }
6103 return value;
6104}
6105
6106static QVariant fncColorRgba( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6107{
6108 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
6109 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6110 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
6111 int alpha = QgsExpressionUtils::getNativeIntValue( values.at( 3 ), parent );
6112 QColor color = QColor( red, green, blue, alpha );
6113 if ( ! color.isValid() )
6114 {
6115 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) );
6116 color = QColor( 0, 0, 0 );
6117 }
6118 return QgsSymbolLayerUtils::encodeColor( color );
6119}
6120
6121QVariant fcnRampColorObject( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6122{
6123 QgsGradientColorRamp expRamp;
6124 const QgsColorRamp *ramp = nullptr;
6125 if ( values.at( 0 ).userType() == qMetaTypeId< QgsGradientColorRamp>() )
6126 {
6127 expRamp = QgsExpressionUtils::getRamp( values.at( 0 ), parent );
6128 ramp = &expRamp;
6129 }
6130 else
6131 {
6132 QString rampName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
6133 ramp = QgsStyle::defaultStyle()->colorRampRef( rampName );
6134 if ( ! ramp )
6136 parent->setEvalErrorString( QObject::tr( "\"%1\" is not a valid color ramp" ).arg( rampName ) );
6137 return QVariant();
6138 }
6139 }
6140
6141 double value = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
6142 QColor color = ramp->color( value );
6143 return color;
6144}
6145
6146QVariant fcnRampColor( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6147{
6148 QColor color = fcnRampColorObject( values, context, parent, node ).value<QColor>();
6149 return color.isValid() ? QgsSymbolLayerUtils::encodeColor( color ) : QVariant();
6150}
6151
6152static QVariant fcnColorHsl( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6153{
6154 // Hue ranges from 0 - 360
6155 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
6156 // Saturation ranges from 0 - 100
6157 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6158 // Lightness ranges from 0 - 100
6159 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6160
6161 QColor color = QColor::fromHslF( hue, saturation, lightness );
6162
6163 if ( ! color.isValid() )
6164 {
6165 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( lightness ) );
6166 color = QColor( 0, 0, 0 );
6167 }
6168
6169 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
6170}
6171
6172static QVariant fncColorHsla( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6173{
6174 // Hue ranges from 0 - 360
6175 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
6176 // Saturation ranges from 0 - 100
6177 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6178 // Lightness ranges from 0 - 100
6179 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6180 // Alpha ranges from 0 - 255
6181 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
6182
6183 QColor color = QColor::fromHslF( hue, saturation, lightness, alpha );
6184 if ( ! color.isValid() )
6185 {
6186 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( lightness ).arg( alpha ) );
6187 color = QColor( 0, 0, 0 );
6188 }
6189 return QgsSymbolLayerUtils::encodeColor( color );
6190}
6191
6192static QVariant fcnColorHslF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6193{
6194 float hue = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) ), 0.f, 1.f );
6195 float saturation = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent ) ), 0.f, 1.f );
6196 float lightness = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) ), 0.f, 1.f );
6197 float alpha = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) ), 0.f, 1.f );
6198
6199 QColor color = QColor::fromHslF( hue, saturation, lightness, alpha );
6200 if ( ! color.isValid() )
6201 {
6202 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( lightness ).arg( alpha ) );
6203 return QVariant();
6204 }
6205
6206 return color;
6207}
6208
6209static QVariant fcnColorHsv( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6210{
6211 // Hue ranges from 0 - 360
6212 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
6213 // Saturation ranges from 0 - 100
6214 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6215 // Value ranges from 0 - 100
6216 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6217
6218 QColor color = QColor::fromHsvF( hue, saturation, value );
6219
6220 if ( ! color.isValid() )
6221 {
6222 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( value ) );
6223 color = QColor( 0, 0, 0 );
6224 }
6225
6226 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
6227}
6228
6229static QVariant fncColorHsva( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6230{
6231 // Hue ranges from 0 - 360
6232 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
6233 // Saturation ranges from 0 - 100
6234 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6235 // Value ranges from 0 - 100
6236 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6237 // Alpha ranges from 0 - 255
6238 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
6239
6240 QColor color = QColor::fromHsvF( hue, saturation, value, alpha );
6241 if ( ! color.isValid() )
6242 {
6243 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( value ).arg( alpha ) );
6244 color = QColor( 0, 0, 0 );
6245 }
6246 return QgsSymbolLayerUtils::encodeColor( color );
6247}
6248
6249static QVariant fcnColorHsvF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6250{
6251 float hue = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) ), 0.f, 1.f );
6252 float saturation = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent ) ), 0.f, 1.f );
6253 float value = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) ), 0.f, 1.f );
6254 float alpha = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) ), 0.f, 1.f );
6255 QColor color = QColor::fromHsvF( hue, saturation, value, alpha );
6256
6257 if ( ! color.isValid() )
6258 {
6259 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( value ).arg( alpha ) );
6260 return QVariant();
6261 }
6262
6263 return color;
6264}
6265
6266static QVariant fcnColorCmykF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6267{
6268 const float cyan = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) ), 0.f, 1.f );
6269 const float magenta = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent ) ), 0.f, 1.f );
6270 const float yellow = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) ), 0.f, 1.f );
6271 const float black = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) ), 0.f, 1.f );
6272 const float alpha = std::clamp( static_cast<float>( QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ) ), 0.f, 1.f );
6273
6274 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black, alpha );
6275 if ( ! color.isValid() )
6276 {
6277 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4:%5' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ).arg( alpha ) );
6278 return QVariant();
6279 }
6280
6281 return color;
6282}
6283
6284static QVariant fcnColorCmyk( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6285{
6286 // Cyan ranges from 0 - 100
6287 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
6288 // Magenta ranges from 0 - 100
6289 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6290 // Yellow ranges from 0 - 100
6291 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6292 // Black ranges from 0 - 100
6293 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
6294
6295 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black );
6296
6297 if ( ! color.isValid() )
6298 {
6299 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ) );
6300 color = QColor( 0, 0, 0 );
6301 }
6302
6303 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
6304}
6305
6306static QVariant fncColorCmyka( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6307{
6308 // Cyan ranges from 0 - 100
6309 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
6310 // Magenta ranges from 0 - 100
6311 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
6312 // Yellow ranges from 0 - 100
6313 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
6314 // Black ranges from 0 - 100
6315 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
6316 // Alpha ranges from 0 - 255
6317 double alpha = QgsExpressionUtils::getIntValue( values.at( 4 ), parent ) / 255.0;
6318
6319 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black, alpha );
6320 if ( ! color.isValid() )
6321 {
6322 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4:%5' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ).arg( alpha ) );
6323 color = QColor( 0, 0, 0 );
6324 }
6325 return QgsSymbolLayerUtils::encodeColor( color );
6326}
6327
6328static QVariant fncColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6329{
6330 const QVariant variant = values.at( 0 );
6331 bool isQColor;
6332 const QColor color = QgsExpressionUtils::getColorValue( variant, parent, isQColor );
6333 if ( !color.isValid() )
6334 return QVariant();
6335
6336 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6337 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
6338 return color.red();
6339 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6340 return color.green();
6341 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6342 return color.blue();
6343 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6344 return color.alpha();
6345 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6346 return static_cast< double >( color.hsvHueF() * 360 );
6347 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6348 return static_cast< double >( color.hsvSaturationF() * 100 );
6349 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6350 return static_cast< double >( color.valueF() * 100 );
6351 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6352 return static_cast< double >( color.hslHueF() * 360 );
6353 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6354 return static_cast< double >( color.hslSaturationF() * 100 );
6355 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6356 return static_cast< double >( color.lightnessF() * 100 );
6357 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6358 return static_cast< double >( color.cyanF() * 100 );
6359 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6360 return static_cast< double >( color.magentaF() * 100 );
6361 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6362 return static_cast< double >( color.yellowF() * 100 );
6363 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6364 return static_cast< double >( color.blackF() * 100 );
6365
6366 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6367 return QVariant();
6368}
6369
6370static QVariant fcnCreateRamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6371{
6372 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
6373 if ( map.empty() )
6374 {
6375 parent->setEvalErrorString( QObject::tr( "A minimum of two colors is required to create a ramp" ) );
6376 return QVariant();
6377 }
6378
6379 QList< QColor > colors;
6381 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
6382 {
6383 colors << QgsSymbolLayerUtils::decodeColor( it.value().toString() );
6384 if ( !colors.last().isValid() )
6385 {
6386 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( it.value().toString() ) );
6387 return QVariant();
6388 }
6389
6390 double step = it.key().toDouble();
6391 if ( it == map.constBegin() )
6392 {
6393 if ( step != 0.0 )
6394 stops << QgsGradientStop( step, colors.last() );
6395 }
6396 else if ( it == map.constEnd() )
6397 {
6398 if ( step != 1.0 )
6399 stops << QgsGradientStop( step, colors.last() );
6400 }
6401 else
6402 {
6403 stops << QgsGradientStop( step, colors.last() );
6404 }
6405 }
6406 bool discrete = values.at( 1 ).toBool();
6407
6408 if ( colors.empty() )
6409 return QVariant();
6410
6411 return QVariant::fromValue( QgsGradientColorRamp( colors.first(), colors.last(), discrete, stops ) );
6412}
6413
6414static QVariant fncSetColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6415{
6416 const QVariant variant = values.at( 0 );
6417 bool isQColor;
6418 QColor color = QgsExpressionUtils::getColorValue( variant, parent, isQColor );
6419 if ( !color.isValid() )
6420 return QVariant();
6421
6422 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6423 int value = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
6424 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
6425 color.setRed( std::clamp( value, 0, 255 ) );
6426 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6427 color.setGreen( std::clamp( value, 0, 255 ) );
6428 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6429 color.setBlue( std::clamp( value, 0, 255 ) );
6430 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6431 color.setAlpha( std::clamp( value, 0, 255 ) );
6432 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6433 color.setHsv( std::clamp( value, 0, 359 ), color.hsvSaturation(), color.value(), color.alpha() );
6434 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6435 color.setHsvF( color.hsvHueF(), std::clamp( value, 0, 100 ) / 100.0, color.valueF(), color.alphaF() );
6436 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6437 color.setHsvF( color.hsvHueF(), color.hsvSaturationF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6438 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6439 color.setHsl( std::clamp( value, 0, 359 ), color.hslSaturation(), color.lightness(), color.alpha() );
6440 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6441 color.setHslF( color.hslHueF(), std::clamp( value, 0, 100 ) / 100.0, color.lightnessF(), color.alphaF() );
6442 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6443 color.setHslF( color.hslHueF(), color.hslSaturationF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6444 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6445 color.setCmykF( std::clamp( value, 0, 100 ) / 100.0, color.magentaF(), color.yellowF(), color.blackF(), color.alphaF() );
6446 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6447 color.setCmykF( color.cyanF(), std::clamp( value, 0, 100 ) / 100.0, color.yellowF(), color.blackF(), color.alphaF() );
6448 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6449 color.setCmykF( color.cyanF(), color.magentaF(), std::clamp( value, 0, 100 ) / 100.0, color.blackF(), color.alphaF() );
6450 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6451 color.setCmykF( color.cyanF(), color.magentaF(), color.yellowF(), std::clamp( value, 0, 100 ) / 100.0, color.alphaF() );
6452 else
6453 {
6454 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6455 return QVariant();
6456 }
6457 return isQColor ? QVariant( color ) : QVariant( QgsSymbolLayerUtils::encodeColor( color ) );
6458}
6459
6460static QVariant fncDarker( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6461{
6462 const QVariant variant = values.at( 0 );
6463 bool isQColor;
6464 QColor color = QgsExpressionUtils::getColorValue( variant, parent, isQColor );
6465 if ( !color.isValid() )
6466 return QVariant();
6467
6468 color = color.darker( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6469
6470 return isQColor ? QVariant( color ) : QVariant( QgsSymbolLayerUtils::encodeColor( color ) );
6471}
6472
6473static QVariant fncLighter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6474{
6475 const QVariant variant = values.at( 0 );
6476 bool isQColor;
6477 QColor color = QgsExpressionUtils::getColorValue( variant, parent, isQColor );
6478 if ( !color.isValid() )
6479 return QVariant();
6480
6481 color = color.lighter( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6482
6483 return isQColor ? QVariant( color ) : QVariant( QgsSymbolLayerUtils::encodeColor( color ) );
6484}
6485
6486static QVariant fcnGetGeometry( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6487{
6488 QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6489 QgsGeometry geom = feat.geometry();
6490 if ( !geom.isNull() )
6491 return QVariant::fromValue( geom );
6492 return QVariant();
6493}
6494
6495static QVariant fcnGetFeatureId( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6496{
6497 const QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6498 if ( !feat.isValid() )
6499 return QVariant();
6500 return feat.id();
6501}
6502
6503static QVariant fcnTransformGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6504{
6505 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
6506 QgsCoordinateReferenceSystem sCrs = QgsExpressionUtils::getCrsValue( values.at( 1 ), parent );
6507 QgsCoordinateReferenceSystem dCrs = QgsExpressionUtils::getCrsValue( values.at( 2 ), parent );
6508
6509 if ( !sCrs.isValid() )
6510 return QVariant::fromValue( fGeom );
6511
6512 if ( !dCrs.isValid() )
6513 return QVariant::fromValue( fGeom );
6514
6516 if ( context )
6517 tContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
6518 QgsCoordinateTransform t( sCrs, dCrs, tContext );
6519 try
6520 {
6522 return QVariant::fromValue( fGeom );
6523 }
6524 catch ( QgsCsException &cse )
6525 {
6526 QgsMessageLog::logMessage( QObject::tr( "Transform error caught in transform() function: %1" ).arg( cse.what() ) );
6527 return QVariant();
6528 }
6529 return QVariant();
6530}
6531
6532
6533static QVariant fcnGetFeatureById( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6534{
6535 bool foundLayer = false;
6536 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6537
6538 //no layer found
6539 if ( !featureSource || !foundLayer )
6540 {
6541 return QVariant();
6542 }
6543
6544 const QgsFeatureId fid = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
6545
6547 req.setFilterFid( fid );
6548 req.setTimeout( 10000 );
6549 req.setRequestMayBeNested( true );
6550 if ( context )
6551 req.setFeedback( context->feedback() );
6552 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6553
6554 QgsFeature fet;
6555 QVariant result;
6556 if ( fIt.nextFeature( fet ) )
6557 result = QVariant::fromValue( fet );
6558
6559 return result;
6560}
6561
6562static QVariant fcnGetFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6563{
6564 //arguments: 1. layer id / name, 2. key attribute, 3. eq value
6565 bool foundLayer = false;
6566 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6567
6568 //no layer found
6569 if ( !featureSource || !foundLayer )
6570 {
6571 return QVariant();
6572 }
6574 QString cacheValueKey;
6575 if ( values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
6576 {
6577 QVariantMap attributeMap = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
6578
6579 QMap <QString, QVariant>::const_iterator i = attributeMap.constBegin();
6580 QString filterString;
6581 for ( ; i != attributeMap.constEnd(); ++i )
6582 {
6583 if ( !filterString.isEmpty() )
6584 {
6585 filterString.append( " AND " );
6586 }
6587 filterString.append( QgsExpression::createFieldEqualityExpression( i.key(), i.value() ) );
6588 }
6589 cacheValueKey = QStringLiteral( "getfeature:%1:%2" ).arg( featureSource->id(), filterString );
6590 if ( context && context->hasCachedValue( cacheValueKey ) )
6591 {
6592 return context->cachedValue( cacheValueKey );
6593 }
6594 req.setFilterExpression( filterString );
6595 }
6596 else
6597 {
6598 QString attribute = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6599 int attributeId = featureSource->fields().lookupField( attribute );
6600 if ( attributeId == -1 )
6601 {
6602 return QVariant();
6603 }
6604
6605 const QVariant &attVal = values.at( 2 );
6606
6607 cacheValueKey = QStringLiteral( "getfeature:%1:%2:%3" ).arg( featureSource->id(), QString::number( attributeId ), attVal.toString() );
6608 if ( context && context->hasCachedValue( cacheValueKey ) )
6609 {
6610 return context->cachedValue( cacheValueKey );
6611 }
6612
6614 }
6615 req.setLimit( 1 );
6616 req.setTimeout( 10000 );
6617 req.setRequestMayBeNested( true );
6618 if ( context )
6619 req.setFeedback( context->feedback() );
6620 if ( !parent->needsGeometry() )
6621 {
6623 }
6624 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6625
6626 QgsFeature fet;
6627 QVariant res;
6628 if ( fIt.nextFeature( fet ) )
6629 {
6630 res = QVariant::fromValue( fet );
6631 }
6632
6633 if ( context )
6634 context->setCachedValue( cacheValueKey, res );
6635 return res;
6636}
6637
6638static QVariant fcnRepresentValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6639{
6640 QVariant result;
6641 QString fieldName;
6642
6643 if ( context )
6644 {
6645 if ( !values.isEmpty() )
6646 {
6647 QgsExpressionNodeColumnRef *col = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
6648 if ( col && ( values.size() == 1 || !values.at( 1 ).isValid() ) )
6649 fieldName = col->name();
6650 else if ( values.size() == 2 )
6651 fieldName = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6652 }
6653
6654 QVariant value = values.at( 0 );
6655
6656 const QgsFields fields = context->fields();
6657 int fieldIndex = fields.lookupField( fieldName );
6658
6659 if ( fieldIndex == -1 )
6660 {
6661 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: Field not found %2" ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6662 }
6663 else
6664 {
6665 // TODO this function is NOT thread safe
6667 QgsVectorLayer *layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
6669
6670 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName, value.toString() );
6671 if ( context->hasCachedValue( cacheValueKey ) )
6672 {
6673 return context->cachedValue( cacheValueKey );
6674 }
6675
6676 const QgsEditorWidgetSetup setup = fields.at( fieldIndex ).editorWidgetSetup();
6678
6679 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName );
6680
6681 QVariant cache;
6682 if ( !context->hasCachedValue( cacheKey ) )
6683 {
6684 cache = formatter->createCache( layer, fieldIndex, setup.config() );
6685 context->setCachedValue( cacheKey, cache );
6686 }
6687 else
6688 cache = context->cachedValue( cacheKey );
6689
6690 result = formatter->representValue( layer, fieldIndex, setup.config(), cache, value );
6691
6692 context->setCachedValue( cacheValueKey, result );
6693 }
6694 }
6695 else
6696 {
6697 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: function cannot be evaluated without a context." ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6698 }
6699
6700 return result;
6701}
6702
6703static QVariant fcnMimeType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6704{
6705 const QVariant data = values.at( 0 );
6706 const QMimeDatabase db;
6707 return db.mimeTypeForData( data.toByteArray() ).name();
6708}
6709
6710static QVariant fcnGetLayerProperty( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6711{
6712 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6713
6714 bool foundLayer = false;
6715 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [layerProperty]( QgsMapLayer * layer )-> QVariant
6716 {
6717 if ( !layer )
6718 return QVariant();
6719
6720 // here, we always prefer the layer metadata values over the older server-specific published values
6721 if ( QString::compare( layerProperty, QStringLiteral( "name" ), Qt::CaseInsensitive ) == 0 )
6722 return layer->name();
6723 else if ( QString::compare( layerProperty, QStringLiteral( "id" ), Qt::CaseInsensitive ) == 0 )
6724 return layer->id();
6725 else if ( QString::compare( layerProperty, QStringLiteral( "title" ), Qt::CaseInsensitive ) == 0 )
6726 return !layer->metadata().title().isEmpty() ? layer->metadata().title() : layer->serverProperties()->title();
6727 else if ( QString::compare( layerProperty, QStringLiteral( "abstract" ), Qt::CaseInsensitive ) == 0 )
6728 return !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->serverProperties()->abstract();
6729 else if ( QString::compare( layerProperty, QStringLiteral( "keywords" ), Qt::CaseInsensitive ) == 0 )
6730 {
6731 QStringList keywords;
6732 const QgsAbstractMetadataBase::KeywordMap keywordMap = layer->metadata().keywords();
6733 for ( auto it = keywordMap.constBegin(); it != keywordMap.constEnd(); ++it )
6734 {
6735 keywords.append( it.value() );
6736 }
6737 if ( !keywords.isEmpty() )
6738 return keywords;
6739 return layer->serverProperties()->keywordList();
6740 }
6741 else if ( QString::compare( layerProperty, QStringLiteral( "data_url" ), Qt::CaseInsensitive ) == 0 )
6742 return layer->serverProperties()->dataUrl();
6743 else if ( QString::compare( layerProperty, QStringLiteral( "attribution" ), Qt::CaseInsensitive ) == 0 )
6744 {
6745 return !layer->metadata().rights().isEmpty() ? QVariant( layer->metadata().rights() ) : QVariant( layer->serverProperties()->attribution() );
6746 }
6747 else if ( QString::compare( layerProperty, QStringLiteral( "attribution_url" ), Qt::CaseInsensitive ) == 0 )
6748 return layer->serverProperties()->attributionUrl();
6749 else if ( QString::compare( layerProperty, QStringLiteral( "source" ), Qt::CaseInsensitive ) == 0 )
6750 return layer->publicSource();
6751 else if ( QString::compare( layerProperty, QStringLiteral( "min_scale" ), Qt::CaseInsensitive ) == 0 )
6752 return layer->minimumScale();
6753 else if ( QString::compare( layerProperty, QStringLiteral( "max_scale" ), Qt::CaseInsensitive ) == 0 )
6754 return layer->maximumScale();
6755 else if ( QString::compare( layerProperty, QStringLiteral( "is_editable" ), Qt::CaseInsensitive ) == 0 )
6756 return layer->isEditable();
6757 else if ( QString::compare( layerProperty, QStringLiteral( "crs" ), Qt::CaseInsensitive ) == 0 )
6758 return layer->crs().authid();
6759 else if ( QString::compare( layerProperty, QStringLiteral( "crs_definition" ), Qt::CaseInsensitive ) == 0 )
6760 return layer->crs().toProj();
6761 else if ( QString::compare( layerProperty, QStringLiteral( "crs_description" ), Qt::CaseInsensitive ) == 0 )
6762 return layer->crs().description();
6763 else if ( QString::compare( layerProperty, QStringLiteral( "crs_ellipsoid" ), Qt::CaseInsensitive ) == 0 )
6764 return layer->crs().ellipsoidAcronym();
6765 else if ( QString::compare( layerProperty, QStringLiteral( "extent" ), Qt::CaseInsensitive ) == 0 )
6766 {
6767 QgsGeometry extentGeom = QgsGeometry::fromRect( layer->extent() );
6768 QVariant result = QVariant::fromValue( extentGeom );
6769 return result;
6770 }
6771 else if ( QString::compare( layerProperty, QStringLiteral( "distance_units" ), Qt::CaseInsensitive ) == 0 )
6772 return QgsUnitTypes::encodeUnit( layer->crs().mapUnits() );
6773 else if ( QString::compare( layerProperty, QStringLiteral( "path" ), Qt::CaseInsensitive ) == 0 )
6774 {
6775 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
6776 return decodedUri.value( QStringLiteral( "path" ) );
6777 }
6778 else if ( QString::compare( layerProperty, QStringLiteral( "type" ), Qt::CaseInsensitive ) == 0 )
6779 {
6780 switch ( layer->type() )
6781 {
6783 return QCoreApplication::translate( "expressions", "Vector" );
6785 return QCoreApplication::translate( "expressions", "Raster" );
6787 return QCoreApplication::translate( "expressions", "Mesh" );
6789 return QCoreApplication::translate( "expressions", "Vector Tile" );
6791 return QCoreApplication::translate( "expressions", "Plugin" );
6793 return QCoreApplication::translate( "expressions", "Annotation" );
6795 return QCoreApplication::translate( "expressions", "Point Cloud" );
6797 return QCoreApplication::translate( "expressions", "Group" );
6799 return QCoreApplication::translate( "expressions", "Tiled Scene" );
6800 }
6801 }
6802 else
6803 {
6804 //vector layer methods
6805 QgsVectorLayer *vLayer = qobject_cast< QgsVectorLayer * >( layer );
6806 if ( vLayer )
6807 {
6808 if ( QString::compare( layerProperty, QStringLiteral( "storage_type" ), Qt::CaseInsensitive ) == 0 )
6809 return vLayer->storageType();
6810 else if ( QString::compare( layerProperty, QStringLiteral( "geometry_type" ), Qt::CaseInsensitive ) == 0 )
6812 else if ( QString::compare( layerProperty, QStringLiteral( "feature_count" ), Qt::CaseInsensitive ) == 0 )
6813 return QVariant::fromValue( vLayer->featureCount() );
6814 }
6815 }
6816
6817 return QVariant();
6818 }, foundLayer );
6819
6820 if ( !foundLayer )
6821 return QVariant();
6822 else
6823 return res;
6824}
6825
6826static QVariant fcnDecodeUri( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6827{
6828 const QString uriPart = values.at( 1 ).toString();
6829
6830 bool foundLayer = false;
6831
6832 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, uriPart]( QgsMapLayer * layer )-> QVariant
6833 {
6834 if ( !layer->dataProvider() )
6835 {
6836 parent->setEvalErrorString( QObject::tr( "Layer %1 has invalid data provider" ).arg( layer->name() ) );
6837 return QVariant();
6838 }
6839
6840 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
6841
6842 if ( !uriPart.isNull() )
6843 {
6844 return decodedUri.value( uriPart );
6845 }
6846 else
6847 {
6848 return decodedUri;
6849 }
6850 }, foundLayer );
6851
6852 if ( !foundLayer )
6853 {
6854 parent->setEvalErrorString( QObject::tr( "Function `decode_uri` requires a valid layer." ) );
6855 return QVariant();
6856 }
6857 else
6858 {
6859 return res;
6860 }
6861}
6862
6863static QVariant fcnGetRasterBandStat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6864{
6865 const int band = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6866 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
6867
6868 bool foundLayer = false;
6869 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, band, layerProperty]( QgsMapLayer * layer )-> QVariant
6870 {
6871 QgsRasterLayer *rl = qobject_cast< QgsRasterLayer * >( layer );
6872 if ( !rl )
6873 return QVariant();
6874
6875 if ( band < 1 || band > rl->bandCount() )
6876 {
6877 parent->setEvalErrorString( QObject::tr( "Invalid band number %1 for layer" ).arg( band ) );
6878 return QVariant();
6879 }
6880
6882
6883 if ( QString::compare( layerProperty, QStringLiteral( "avg" ), Qt::CaseInsensitive ) == 0 )
6885 else if ( QString::compare( layerProperty, QStringLiteral( "stdev" ), Qt::CaseInsensitive ) == 0 )
6887 else if ( QString::compare( layerProperty, QStringLiteral( "min" ), Qt::CaseInsensitive ) == 0 )
6889 else if ( QString::compare( layerProperty, QStringLiteral( "max" ), Qt::CaseInsensitive ) == 0 )
6891 else if ( QString::compare( layerProperty, QStringLiteral( "range" ), Qt::CaseInsensitive ) == 0 )
6893 else if ( QString::compare( layerProperty, QStringLiteral( "sum" ), Qt::CaseInsensitive ) == 0 )
6895 else
6896 {
6897 parent->setEvalErrorString( QObject::tr( "Invalid raster statistic: '%1'" ).arg( layerProperty ) );
6898 return QVariant();
6899 }
6900
6901 QgsRasterBandStats stats = rl->dataProvider()->bandStatistics( band, stat );
6902 switch ( stat )
6903 {
6905 return stats.mean;
6907 return stats.stdDev;
6909 return stats.minimumValue;
6911 return stats.maximumValue;
6913 return stats.range;
6915 return stats.sum;
6916 default:
6917 break;
6918 }
6919 return QVariant();
6920 }, foundLayer );
6921
6922 if ( !foundLayer )
6923 {
6924#if 0 // for consistency with other functions we should raise an error here, but for compatibility with old projects we don't
6925 parent->setEvalErrorString( QObject::tr( "Function `raster_statistic` requires a valid raster layer." ) );
6926#endif
6927 return QVariant();
6928 }
6929 else
6930 {
6931 return res;
6932 }
6933}
6934
6935static QVariant fcnArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6936{
6937 return values;
6938}
6939
6940static QVariant fcnArraySort( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6941{
6942 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6943 bool ascending = values.value( 1 ).toBool();
6944 std::sort( list.begin(), list.end(), [ascending]( QVariant a, QVariant b ) -> bool { return ( !ascending ? qgsVariantLessThan( b, a ) : qgsVariantLessThan( a, b ) ); } );
6945 return list;
6946}
6947
6948static QVariant fcnArrayLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6949{
6950 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).length();
6951}
6952
6953static QVariant fcnArrayContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6954{
6955 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).contains( values.at( 1 ) ) );
6956}
6957
6958static QVariant fcnArrayCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6959{
6960 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).count( values.at( 1 ) ) );
6961}
6962
6963static QVariant fcnArrayAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6964{
6965 QVariantList listA = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6966 QVariantList listB = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
6967 int match = 0;
6968 for ( const auto &item : listB )
6969 {
6970 if ( listA.contains( item ) )
6971 match++;
6972 }
6973
6974 return QVariant( match == listB.count() );
6975}
6976
6977static QVariant fcnArrayFind( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6978{
6979 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).indexOf( values.at( 1 ) );
6980}
6981
6982static QVariant fcnArrayGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6983{
6984 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6985 const int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6986 if ( pos < list.length() && pos >= 0 ) return list.at( pos );
6987 else if ( pos < 0 && ( list.length() + pos ) >= 0 )
6988 return list.at( list.length() + pos );
6989 return QVariant();
6990}
6991
6992static QVariant fcnArrayFirst( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6993{
6994 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6995 return list.value( 0 );
6996}
6997
6998static QVariant fcnArrayLast( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6999{
7000 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7001 return list.value( list.size() - 1 );
7002}
7003
7004static QVariant fcnArrayMinimum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7005{
7006 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7007 return list.isEmpty() ? QVariant() : *std::min_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
7008}
7009
7010static QVariant fcnArrayMaximum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7011{
7012 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7013 return list.isEmpty() ? QVariant() : *std::max_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
7014}
7015
7016static QVariant fcnArrayMean( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7017{
7018 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7019 int i = 0;
7020 double total = 0.0;
7021 for ( const QVariant &item : list )
7022 {
7023 switch ( item.userType() )
7024 {
7025 case QMetaType::Int:
7026 case QMetaType::UInt:
7027 case QMetaType::LongLong:
7028 case QMetaType::ULongLong:
7029 case QMetaType::Float:
7030 case QMetaType::Double:
7031 total += item.toDouble();
7032 ++i;
7033 break;
7034 }
7035 }
7036 return i == 0 ? QVariant() : total / i;
7037}
7038
7039static QVariant fcnArrayMedian( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7040{
7041 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7042 QVariantList numbers;
7043 for ( const auto &item : list )
7044 {
7045 switch ( item.userType() )
7046 {
7047 case QMetaType::Int:
7048 case QMetaType::UInt:
7049 case QMetaType::LongLong:
7050 case QMetaType::ULongLong:
7051 case QMetaType::Float:
7052 case QMetaType::Double:
7053 numbers.append( item );
7054 break;
7055 }
7056 }
7057 std::sort( numbers.begin(), numbers.end(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
7058 const int count = numbers.count();
7059 if ( count == 0 )
7060 {
7061 return QVariant();
7062 }
7063 else if ( count % 2 )
7064 {
7065 return numbers.at( count / 2 );
7066 }
7067 else
7068 {
7069 return ( numbers.at( count / 2 - 1 ).toDouble() + numbers.at( count / 2 ).toDouble() ) / 2;
7070 }
7071}
7072
7073static QVariant fcnArraySum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7074{
7075 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7076 int i = 0;
7077 double total = 0.0;
7078 for ( const QVariant &item : list )
7079 {
7080 switch ( item.userType() )
7081 {
7082 case QMetaType::Int:
7083 case QMetaType::UInt:
7084 case QMetaType::LongLong:
7085 case QMetaType::ULongLong:
7086 case QMetaType::Float:
7087 case QMetaType::Double:
7088 total += item.toDouble();
7089 ++i;
7090 break;
7091 }
7092 }
7093 return i == 0 ? QVariant() : total;
7094}
7095
7096static QVariant convertToSameType( const QVariant &value, QMetaType::Type type )
7097{
7098 QVariant result = value;
7099 result.convert( static_cast<int>( type ) );
7100 return result;
7101}
7102
7103static QVariant fcnArrayMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
7104{
7105 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7106 QHash< QVariant, int > hash;
7107 for ( const auto &item : list )
7108 {
7109 ++hash[item];
7110 }
7111 const QList< int > occurrences = hash.values();
7112 if ( occurrences.empty() )
7113 return QVariantList();
7114
7115 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
7116
7117 const QString option = values.at( 1 ).toString();
7118 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
7119 {
7120 return convertToSameType( hash.keys( maxValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7121 }
7122 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
7123 {
7124 if ( hash.isEmpty() )
7125 return QVariant();
7126
7127 return QVariant( hash.key( maxValue ) );
7128 }
7129 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
7130 {
7131 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( maxValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) ), context, parent, node );
7132 }
7133 else if ( option.compare( QLatin1String( "real_majority" ), Qt::CaseInsensitive ) == 0 )
7134 {
7135 if ( maxValue * 2 <= list.size() )
7136 return QVariant();
7137
7138 return QVariant( hash.key( maxValue ) );
7139 }
7140 else
7141 {
7142 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
7143 return QVariant();
7144 }
7145}
7146
7147static QVariant fcnArrayMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
7148{
7149 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7150 QHash< QVariant, int > hash;
7151 for ( const auto &item : list )
7152 {
7153 ++hash[item];
7154 }
7155 const QList< int > occurrences = hash.values();
7156 if ( occurrences.empty() )
7157 return QVariantList();
7158
7159 const int minValue = *std::min_element( occurrences.constBegin(), occurrences.constEnd() );
7160
7161 const QString option = values.at( 1 ).toString();
7162 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
7163 {
7164 return convertToSameType( hash.keys( minValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7165 }
7166 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
7167 {
7168 if ( hash.isEmpty() )
7169 return QVariant();
7170
7171 return QVariant( hash.key( minValue ) );
7172 }
7173 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
7174 {
7175 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( minValue ), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) ), context, parent, node );
7176 }
7177 else if ( option.compare( QLatin1String( "real_minority" ), Qt::CaseInsensitive ) == 0 )
7178 {
7179 if ( hash.isEmpty() )
7180 return QVariant();
7181
7182 // Remove the majority, all others are minority
7183 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
7184 if ( maxValue * 2 > list.size() )
7185 hash.remove( hash.key( maxValue ) );
7186
7187 return convertToSameType( hash.keys(), static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7188 }
7189 else
7190 {
7191 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
7192 return QVariant();
7193 }
7194}
7195
7196static QVariant fcnArrayAppend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7197{
7198 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7199 list.append( values.at( 1 ) );
7200 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7201}
7202
7203static QVariant fcnArrayPrepend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7204{
7205 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7206 list.prepend( values.at( 1 ) );
7207 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7208}
7209
7210static QVariant fcnArrayInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7211{
7212 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7213 list.insert( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), values.at( 2 ) );
7214 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7215}
7216
7217static QVariant fcnArrayRemoveAt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7218{
7219 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7220 int position = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
7221 if ( position < 0 )
7222 position = position + list.length();
7223 if ( position >= 0 && position < list.length() )
7224 list.removeAt( position );
7225 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7226}
7227
7228static QVariant fcnArrayRemoveAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7229{
7230 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
7231 return QVariant();
7232
7233 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7234
7235 const QVariant toRemove = values.at( 1 );
7236 if ( QgsVariantUtils::isNull( toRemove ) )
7237 {
7238 list.erase( std::remove_if( list.begin(), list.end(), []( const QVariant & element )
7239 {
7240 return QgsVariantUtils::isNull( element );
7241 } ), list.end() );
7242 }
7243 else
7244 {
7245 list.removeAll( toRemove );
7246 }
7247 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7248}
7249
7250static QVariant fcnArrayReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7251{
7252 if ( values.count() == 2 && values.at( 1 ).userType() == QMetaType::Type::QVariantMap )
7253 {
7254 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
7255
7256 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7257 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
7258 {
7259 int index = list.indexOf( it.key() );
7260 while ( index >= 0 )
7261 {
7262 list.replace( index, it.value() );
7263 index = list.indexOf( it.key() );
7264 }
7265 }
7266
7267 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7268 }
7269 else if ( values.count() == 3 )
7270 {
7271 QVariantList before;
7272 QVariantList after;
7273 bool isSingleReplacement = false;
7274
7275 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).userType() != QMetaType::Type::QStringList )
7276 {
7277 before = QVariantList() << values.at( 1 );
7278 }
7279 else
7280 {
7281 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
7282 }
7283
7284 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
7285 {
7286 after = QVariantList() << values.at( 2 );
7287 isSingleReplacement = true;
7288 }
7289 else
7290 {
7291 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
7292 }
7293
7294 if ( !isSingleReplacement && before.length() != after.length() )
7295 {
7296 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
7297 return QVariant();
7298 }
7299
7300 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7301 for ( int i = 0; i < before.length(); i++ )
7302 {
7303 int index = list.indexOf( before.at( i ) );
7304 while ( index >= 0 )
7305 {
7306 list.replace( index, after.at( isSingleReplacement ? 0 : i ) );
7307 index = list.indexOf( before.at( i ) );
7308 }
7309 }
7310
7311 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7312 }
7313 else
7314 {
7315 parent->setEvalErrorString( QObject::tr( "Function array_replace requires 2 or 3 arguments" ) );
7316 return QVariant();
7317 }
7318}
7319
7320static QVariant fcnArrayPrioritize( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7321{
7322 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7323 QVariantList list_new;
7324
7325 for ( const QVariant &cur : QgsExpressionUtils::getListValue( values.at( 1 ), parent ) )
7326 {
7327 while ( list.removeOne( cur ) )
7328 {
7329 list_new.append( cur );
7330 }
7331 }
7332
7333 list_new.append( list );
7334
7335 return convertToSameType( list_new, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7336}
7337
7338static QVariant fcnArrayCat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7339{
7340 QVariantList list;
7341 for ( const QVariant &cur : values )
7342 {
7343 list += QgsExpressionUtils::getListValue( cur, parent );
7344 }
7345 return convertToSameType( list, static_cast<QMetaType::Type>( values.at( 0 ).userType() ) );
7346}
7347
7348static QVariant fcnArraySlice( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7349{
7350 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7351 int start_pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
7352 const int end_pos = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
7353 int slice_length = 0;
7354 // negative positions means positions taken relative to the end of the array
7355 if ( start_pos < 0 )
7356 {
7357 start_pos = list.length() + start_pos;
7358 }
7359 if ( end_pos >= 0 )
7360 {
7361 slice_length = end_pos - start_pos + 1;
7362 }
7363 else
7364 {
7365 slice_length = list.length() + end_pos - start_pos + 1;
7366 }
7367 //avoid negative lengths in QList.mid function
7368 if ( slice_length < 0 )
7369 {
7370 slice_length = 0;
7371 }
7372 list = list.mid( start_pos, slice_length );
7373 return list;
7374}
7375
7376static QVariant fcnArrayReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7377{
7378 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7379 std::reverse( list.begin(), list.end() );
7380 return list;
7381}
7382
7383static QVariant fcnArrayIntersect( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7384{
7385 const QVariantList array1 = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7386 const QVariantList array2 = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
7387 for ( const QVariant &cur : array2 )
7388 {
7389 if ( array1.contains( cur ) )
7390 return QVariant( true );
7391 }
7392 return QVariant( false );
7393}
7394
7395static QVariant fcnArrayDistinct( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7396{
7397 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7398
7399 QVariantList distinct;
7400
7401 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7402 {
7403 if ( !distinct.contains( *it ) )
7404 {
7405 distinct += ( *it );
7406 }
7407 }
7408
7409 return distinct;
7410}
7411
7412static QVariant fcnArrayToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7413{
7414 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7415 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7416 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7417
7418 QString str;
7419
7420 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7421 {
7422 str += ( !( *it ).toString().isEmpty() ) ? ( *it ).toString() : empty;
7423 if ( it != ( array.constEnd() - 1 ) )
7424 {
7425 str += delimiter;
7426 }
7427 }
7428
7429 return QVariant( str );
7430}
7431
7432static QVariant fcnStringToArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7433{
7434 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7435 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7436 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7437
7438 QStringList list = str.split( delimiter );
7439 QVariantList array;
7440
7441 for ( QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it )
7442 {
7443 array += ( !( *it ).isEmpty() ) ? *it : empty;
7444 }
7445
7446 return array;
7447}
7448
7449static QVariant fcnLoadJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7450{
7451 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7452 QJsonDocument document = QJsonDocument::fromJson( str.toUtf8() );
7453 if ( document.isNull() )
7454 return QVariant();
7455
7456 return document.toVariant();
7457}
7458
7459static QVariant fcnWriteJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7460{
7461 Q_UNUSED( parent )
7462 QJsonDocument document = QJsonDocument::fromVariant( values.at( 0 ) );
7463 return QString( document.toJson( QJsonDocument::Compact ) );
7464}
7465
7466static QVariant fcnHstoreToMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7467{
7468 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7469 if ( str.isEmpty() )
7470 return QVariantMap();
7471 str = str.trimmed();
7472
7473 return QgsHstoreUtils::parse( str );
7474}
7475
7476static QVariant fcnMapToHstore( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7477{
7478 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7479 return QgsHstoreUtils::build( map );
7480}
7481
7482static QVariant fcnMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7483{
7484 QVariantMap result;
7485 for ( int i = 0; i + 1 < values.length(); i += 2 )
7486 {
7487 result.insert( QgsExpressionUtils::getStringValue( values.at( i ), parent ), values.at( i + 1 ) );
7488 }
7489 return result;
7490}
7491
7492static QVariant fcnMapPrefixKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7493{
7494 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7495 const QString prefix = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7496 QVariantMap resultMap;
7497
7498 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7499 {
7500 resultMap.insert( QString( it.key() ).prepend( prefix ), it.value() );
7501 }
7502
7503 return resultMap;
7504}
7505
7506static QVariant fcnMapGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7507{
7508 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).value( values.at( 1 ).toString() );
7509}
7510
7511static QVariant fcnMapExist( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7512{
7513 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).contains( values.at( 1 ).toString() );
7514}
7515
7516static QVariant fcnMapDelete( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7517{
7518 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7519 map.remove( values.at( 1 ).toString() );
7520 return map;
7521}
7522
7523static QVariant fcnMapInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7524{
7525 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7526 map.insert( values.at( 1 ).toString(), values.at( 2 ) );
7527 return map;
7528}
7529
7530static QVariant fcnMapConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7531{
7532 QVariantMap result;
7533 for ( const QVariant &cur : values )
7534 {
7535 const QVariantMap curMap = QgsExpressionUtils::getMapValue( cur, parent );
7536 for ( QVariantMap::const_iterator it = curMap.constBegin(); it != curMap.constEnd(); ++it )
7537 result.insert( it.key(), it.value() );
7538 }
7539 return result;
7540}
7541
7542static QVariant fcnMapAKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7543{
7544 return QStringList( QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).keys() );
7545}
7546
7547static QVariant fcnMapAVals( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7548{
7549 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).values();
7550}
7551
7552static QVariant fcnEnvVar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7553{
7554 const QString envVarName = values.at( 0 ).toString();
7555 if ( !QProcessEnvironment::systemEnvironment().contains( envVarName ) )
7556 return QVariant();
7557
7558 return QProcessEnvironment::systemEnvironment().value( envVarName );
7559}
7560
7561static QVariant fcnBaseFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7562{
7563 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7564 if ( parent->hasEvalError() )
7565 {
7566 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "base_file_name" ) ) );
7567 return QVariant();
7568 }
7569 return QFileInfo( file ).completeBaseName();
7570}
7571
7572static QVariant fcnFileSuffix( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7573{
7574 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7575 if ( parent->hasEvalError() )
7576 {
7577 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_suffix" ) ) );
7578 return QVariant();
7579 }
7580 return QFileInfo( file ).completeSuffix();
7581}
7582
7583static QVariant fcnFileExists( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7584{
7585 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7586 if ( parent->hasEvalError() )
7587 {
7588 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_exists" ) ) );
7589 return QVariant();
7590 }
7591 return QFileInfo::exists( file );
7592}
7593
7594static QVariant fcnFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7595{
7596 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7597 if ( parent->hasEvalError() )
7598 {
7599 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_name" ) ) );
7600 return QVariant();
7601 }
7602 return QFileInfo( file ).fileName();
7603}
7604
7605static QVariant fcnPathIsFile( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7606{
7607 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7608 if ( parent->hasEvalError() )
7609 {
7610 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_file" ) ) );
7611 return QVariant();
7612 }
7613 return QFileInfo( file ).isFile();
7614}
7615
7616static QVariant fcnPathIsDir( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7617{
7618 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7619 if ( parent->hasEvalError() )
7620 {
7621 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_directory" ) ) );
7622 return QVariant();
7623 }
7624 return QFileInfo( file ).isDir();
7625}
7626
7627static QVariant fcnFilePath( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7628{
7629 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7630 if ( parent->hasEvalError() )
7631 {
7632 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_path" ) ) );
7633 return QVariant();
7634 }
7635 return QDir::toNativeSeparators( QFileInfo( file ).path() );
7636}
7637
7638static QVariant fcnFileSize( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7639{
7640 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7641 if ( parent->hasEvalError() )
7642 {
7643 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_size" ) ) );
7644 return QVariant();
7645 }
7646 return QFileInfo( file ).size();
7647}
7648
7649static QVariant fcnHash( const QString &str, const QCryptographicHash::Algorithm algorithm )
7650{
7651 return QString( QCryptographicHash::hash( str.toUtf8(), algorithm ).toHex() );
7652}
7653
7654static QVariant fcnGenericHash( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7655{
7656 QVariant hash;
7657 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7658 QString method = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).toLower();
7659
7660 if ( method == QLatin1String( "md4" ) )
7661 {
7662 hash = fcnHash( str, QCryptographicHash::Md4 );
7663 }
7664 else if ( method == QLatin1String( "md5" ) )
7665 {
7666 hash = fcnHash( str, QCryptographicHash::Md5 );
7667 }
7668 else if ( method == QLatin1String( "sha1" ) )
7669 {
7670 hash = fcnHash( str, QCryptographicHash::Sha1 );
7671 }
7672 else if ( method == QLatin1String( "sha224" ) )
7673 {
7674 hash = fcnHash( str, QCryptographicHash::Sha224 );
7675 }
7676 else if ( method == QLatin1String( "sha256" ) )
7677 {
7678 hash = fcnHash( str, QCryptographicHash::Sha256 );
7679 }
7680 else if ( method == QLatin1String( "sha384" ) )
7681 {
7682 hash = fcnHash( str, QCryptographicHash::Sha384 );
7683 }
7684 else if ( method == QLatin1String( "sha512" ) )
7685 {
7686 hash = fcnHash( str, QCryptographicHash::Sha512 );
7687 }
7688 else if ( method == QLatin1String( "sha3_224" ) )
7689 {
7690 hash = fcnHash( str, QCryptographicHash::Sha3_224 );
7691 }
7692 else if ( method == QLatin1String( "sha3_256" ) )
7693 {
7694 hash = fcnHash( str, QCryptographicHash::Sha3_256 );
7695 }
7696 else if ( method == QLatin1String( "sha3_384" ) )
7697 {
7698 hash = fcnHash( str, QCryptographicHash::Sha3_384 );
7699 }
7700 else if ( method == QLatin1String( "sha3_512" ) )
7701 {
7702 hash = fcnHash( str, QCryptographicHash::Sha3_512 );
7703 }
7704 else if ( method == QLatin1String( "keccak_224" ) )
7705 {
7706 hash = fcnHash( str, QCryptographicHash::Keccak_224 );
7707 }
7708 else if ( method == QLatin1String( "keccak_256" ) )
7709 {
7710 hash = fcnHash( str, QCryptographicHash::Keccak_256 );
7711 }
7712 else if ( method == QLatin1String( "keccak_384" ) )
7713 {
7714 hash = fcnHash( str, QCryptographicHash::Keccak_384 );
7715 }
7716 else if ( method == QLatin1String( "keccak_512" ) )
7717 {
7718 hash = fcnHash( str, QCryptographicHash::Keccak_512 );
7719 }
7720 else
7721 {
7722 parent->setEvalErrorString( QObject::tr( "Hash method %1 is not available on this system." ).arg( str ) );
7723 }
7724 return hash;
7725}
7726
7727static QVariant fcnHashMd5( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7728{
7729 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Md5 );
7730}
7731
7732static QVariant fcnHashSha256( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7733{
7734 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Sha256 );
7735}
7736
7737static QVariant fcnToBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7738{
7739 const QByteArray input = values.at( 0 ).toByteArray();
7740 return QVariant( QString( input.toBase64() ) );
7741}
7742
7743static QVariant fcnToFormUrlEncode( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7744{
7745 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7746 QUrlQuery query;
7747 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7748 {
7749 query.addQueryItem( it.key(), it.value().toString() );
7750 }
7751 return query.toString( QUrl::ComponentFormattingOption::FullyEncoded );
7752}
7753
7754static QVariant fcnFromBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7755{
7756 const QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7757 const QByteArray base64 = value.toLocal8Bit();
7758 const QByteArray decoded = QByteArray::fromBase64( base64 );
7759 return QVariant( decoded );
7760}
7761
7762typedef bool ( QgsGeometry::*RelationFunction )( const QgsGeometry &geometry ) const;
7763
7764static 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 )
7765{
7766
7767 if ( ! context )
7768 {
7769 parent->setEvalErrorString( QStringLiteral( "This function was called without an expression context." ) );
7770 return QVariant();
7771 }
7772
7773 const QVariant sourceLayerRef = context->variable( QStringLiteral( "layer" ) ); //used to detect if sourceLayer and targetLayer are the same
7774 // TODO this function is NOT thread safe
7776 QgsVectorLayer *sourceLayer = QgsExpressionUtils::getVectorLayer( sourceLayerRef, context, parent );
7778
7779 QgsFeatureRequest request;
7780 request.setTimeout( 10000 );
7781 request.setRequestMayBeNested( true );
7782 request.setFeedback( context->feedback() );
7783
7784 // First parameter is the overlay layer
7785 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
7787
7788 const bool layerCanBeCached = node->isStatic( parent, context );
7789 QVariant targetLayerValue = node->eval( parent, context );
7791
7792 // Second parameter is the expression to evaluate (or null for testonly)
7793 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
7795 QString subExpString = node->dump();
7796
7797 bool testOnly = ( subExpString == "NULL" );
7798 // TODO this function is NOT thread safe
7800 QgsVectorLayer *targetLayer = QgsExpressionUtils::getVectorLayer( targetLayerValue, context, parent );
7802 if ( !targetLayer ) // No layer, no joy
7803 {
7804 parent->setEvalErrorString( QObject::tr( "Layer '%1' could not be loaded." ).arg( targetLayerValue.toString() ) );
7805 return QVariant();
7806 }
7807
7808 // Third parameter is the filtering expression
7809 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
7811 QString filterString = node->dump();
7812 if ( filterString != "NULL" )
7813 {
7814 request.setFilterExpression( filterString ); //filter cached features
7815 }
7816
7817 // Fourth parameter is the limit
7818 node = QgsExpressionUtils::getNode( values.at( 3 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7820 QVariant limitValue = node->eval( parent, context );
7822 qlonglong limit = QgsExpressionUtils::getIntValue( limitValue, parent );
7823
7824 // Fifth parameter (for nearest only) is the max distance
7825 double max_distance = 0;
7826 if ( isNearestFunc ) //maxdistance param handling
7827 {
7828 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
7830 QVariant distanceValue = node->eval( parent, context );
7832 max_distance = QgsExpressionUtils::getDoubleValue( distanceValue, parent );
7833 }
7834
7835 // Fifth or sixth (for nearest only) parameter is the cache toggle
7836 node = QgsExpressionUtils::getNode( values.at( isNearestFunc ? 5 : 4 ), parent );
7838 QVariant cacheValue = node->eval( parent, context );
7840 bool cacheEnabled = cacheValue.toBool();
7841
7842 // Sixth parameter (for intersects only) is the min overlap (area or length)
7843 // Seventh parameter (for intersects only) is the min inscribed circle radius
7844 // Eighth parameter (for intersects only) is the return_details
7845 // Ninth parameter (for intersects only) is the sort_by_intersection_size flag
7846 double minOverlap { -1 };
7847 double minInscribedCircleRadius { -1 };
7848 bool returnDetails = false; //#spellok
7849 bool sortByMeasure = false;
7850 bool sortAscending = false;
7851 bool requireMeasures = false;
7852 bool overlapOrRadiusFilter = false;
7853 if ( isIntersectsFunc )
7854 {
7855
7856 node = QgsExpressionUtils::getNode( values.at( 5 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7858 const QVariant minOverlapValue = node->eval( parent, context );
7860 minOverlap = QgsExpressionUtils::getDoubleValue( minOverlapValue, parent );
7861 node = QgsExpressionUtils::getNode( values.at( 6 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7863 const QVariant minInscribedCircleRadiusValue = node->eval( parent, context );
7865 minInscribedCircleRadius = QgsExpressionUtils::getDoubleValue( minInscribedCircleRadiusValue, parent );
7866 node = QgsExpressionUtils::getNode( values.at( 7 ), parent );
7867 // Return measures is only effective when an expression is set
7868 returnDetails = !testOnly && node->eval( parent, context ).toBool(); //#spellok
7869 node = QgsExpressionUtils::getNode( values.at( 8 ), parent );
7870 // Sort by measures is only effective when an expression is set
7871 const QString sorting { node->eval( parent, context ).toString().toLower() };
7872 sortByMeasure = !testOnly && ( sorting.startsWith( "asc" ) || sorting.startsWith( "des" ) );
7873 sortAscending = sorting.startsWith( "asc" );
7874 requireMeasures = sortByMeasure || returnDetails; //#spellok
7875 overlapOrRadiusFilter = minInscribedCircleRadius != -1 || minOverlap != -1;
7876 }
7877
7878
7879 FEAT_FROM_CONTEXT( context, feat )
7880 const QgsGeometry geometry = feat.geometry();
7881
7882 if ( sourceLayer && targetLayer->crs() != sourceLayer->crs() )
7883 {
7884 QgsCoordinateTransformContext TransformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
7885 request.setDestinationCrs( sourceLayer->crs(), TransformContext ); //if crs are not the same, cached target will be reprojected to source crs
7886 }
7887
7888 bool sameLayers = ( sourceLayer && sourceLayer->id() == targetLayer->id() );
7889
7890 QgsRectangle intDomain = geometry.boundingBox();
7891 if ( bboxGrow != 0 )
7892 {
7893 intDomain.grow( bboxGrow ); //optional parameter to enlarge boundary context for touches and equals methods
7894 }
7895
7896 const QString cacheBase { QStringLiteral( "%1:%2:%3" ).arg( targetLayer->id(), subExpString, filterString ) };
7897
7898 // Cache (a local spatial index) is always enabled for nearest function (as we need QgsSpatialIndex::nearestNeighbor)
7899 // Otherwise, it can be toggled by the user
7900 QgsSpatialIndex spatialIndex;
7901 QgsVectorLayer *cachedTarget;
7902 QList<QgsFeature> features;
7903 if ( isNearestFunc || ( layerCanBeCached && cacheEnabled ) )
7904 {
7905 // If the cache (local spatial index) is enabled, we materialize the whole
7906 // layer, then do the request on that layer instead.
7907 const QString cacheLayer { QStringLiteral( "ovrlaylyr:%1" ).arg( cacheBase ) };
7908 const QString cacheIndex { QStringLiteral( "ovrlayidx:%1" ).arg( cacheBase ) };
7909
7910 if ( !context->hasCachedValue( cacheLayer ) ) // should check for same crs. if not the same we could think to reproject target layer before charging cache
7911 {
7912 cachedTarget = targetLayer->materialize( request );
7913 if ( layerCanBeCached )
7914 context->setCachedValue( cacheLayer, QVariant::fromValue( cachedTarget ) );
7915 }
7916 else
7917 {
7918 cachedTarget = context->cachedValue( cacheLayer ).value<QgsVectorLayer *>();
7919 }
7920
7921 if ( !context->hasCachedValue( cacheIndex ) )
7922 {
7923 spatialIndex = QgsSpatialIndex( cachedTarget->getFeatures(), nullptr, QgsSpatialIndex::FlagStoreFeatureGeometries );
7924 if ( layerCanBeCached )
7925 context->setCachedValue( cacheIndex, QVariant::fromValue( spatialIndex ) );
7926 }
7927 else
7928 {
7929 spatialIndex = context->cachedValue( cacheIndex ).value<QgsSpatialIndex>();
7930 }
7931
7932 QList<QgsFeatureId> fidsList;
7933 if ( isNearestFunc )
7934 {
7935 fidsList = spatialIndex.nearestNeighbor( geometry, sameLayers ? limit + 1 : limit, max_distance );
7936 }
7937 else
7938 {
7939 fidsList = spatialIndex.intersects( intDomain );
7940 }
7941
7942 QListIterator<QgsFeatureId> i( fidsList );
7943 while ( i.hasNext() )
7944 {
7945 QgsFeatureId fId2 = i.next();
7946 if ( sameLayers && feat.id() == fId2 )
7947 continue;
7948 features.append( cachedTarget->getFeature( fId2 ) );
7949 }
7950
7951 }
7952 else
7953 {
7954 // If the cache (local spatial index) is not enabled, we directly
7955 // get the features from the target layer
7956 request.setFilterRect( intDomain );
7957 QgsFeatureIterator fit = targetLayer->getFeatures( request );
7958 QgsFeature feat2;
7959 while ( fit.nextFeature( feat2 ) )
7960 {
7961 if ( sameLayers && feat.id() == feat2.id() )
7962 continue;
7963 features.append( feat2 );
7964 }
7965 }
7966
7967 QgsExpression subExpression;
7968 QgsExpressionContext subContext;
7969 if ( !testOnly )
7970 {
7971 const QString expCacheKey { QStringLiteral( "exp:%1" ).arg( cacheBase ) };
7972 const QString ctxCacheKey { QStringLiteral( "ctx:%1" ).arg( cacheBase ) };
7973
7974 if ( !context->hasCachedValue( expCacheKey ) || !context->hasCachedValue( ctxCacheKey ) )
7975 {
7976 subExpression = QgsExpression( subExpString );
7978 subExpression.prepare( &subContext );
7979 }
7980 else
7981 {
7982 subExpression = context->cachedValue( expCacheKey ).value<QgsExpression>();
7983 subContext = context->cachedValue( ctxCacheKey ).value<QgsExpressionContext>();
7984 }
7985 }
7986
7987 // //////////////////////////////////////////////////////////////////
7988 // Helper functions for geometry tests
7989
7990 // Test function for linestring geometries, returns TRUE if test passes
7991 auto testLinestring = [ = ]( const QgsGeometry intersection, double & overlapValue ) -> bool
7992 {
7993 bool testResult { false };
7994 // For return measures:
7995 QVector<double> overlapValues;
7996 const QgsGeometry merged { intersection.mergeLines() };
7997 for ( auto it = merged.const_parts_begin(); ! testResult && it != merged.const_parts_end(); ++it )
7998 {
7999 const QgsCurve *geom = qgsgeometry_cast< const QgsCurve * >( *it );
8000 // Check min overlap for intersection (if set)
8001 if ( minOverlap != -1 || requireMeasures )
8002 {
8003 overlapValue = geom->length();
8004 overlapValues.append( overlapValue );
8005 if ( minOverlap != -1 )
8006 {
8007 if ( overlapValue >= minOverlap )
8008 {
8009 testResult = true;
8010 }
8011 else
8012 {
8013 continue;
8014 }
8015 }
8016 }
8017 }
8018
8019 if ( ! overlapValues.isEmpty() )
8020 {
8021 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
8022 }
8023
8024 return testResult;
8025 };
8026
8027 // Test function for polygon geometries, returns TRUE if test passes
8028 auto testPolygon = [ = ]( const QgsGeometry intersection, double & radiusValue, double & overlapValue ) -> bool
8029 {
8030 // overlap and inscribed circle tests must be checked both (if the values are != -1)
8031 bool testResult { false };
8032 // For return measures:
8033 QVector<double> overlapValues;
8034 QVector<double> radiusValues;
8035 for ( auto it = intersection.const_parts_begin(); ( ! testResult || requireMeasures ) && it != intersection.const_parts_end(); ++it )
8036 {
8037 const QgsCurvePolygon *geom = qgsgeometry_cast< const QgsCurvePolygon * >( *it );
8038 // Check min overlap for intersection (if set)
8039 if ( minOverlap != -1 || requireMeasures )
8040 {
8041 overlapValue = geom->area();
8042 overlapValues.append( geom->area() );
8043 if ( minOverlap != - 1 )
8044 {
8045 if ( overlapValue >= minOverlap )
8046 {
8047 testResult = true;
8048 }
8049 else
8050 {
8051 continue;
8052 }
8053 }
8054 }
8055
8056 // Check min inscribed circle radius for intersection (if set)
8057 if ( minInscribedCircleRadius != -1 || requireMeasures )
8058 {
8059 const QgsRectangle bbox = geom->boundingBox();
8060 const double width = bbox.width();
8061 const double height = bbox.height();
8062 const double size = width > height ? width : height;
8063 const double tolerance = size / 100.0;
8064 radiusValue = QgsGeos( geom ).maximumInscribedCircle( tolerance )->length();
8065 testResult = radiusValue >= minInscribedCircleRadius;
8066 radiusValues.append( radiusValues );
8067 }
8068 } // end for parts
8069
8070 // Get the max values
8071 if ( !radiusValues.isEmpty() )
8072 {
8073 radiusValue = *std::max_element( radiusValues.cbegin(), radiusValues.cend() );
8074 }
8075
8076 if ( ! overlapValues.isEmpty() )
8077 {
8078 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
8079 }
8080
8081 return testResult;
8082
8083 };
8084
8085
8086 bool found = false;
8087 int foundCount = 0;
8088 QVariantList results;
8089
8090 QListIterator<QgsFeature> i( features );
8091 while ( i.hasNext() && ( sortByMeasure || limit == -1 || foundCount < limit ) )
8092 {
8093
8094 QgsFeature feat2 = i.next();
8095
8096
8097 if ( ! relationFunction || ( geometry.*relationFunction )( feat2.geometry() ) ) // Calls the method provided as template argument for the function (e.g. QgsGeometry::intersects)
8098 {
8099
8100 double overlapValue = -1;
8101 double radiusValue = -1;
8102
8103 if ( isIntersectsFunc && ( requireMeasures || overlapOrRadiusFilter ) )
8104 {
8105
8106 QgsGeometry intersection { geometry.intersection( feat2.geometry() ) };
8107
8108 // Pre-process collections: if the tested geometry is a polygon we take the polygons from the collection
8109 if ( intersection.wkbType() == Qgis::WkbType::GeometryCollection )
8110 {
8111 const QVector<QgsGeometry> geometries { intersection.asGeometryCollection() };
8112 intersection = QgsGeometry();
8113 QgsMultiPolygonXY poly;
8114 QgsMultiPolylineXY line;
8115 QgsMultiPointXY point;
8116 for ( const auto &geom : std::as_const( geometries ) )
8117 {
8118 switch ( geom.type() )
8119 {
8121 {
8122 poly.append( geom.asPolygon() );
8123 break;
8124 }
8126 {
8127 line.append( geom.asPolyline() );
8128 break;
8129 }
8131 {
8132 point.append( geom.asPoint() );
8133 break;
8134 }
8137 {
8138 break;
8139 }
8140 }
8141 }
8142
8143 switch ( geometry.type() )
8144 {
8146 {
8147 intersection = QgsGeometry::fromMultiPolygonXY( poly );
8148 break;
8149 }
8151 {
8152 intersection = QgsGeometry::fromMultiPolylineXY( line );
8153 break;
8154 }
8156 {
8157 intersection = QgsGeometry::fromMultiPointXY( point );
8158 break;
8159 }
8162 {
8163 break;
8164 }
8165 }
8166 }
8167
8168 // Depending on the intersection geometry type and on the geometry type of
8169 // the tested geometry we can run different tests and collect different measures
8170 // that can be used for sorting (if required).
8171 switch ( intersection.type() )
8172 {
8173
8175 {
8176
8177 // Overlap and inscribed circle tests must be checked both (if the values are != -1)
8178 bool testResult { testPolygon( intersection, radiusValue, overlapValue ) };
8179
8180 if ( ! testResult && overlapOrRadiusFilter )
8181 {
8182 continue;
8183 }
8184
8185 break;
8186 }
8187
8189 {
8190
8191 // If the intersection is a linestring and a minimum circle is required
8192 // we can discard this result immediately.
8193 if ( minInscribedCircleRadius != -1 )
8194 {
8195 continue;
8196 }
8197
8198 // Otherwise a test for the overlap value is performed.
8199 const bool testResult { testLinestring( intersection, overlapValue ) };
8200
8201 if ( ! testResult && overlapOrRadiusFilter )
8202 {
8203 continue;
8204 }
8205
8206 break;
8207 }
8208
8210 {
8211
8212 // If the intersection is a point and a minimum circle is required
8213 // we can discard this result immediately.
8214 if ( minInscribedCircleRadius != -1 )
8215 {
8216 continue;
8217 }
8218
8219 bool testResult { false };
8220 if ( minOverlap != -1 || requireMeasures )
8221 {
8222 // Initially set this to 0 because it's a point intersection...
8223 overlapValue = 0;
8224 // ... but if the target geometry is not a point and the source
8225 // geometry is a point, we must record the length or the area
8226 // of the intersected geometry and use that as a measure for
8227 // sorting or reporting.
8228 if ( geometry.type() == Qgis::GeometryType::Point )
8229 {
8230 switch ( feat2.geometry().type() )
8231 {
8235 {
8236 break;
8237 }
8239 {
8240 testResult = testLinestring( feat2.geometry(), overlapValue );
8241 break;
8242 }
8244 {
8245 testResult = testPolygon( feat2.geometry(), radiusValue, overlapValue );
8246 break;
8247 }
8248 }
8249 }
8250
8251 if ( ! testResult && overlapOrRadiusFilter )
8252 {
8253 continue;
8254 }
8255
8256 }
8257 break;
8258 }
8259
8262 {
8263 continue;
8264 }
8265 }
8266 }
8267
8268 found = true;
8269 foundCount++;
8270
8271 // We just want a single boolean result if there is any intersect: finish and return true
8272 if ( testOnly )
8273 break;
8274
8275 if ( !invert )
8276 {
8277 // We want a list of attributes / geometries / other expression values, evaluate now
8278 subContext.setFeature( feat2 );
8279 const QVariant expResult = subExpression.evaluate( &subContext );
8280
8281 if ( requireMeasures )
8282 {
8283 QVariantMap resultRecord;
8284 resultRecord.insert( QStringLiteral( "id" ), feat2.id() );
8285 resultRecord.insert( QStringLiteral( "result" ), expResult );
8286 // Overlap is always added because return measures was set
8287 resultRecord.insert( QStringLiteral( "overlap" ), overlapValue );
8288 // Radius is only added when is different than -1 (because for linestrings is not set)
8289 if ( radiusValue != -1 )
8290 {
8291 resultRecord.insert( QStringLiteral( "radius" ), radiusValue );
8292 }
8293 results.append( resultRecord );
8294 }
8295 else
8296 {
8297 results.append( expResult );
8298 }
8299 }
8300 else
8301 {
8302 // If not, results is a list of found ids, which we'll inverse and evaluate below
8303 results.append( feat2.id() );
8304 }
8305 }
8306 }
8307
8308 if ( testOnly )
8309 {
8310 if ( invert )
8311 found = !found;//for disjoint condition
8312 return found;
8313 }
8314
8315 if ( !invert )
8316 {
8317 if ( requireMeasures )
8318 {
8319 if ( sortByMeasure )
8320 {
8321 std::sort( results.begin(), results.end(), [ sortAscending ]( const QVariant & recordA, const QVariant & recordB ) -> bool
8322 {
8323 return sortAscending ?
8324 recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble()
8325 : recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble();
8326 } );
8327 }
8328 // Resize
8329 if ( limit > 0 && results.size() > limit )
8330 {
8331 results.erase( results.begin() + limit );
8332 }
8333
8334 if ( ! returnDetails ) //#spellok
8335 {
8336 QVariantList expResults;
8337 for ( auto it = results.constBegin(); it != results.constEnd(); ++it )
8338 {
8339 expResults.append( it->toMap().value( QStringLiteral( "result" ) ) );
8340 }
8341 return expResults;
8342 }
8343 }
8344
8345 return results;
8346 }
8347
8348 // for disjoint condition returns the results for cached layers not intersected feats
8349 QVariantList disjoint_results;
8350 QgsFeature feat2;
8351 QgsFeatureRequest request2;
8352 request2.setLimit( limit );
8353 if ( context )
8354 request2.setFeedback( context->feedback() );
8355 QgsFeatureIterator fi = targetLayer->getFeatures( request2 );
8356 while ( fi.nextFeature( feat2 ) )
8357 {
8358 if ( !results.contains( feat2.id() ) )
8359 {
8360 subContext.setFeature( feat2 );
8361 disjoint_results.append( subExpression.evaluate( &subContext ) );
8362 }
8363 }
8364 return disjoint_results;
8365
8366}
8367
8368// Intersect functions:
8369
8370static QVariant fcnGeomOverlayIntersects( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8371{
8372 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, false, 0, false, true );
8373}
8374
8375static QVariant fcnGeomOverlayContains( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8376{
8377 return executeGeomOverlay( values, context, parent, &QgsGeometry::contains );
8378}
8379
8380static QVariant fcnGeomOverlayCrosses( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8381{
8382 return executeGeomOverlay( values, context, parent, &QgsGeometry::crosses );
8383}
8384
8385static QVariant fcnGeomOverlayEquals( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8386{
8387 return executeGeomOverlay( values, context, parent, &QgsGeometry::equals, false, 0.01 ); //grow amount should adapt to current units
8388}
8389
8390static QVariant fcnGeomOverlayTouches( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8391{
8392 return executeGeomOverlay( values, context, parent, &QgsGeometry::touches, false, 0.01 ); //grow amount should adapt to current units
8393}
8394
8395static QVariant fcnGeomOverlayWithin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8396{
8397 return executeGeomOverlay( values, context, parent, &QgsGeometry::within );
8398}
8400static QVariant fcnGeomOverlayDisjoint( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8401{
8402 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, true, 0, false, true );
8403}
8404
8405static QVariant fcnGeomOverlayNearest( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
8406{
8407 return executeGeomOverlay( values, context, parent, nullptr, false, 0, true );
8408}
8409
8410const QList<QgsExpressionFunction *> &QgsExpression::Functions()
8411{
8412 // The construction of the list isn't thread-safe, and without the mutex,
8413 // crashes in the WFS provider may occur, since it can parse expressions
8414 // in parallel.
8415 // The mutex needs to be recursive.
8416 QMutexLocker locker( &sFunctionsMutex );
8417
8418 QList<QgsExpressionFunction *> &functions = *sFunctions();
8419
8420 if ( functions.isEmpty() )
8421 {
8423 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
8424 << QgsExpressionFunction::Parameter( QStringLiteral( "group_by" ), true )
8425 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true );
8426
8427 QgsExpressionFunction::ParameterList aggParamsConcat = aggParams;
8428 aggParamsConcat << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8429 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8430
8431 QgsExpressionFunction::ParameterList aggParamsArray = aggParams;
8432 aggParamsArray << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8433
8434 functions
8435 << new QgsStaticExpressionFunction( QStringLiteral( "sqrt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnSqrt, QStringLiteral( "Math" ) )
8436 << new QgsStaticExpressionFunction( QStringLiteral( "radians" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "degrees" ) ), fcnRadians, QStringLiteral( "Math" ) )
8437 << new QgsStaticExpressionFunction( QStringLiteral( "degrees" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "radians" ) ), fcnDegrees, QStringLiteral( "Math" ) )
8438 << new QgsStaticExpressionFunction( QStringLiteral( "azimuth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnAzimuth, QStringLiteral( "GeometryGroup" ) )
8439 << 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" ) )
8440 << new QgsStaticExpressionFunction( QStringLiteral( "inclination" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnInclination, QStringLiteral( "GeometryGroup" ) )
8441 << 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" ) )
8442 << new QgsStaticExpressionFunction( QStringLiteral( "abs" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAbs, QStringLiteral( "Math" ) )
8443 << new QgsStaticExpressionFunction( QStringLiteral( "cos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnCos, QStringLiteral( "Math" ) )
8444 << new QgsStaticExpressionFunction( QStringLiteral( "sin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnSin, QStringLiteral( "Math" ) )
8445 << new QgsStaticExpressionFunction( QStringLiteral( "tan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnTan, QStringLiteral( "Math" ) )
8446 << new QgsStaticExpressionFunction( QStringLiteral( "asin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAsin, QStringLiteral( "Math" ) )
8447 << new QgsStaticExpressionFunction( QStringLiteral( "acos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAcos, QStringLiteral( "Math" ) )
8448 << new QgsStaticExpressionFunction( QStringLiteral( "atan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAtan, QStringLiteral( "Math" ) )
8449 << new QgsStaticExpressionFunction( QStringLiteral( "atan2" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ), fcnAtan2, QStringLiteral( "Math" ) )
8450 << new QgsStaticExpressionFunction( QStringLiteral( "exp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnExp, QStringLiteral( "Math" ) )
8451 << new QgsStaticExpressionFunction( QStringLiteral( "ln" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLn, QStringLiteral( "Math" ) )
8452 << new QgsStaticExpressionFunction( QStringLiteral( "log10" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog10, QStringLiteral( "Math" ) )
8453 << new QgsStaticExpressionFunction( QStringLiteral( "log" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "base" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog, QStringLiteral( "Math" ) )
8454 << new QgsStaticExpressionFunction( QStringLiteral( "round" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 ), fcnRound, QStringLiteral( "Math" ) );
8455
8456 QgsStaticExpressionFunction *randFunc = new QgsStaticExpressionFunction( QStringLiteral( "rand" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true ), fcnRnd, QStringLiteral( "Math" ) );
8457 randFunc->setIsStatic( false );
8458 functions << randFunc;
8459
8460 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" ) );
8461 randfFunc->setIsStatic( false );
8462 functions << randfFunc;
8463
8464 functions
8465 << new QgsStaticExpressionFunction( QStringLiteral( "max" ), -1, fcnMax, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8466 << new QgsStaticExpressionFunction( QStringLiteral( "min" ), -1, fcnMin, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8467 << new QgsStaticExpressionFunction( QStringLiteral( "clamp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ), fcnClamp, QStringLiteral( "Math" ) )
8468 << 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" ) )
8469 << 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" ) )
8470 << 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" ) )
8471 << new QgsStaticExpressionFunction( QStringLiteral( "floor" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnFloor, QStringLiteral( "Math" ) )
8472 << new QgsStaticExpressionFunction( QStringLiteral( "ceil" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnCeil, QStringLiteral( "Math" ) )
8473 << new QgsStaticExpressionFunction( QStringLiteral( "pi" ), 0, fcnPi, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$pi" ) )
8474 << new QgsStaticExpressionFunction( QStringLiteral( "to_bool" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToBool, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "tobool" ), /* handlesNull = */ true )
8475 << new QgsStaticExpressionFunction( QStringLiteral( "to_int" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToInt, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toint" ) )
8476 << new QgsStaticExpressionFunction( QStringLiteral( "to_real" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToReal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toreal" ) )
8477 << 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" ) )
8478 << 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" ) )
8479 << 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" ) )
8480 << 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" ) )
8481 << 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" ) )
8482 << 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" ) )
8483 << 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" ) )
8484 << new QgsStaticExpressionFunction( QStringLiteral( "to_decimal" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToDecimal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todecimal" ) )
8485 << new QgsStaticExpressionFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8486 << new QgsStaticExpressionFunction( QStringLiteral( "nullif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value2" ) ), fcnNullIf, QStringLiteral( "Conditionals" ) )
8487 << 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 )
8488 << new QgsStaticExpressionFunction( QStringLiteral( "try" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "alternative" ), true, QVariant() ), fcnTry, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), true )
8489
8490 << new QgsStaticExpressionFunction( QStringLiteral( "aggregate" ),
8492 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8493 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8494 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8495 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8496 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8497 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8498 fcnAggregate,
8499 QStringLiteral( "Aggregates" ),
8500 QString(),
8501 []( const QgsExpressionNodeFunction * node )
8502 {
8503 // usesGeometry callback: return true if @parent variable is referenced
8504
8505 if ( !node )
8506 return true;
8507
8508 if ( !node->args() )
8509 return false;
8510
8511 QSet<QString> referencedVars;
8512 if ( node->args()->count() > 2 )
8513 {
8514 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8515 referencedVars = subExpressionNode->referencedVariables();
8516 }
8517
8518 if ( node->args()->count() > 3 )
8519 {
8520 QgsExpressionNode *filterNode = node->args()->at( 3 );
8521 referencedVars.unite( filterNode->referencedVariables() );
8522 }
8523 return referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() );
8524 },
8525 []( const QgsExpressionNodeFunction * node )
8526 {
8527 // referencedColumns callback: return AllAttributes if @parent variable is referenced
8528
8529 if ( !node )
8530 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8531
8532 if ( !node->args() )
8533 return QSet<QString>();
8534
8535 QSet<QString> referencedCols;
8536 QSet<QString> referencedVars;
8537
8538 if ( node->args()->count() > 2 )
8539 {
8540 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8541 referencedVars = subExpressionNode->referencedVariables();
8542 referencedCols = subExpressionNode->referencedColumns();
8543 }
8544 if ( node->args()->count() > 3 )
8545 {
8546 QgsExpressionNode *filterNode = node->args()->at( 3 );
8547 referencedVars = filterNode->referencedVariables();
8548 referencedCols.unite( filterNode->referencedColumns() );
8549 }
8550
8551 if ( referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() ) )
8552 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8553 else
8554 return referencedCols;
8555 },
8556 true
8557 )
8558
8559 << new QgsStaticExpressionFunction( QStringLiteral( "relation_aggregate" ), QgsExpressionFunction::ParameterList()
8560 << QgsExpressionFunction::Parameter( QStringLiteral( "relation" ) )
8561 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8562 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8563 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8564 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8565 fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true )
8566
8567 << new QgsStaticExpressionFunction( QStringLiteral( "count" ), aggParams, fcnAggregateCount, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8568 << new QgsStaticExpressionFunction( QStringLiteral( "count_distinct" ), aggParams, fcnAggregateCountDistinct, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8569 << new QgsStaticExpressionFunction( QStringLiteral( "count_missing" ), aggParams, fcnAggregateCountMissing, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8570 << new QgsStaticExpressionFunction( QStringLiteral( "minimum" ), aggParams, fcnAggregateMin, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8571 << new QgsStaticExpressionFunction( QStringLiteral( "maximum" ), aggParams, fcnAggregateMax, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8572 << new QgsStaticExpressionFunction( QStringLiteral( "sum" ), aggParams, fcnAggregateSum, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8573 << new QgsStaticExpressionFunction( QStringLiteral( "mean" ), aggParams, fcnAggregateMean, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8574 << new QgsStaticExpressionFunction( QStringLiteral( "median" ), aggParams, fcnAggregateMedian, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8575 << new QgsStaticExpressionFunction( QStringLiteral( "stdev" ), aggParams, fcnAggregateStdev, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8576 << new QgsStaticExpressionFunction( QStringLiteral( "range" ), aggParams, fcnAggregateRange, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8577 << new QgsStaticExpressionFunction( QStringLiteral( "minority" ), aggParams, fcnAggregateMinority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8578 << new QgsStaticExpressionFunction( QStringLiteral( "majority" ), aggParams, fcnAggregateMajority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8579 << new QgsStaticExpressionFunction( QStringLiteral( "q1" ), aggParams, fcnAggregateQ1, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8580 << new QgsStaticExpressionFunction( QStringLiteral( "q3" ), aggParams, fcnAggregateQ3, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8581 << new QgsStaticExpressionFunction( QStringLiteral( "iqr" ), aggParams, fcnAggregateIQR, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8582 << new QgsStaticExpressionFunction( QStringLiteral( "min_length" ), aggParams, fcnAggregateMinLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8583 << new QgsStaticExpressionFunction( QStringLiteral( "max_length" ), aggParams, fcnAggregateMaxLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8584 << new QgsStaticExpressionFunction( QStringLiteral( "collect" ), aggParams, fcnAggregateCollectGeometry, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8585 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate" ), aggParamsConcat, fcnAggregateStringConcat, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8586 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate_unique" ), aggParamsConcat, fcnAggregateStringConcatUnique, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8587 << new QgsStaticExpressionFunction( QStringLiteral( "array_agg" ), aggParamsArray, fcnAggregateArray, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8588
8589 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_match" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpMatch, QStringList() << QStringLiteral( "Conditionals" ) << QStringLiteral( "String" ) )
8590 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_matches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnRegexpMatches, QStringLiteral( "Arrays" ) )
8591
8592 << new QgsStaticExpressionFunction( QStringLiteral( "now" ), 0, fcnNow, QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$now" ) )
8593 << new QgsStaticExpressionFunction( QStringLiteral( "age" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime1" ) )
8594 << QgsExpressionFunction::Parameter( QStringLiteral( "datetime2" ) ),
8595 fcnAge, QStringLiteral( "Date and Time" ) )
8596 << new QgsStaticExpressionFunction( QStringLiteral( "year" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnYear, QStringLiteral( "Date and Time" ) )
8597 << new QgsStaticExpressionFunction( QStringLiteral( "month" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnMonth, QStringLiteral( "Date and Time" ) )
8598 << new QgsStaticExpressionFunction( QStringLiteral( "week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnWeek, QStringLiteral( "Date and Time" ) )
8599 << new QgsStaticExpressionFunction( QStringLiteral( "day" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDay, QStringLiteral( "Date and Time" ) )
8600 << new QgsStaticExpressionFunction( QStringLiteral( "hour" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnHour, QStringLiteral( "Date and Time" ) )
8601 << new QgsStaticExpressionFunction( QStringLiteral( "minute" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnMinute, QStringLiteral( "Date and Time" ) )
8602 << new QgsStaticExpressionFunction( QStringLiteral( "second" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnSeconds, QStringLiteral( "Date and Time" ) )
8603 << new QgsStaticExpressionFunction( QStringLiteral( "epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnEpoch, QStringLiteral( "Date and Time" ) )
8604 << new QgsStaticExpressionFunction( QStringLiteral( "datetime_from_epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "long" ) ), fcnDateTimeFromEpoch, QStringLiteral( "Date and Time" ) )
8605 << new QgsStaticExpressionFunction( QStringLiteral( "day_of_week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDayOfWeek, QStringLiteral( "Date and Time" ) )
8606 << new QgsStaticExpressionFunction( QStringLiteral( "make_date" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8607 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8608 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) ),
8609 fcnMakeDate, QStringLiteral( "Date and Time" ) )
8610 << new QgsStaticExpressionFunction( QStringLiteral( "make_time" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8611 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8612 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8613 fcnMakeTime, QStringLiteral( "Date and Time" ) )
8614 << new QgsStaticExpressionFunction( QStringLiteral( "make_datetime" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8615 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8616 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) )
8617 << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8618 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8619 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8620 fcnMakeDateTime, QStringLiteral( "Date and Time" ) )
8621 << new QgsStaticExpressionFunction( QStringLiteral( "make_interval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "years" ), true, 0 )
8622 << QgsExpressionFunction::Parameter( QStringLiteral( "months" ), true, 0 )
8623 << QgsExpressionFunction::Parameter( QStringLiteral( "weeks" ), true, 0 )
8624 << QgsExpressionFunction::Parameter( QStringLiteral( "days" ), true, 0 )
8625 << QgsExpressionFunction::Parameter( QStringLiteral( "hours" ), true, 0 )
8626 << QgsExpressionFunction::Parameter( QStringLiteral( "minutes" ), true, 0 )
8627 << QgsExpressionFunction::Parameter( QStringLiteral( "seconds" ), true, 0 ),
8628 fcnMakeInterval, QStringLiteral( "Date and Time" ) )
8629 << new QgsStaticExpressionFunction( QStringLiteral( "lower" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnLower, QStringLiteral( "String" ) )
8630 << new QgsStaticExpressionFunction( QStringLiteral( "upper" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnUpper, QStringLiteral( "String" ) )
8631 << new QgsStaticExpressionFunction( QStringLiteral( "title" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTitle, QStringLiteral( "String" ) )
8632 << new QgsStaticExpressionFunction( QStringLiteral( "trim" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTrim, QStringLiteral( "String" ) )
8633 << new QgsStaticExpressionFunction( QStringLiteral( "ltrim" ), QgsExpressionFunction::ParameterList()
8634 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8635 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnLTrim, QStringLiteral( "String" ) )
8636 << new QgsStaticExpressionFunction( QStringLiteral( "rtrim" ), QgsExpressionFunction::ParameterList()
8637 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8638 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnRTrim, QStringLiteral( "String" ) )
8639 << new QgsStaticExpressionFunction( QStringLiteral( "levenshtein" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLevenshtein, QStringLiteral( "Fuzzy Matching" ) )
8640 << new QgsStaticExpressionFunction( QStringLiteral( "longest_common_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLCS, QStringLiteral( "Fuzzy Matching" ) )
8641 << new QgsStaticExpressionFunction( QStringLiteral( "hamming_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnHamming, QStringLiteral( "Fuzzy Matching" ) )
8642 << new QgsStaticExpressionFunction( QStringLiteral( "soundex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnSoundex, QStringLiteral( "Fuzzy Matching" ) )
8643 << new QgsStaticExpressionFunction( QStringLiteral( "char" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "code" ) ), fcnChar, QStringLiteral( "String" ) )
8644 << new QgsStaticExpressionFunction( QStringLiteral( "ascii" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnAscii, QStringLiteral( "String" ) )
8645 << new QgsStaticExpressionFunction( QStringLiteral( "wordwrap" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "delimiter" ), true, "" ), fcnWordwrap, QStringLiteral( "String" ) )
8646 << new QgsStaticExpressionFunction( QStringLiteral( "length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ), true, "" ), fcnLength, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "GeometryGroup" ) )
8647 << new QgsStaticExpressionFunction( QStringLiteral( "length3D" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLength3D, QStringLiteral( "GeometryGroup" ) )
8648 << new QgsStaticExpressionFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) )
8649 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_replace" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) )
8650 << QgsExpressionFunction::Parameter( QStringLiteral( "replacement" ) ), fcnRegexpReplace, QStringLiteral( "String" ) )
8651 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpSubstr, QStringLiteral( "String" ) )
8652 << new QgsStaticExpressionFunction( QStringLiteral( "substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(),
8653 false, QSet< QString >(), false, QStringList(), true )
8654 << new QgsStaticExpressionFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8655 << new QgsStaticExpressionFunction( QStringLiteral( "strpos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "haystack" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "needle" ) ), fcnStrpos, QStringLiteral( "String" ) )
8656 << new QgsStaticExpressionFunction( QStringLiteral( "left" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnLeft, QStringLiteral( "String" ) )
8657 << new QgsStaticExpressionFunction( QStringLiteral( "right" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnRight, QStringLiteral( "String" ) )
8658 << new QgsStaticExpressionFunction( QStringLiteral( "rpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnRPad, QStringLiteral( "String" ) )
8659 << new QgsStaticExpressionFunction( QStringLiteral( "lpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnLPad, QStringLiteral( "String" ) )
8660 << new QgsStaticExpressionFunction( QStringLiteral( "format" ), -1, fcnFormatString, QStringLiteral( "String" ) )
8661 << new QgsStaticExpressionFunction( QStringLiteral( "format_number" ), QgsExpressionFunction::ParameterList()
8662 << QgsExpressionFunction::Parameter( QStringLiteral( "number" ) )
8663 << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 )
8664 << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() )
8665 << QgsExpressionFunction::Parameter( QStringLiteral( "omit_group_separators" ), true, false )
8666 << QgsExpressionFunction::Parameter( QStringLiteral( "trim_trailing_zeroes" ), true, false ), fcnFormatNumber, QStringLiteral( "String" ) )
8667 << 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" ) )
8668 << new QgsStaticExpressionFunction( QStringLiteral( "color_grayscale_average" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ), fcnColorGrayscaleAverage, QStringLiteral( "Color" ) )
8669 << new QgsStaticExpressionFunction( QStringLiteral( "color_mix_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color1" ) )
8670 << QgsExpressionFunction::Parameter( QStringLiteral( "color2" ) )
8671 << QgsExpressionFunction::Parameter( QStringLiteral( "ratio" ) ),
8672 fcnColorMixRgb, QStringLiteral( "Color" ) )
8673 << new QgsStaticExpressionFunction( QStringLiteral( "color_mix" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color1" ) )
8674 << QgsExpressionFunction::Parameter( QStringLiteral( "color2" ) )
8675 << QgsExpressionFunction::Parameter( QStringLiteral( "ratio" ) ),
8676 fcnColorMix, QStringLiteral( "Color" ) )
8677 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8678 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8679 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) ),
8680 fcnColorRgb, QStringLiteral( "Color" ) )
8681 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgbf" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8682 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8683 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) )
8684 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ), true, 1. ),
8685 fcnColorRgbF, QStringLiteral( "Color" ) )
8686 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgba" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8687 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8688 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) )
8689 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8690 fncColorRgba, QStringLiteral( "Color" ) )
8691 << new QgsStaticExpressionFunction( QStringLiteral( "ramp_color" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "ramp_name" ) )
8692 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8693 fcnRampColor, QStringLiteral( "Color" ) )
8694 << new QgsStaticExpressionFunction( QStringLiteral( "ramp_color_object" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "ramp_name" ) )
8695 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8696 fcnRampColorObject, QStringLiteral( "Color" ) )
8697 << new QgsStaticExpressionFunction( QStringLiteral( "create_ramp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
8698 << QgsExpressionFunction::Parameter( QStringLiteral( "discrete" ), true, false ),
8699 fcnCreateRamp, QStringLiteral( "Color" ) )
8700 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8701 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8702 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) ),
8703 fcnColorHsl, QStringLiteral( "Color" ) )
8704 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsla" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8705 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8706 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) )
8707 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8708 fncColorHsla, QStringLiteral( "Color" ) )
8709 << new QgsStaticExpressionFunction( QStringLiteral( "color_hslf" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8710 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8711 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) )
8712 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ), true, 1. ),
8713 fcnColorHslF, QStringLiteral( "Color" ) )
8714 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsv" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8715 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8716 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8717 fcnColorHsv, QStringLiteral( "Color" ) )
8718 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsva" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8719 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8720 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
8721 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8722 fncColorHsva, QStringLiteral( "Color" ) )
8723 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsvf" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8724 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8725 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
8726 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ), true, 1. ),
8727 fcnColorHsvF, QStringLiteral( "Color" ) )
8728 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyk" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8729 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8730 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8731 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) ),
8732 fcnColorCmyk, QStringLiteral( "Color" ) )
8733 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyka" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8734 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8735 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8736 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) )
8737 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8738 fncColorCmyka, QStringLiteral( "Color" ) )
8739 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmykf" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8740 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8741 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8742 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) )
8743 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ), true, 1. ),
8744 fcnColorCmykF, QStringLiteral( "Color" ) )
8745 << new QgsStaticExpressionFunction( QStringLiteral( "color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8746 << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ),
8747 fncColorPart, QStringLiteral( "Color" ) )
8748 << new QgsStaticExpressionFunction( QStringLiteral( "darker" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8749 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8750 fncDarker, QStringLiteral( "Color" ) )
8751 << new QgsStaticExpressionFunction( QStringLiteral( "lighter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8752 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8753 fncLighter, QStringLiteral( "Color" ) )
8754 << new QgsStaticExpressionFunction( QStringLiteral( "set_color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fncSetColorPart, QStringLiteral( "Color" ) )
8755
8756 // file info
8757 << new QgsStaticExpressionFunction( QStringLiteral( "base_file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8758 fcnBaseFileName, QStringLiteral( "Files and Paths" ) )
8759 << new QgsStaticExpressionFunction( QStringLiteral( "file_suffix" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8760 fcnFileSuffix, QStringLiteral( "Files and Paths" ) )
8761 << new QgsStaticExpressionFunction( QStringLiteral( "file_exists" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8762 fcnFileExists, QStringLiteral( "Files and Paths" ) )
8763 << new QgsStaticExpressionFunction( QStringLiteral( "file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8764 fcnFileName, QStringLiteral( "Files and Paths" ) )
8765 << new QgsStaticExpressionFunction( QStringLiteral( "is_file" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8766 fcnPathIsFile, QStringLiteral( "Files and Paths" ) )
8767 << new QgsStaticExpressionFunction( QStringLiteral( "is_directory" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8768 fcnPathIsDir, QStringLiteral( "Files and Paths" ) )
8769 << new QgsStaticExpressionFunction( QStringLiteral( "file_path" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8770 fcnFilePath, QStringLiteral( "Files and Paths" ) )
8771 << new QgsStaticExpressionFunction( QStringLiteral( "file_size" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8772 fcnFileSize, QStringLiteral( "Files and Paths" ) )
8773
8774 << new QgsStaticExpressionFunction( QStringLiteral( "exif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tag" ), true ),
8775 fcnExif, QStringLiteral( "Files and Paths" ) )
8776 << new QgsStaticExpressionFunction( QStringLiteral( "exif_geotag" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8777 fcnExifGeoTag, QStringLiteral( "GeometryGroup" ) )
8778
8779 // hash
8780 << new QgsStaticExpressionFunction( QStringLiteral( "hash" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "method" ) ),
8781 fcnGenericHash, QStringLiteral( "Conversions" ) )
8782 << new QgsStaticExpressionFunction( QStringLiteral( "md5" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8783 fcnHashMd5, QStringLiteral( "Conversions" ) )
8784 << new QgsStaticExpressionFunction( QStringLiteral( "sha256" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8785 fcnHashSha256, QStringLiteral( "Conversions" ) )
8786
8787 //base64
8788 << new QgsStaticExpressionFunction( QStringLiteral( "to_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8789 fcnToBase64, QStringLiteral( "Conversions" ) )
8790 << new QgsStaticExpressionFunction( QStringLiteral( "from_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8791 fcnFromBase64, QStringLiteral( "Conversions" ) )
8792
8793 // deprecated stuff - hidden from users
8794 << new QgsStaticExpressionFunction( QStringLiteral( "$scale" ), QgsExpressionFunction::ParameterList(), fcnMapScale, QStringLiteral( "deprecated" ) );
8795
8796 QgsStaticExpressionFunction *geomFunc = new QgsStaticExpressionFunction( QStringLiteral( "$geometry" ), 0, fcnGeometry, QStringLiteral( "GeometryGroup" ), QString(), true );
8797 geomFunc->setIsStatic( false );
8798 functions << geomFunc;
8799
8800 QgsStaticExpressionFunction *areaFunc = new QgsStaticExpressionFunction( QStringLiteral( "$area" ), 0, fcnGeomArea, QStringLiteral( "GeometryGroup" ), QString(), true );
8801 areaFunc->setIsStatic( false );
8802 functions << areaFunc;
8803
8804 functions << new QgsStaticExpressionFunction( QStringLiteral( "area" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnArea, QStringLiteral( "GeometryGroup" ) );
8805
8806 QgsStaticExpressionFunction *lengthFunc = new QgsStaticExpressionFunction( QStringLiteral( "$length" ), 0, fcnGeomLength, QStringLiteral( "GeometryGroup" ), QString(), true );
8807 lengthFunc->setIsStatic( false );
8808 functions << lengthFunc;
8809
8810 QgsStaticExpressionFunction *perimeterFunc = new QgsStaticExpressionFunction( QStringLiteral( "$perimeter" ), 0, fcnGeomPerimeter, QStringLiteral( "GeometryGroup" ), QString(), true );
8811 perimeterFunc->setIsStatic( false );
8812 functions << perimeterFunc;
8813
8814 functions << new QgsStaticExpressionFunction( QStringLiteral( "perimeter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPerimeter, QStringLiteral( "GeometryGroup" ) );
8815
8816 functions << new QgsStaticExpressionFunction( QStringLiteral( "roundness" ),
8818 fcnRoundness, QStringLiteral( "GeometryGroup" ) );
8819
8820 QgsStaticExpressionFunction *xFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x" ), 0, fcnX, QStringLiteral( "GeometryGroup" ), QString(), true );
8821 xFunc->setIsStatic( false );
8822 functions << xFunc;
8823
8824 QgsStaticExpressionFunction *yFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y" ), 0, fcnY, QStringLiteral( "GeometryGroup" ), QString(), true );
8825 yFunc->setIsStatic( false );
8826 functions << yFunc;
8827
8828 QgsStaticExpressionFunction *zFunc = new QgsStaticExpressionFunction( QStringLiteral( "$z" ), 0, fcnZ, QStringLiteral( "GeometryGroup" ), QString(), true );
8829 zFunc->setIsStatic( false );
8830 functions << zFunc;
8831
8832 QMap< QString, QgsExpressionFunction::FcnEval > geometry_overlay_definitions
8833 {
8834 { QStringLiteral( "overlay_intersects" ), fcnGeomOverlayIntersects },
8835 { QStringLiteral( "overlay_contains" ), fcnGeomOverlayContains },
8836 { QStringLiteral( "overlay_crosses" ), fcnGeomOverlayCrosses },
8837 { QStringLiteral( "overlay_equals" ), fcnGeomOverlayEquals },
8838 { QStringLiteral( "overlay_touches" ), fcnGeomOverlayTouches },
8839 { QStringLiteral( "overlay_disjoint" ), fcnGeomOverlayDisjoint },
8840 { QStringLiteral( "overlay_within" ), fcnGeomOverlayWithin },
8841 };
8842 QMapIterator< QString, QgsExpressionFunction::FcnEval > i( geometry_overlay_definitions );
8843 while ( i.hasNext() )
8844 {
8845 i.next();
8847 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8848 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8849 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8850 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( -1 ), true )
8851 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false )
8852 << QgsExpressionFunction::Parameter( QStringLiteral( "min_overlap" ), true, QVariant( -1 ), false )
8853 << QgsExpressionFunction::Parameter( QStringLiteral( "min_inscribed_circle_radius" ), true, QVariant( -1 ), false )
8854 << QgsExpressionFunction::Parameter( QStringLiteral( "return_details" ), true, false, false )
8855 << QgsExpressionFunction::Parameter( QStringLiteral( "sort_by_intersection_size" ), true, QString(), false ),
8856 i.value(), QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8857
8858 // The current feature is accessed for the geometry, so this should not be cached
8859 fcnGeomOverlayFunc->setIsStatic( false );
8860 functions << fcnGeomOverlayFunc;
8861 }
8862
8863 QgsStaticExpressionFunction *fcnGeomOverlayNearestFunc = new QgsStaticExpressionFunction( QStringLiteral( "overlay_nearest" ), QgsExpressionFunction::ParameterList()
8864 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8865 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8866 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8867 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( 1 ), true )
8868 << QgsExpressionFunction::Parameter( QStringLiteral( "max_distance" ), true, 0 )
8869 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false ),
8870 fcnGeomOverlayNearest, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8871 // The current feature is accessed for the geometry, so this should not be cached
8872 fcnGeomOverlayNearestFunc->setIsStatic( false );
8873 functions << fcnGeomOverlayNearestFunc;
8874
8875 functions
8876 << new QgsStaticExpressionFunction( QStringLiteral( "is_valid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomIsValid, QStringLiteral( "GeometryGroup" ) )
8877 << new QgsStaticExpressionFunction( QStringLiteral( "x" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomX, QStringLiteral( "GeometryGroup" ) )
8878 << new QgsStaticExpressionFunction( QStringLiteral( "y" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomY, QStringLiteral( "GeometryGroup" ) )
8879 << new QgsStaticExpressionFunction( QStringLiteral( "z" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomZ, QStringLiteral( "GeometryGroup" ) )
8880 << new QgsStaticExpressionFunction( QStringLiteral( "m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomM, QStringLiteral( "GeometryGroup" ) )
8881 << new QgsStaticExpressionFunction( QStringLiteral( "point_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ), fcnPointN, QStringLiteral( "GeometryGroup" ) )
8882 << new QgsStaticExpressionFunction( QStringLiteral( "start_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnStartPoint, QStringLiteral( "GeometryGroup" ) )
8883 << new QgsStaticExpressionFunction( QStringLiteral( "end_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnEndPoint, QStringLiteral( "GeometryGroup" ) )
8884 << new QgsStaticExpressionFunction( QStringLiteral( "nodes_to_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8885 << QgsExpressionFunction::Parameter( QStringLiteral( "ignore_closing_nodes" ), true, false ),
8886 fcnNodesToPoints, QStringLiteral( "GeometryGroup" ) )
8887 << new QgsStaticExpressionFunction( QStringLiteral( "segments_to_lines" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnSegmentsToLines, QStringLiteral( "GeometryGroup" ) )
8888 << new QgsStaticExpressionFunction( QStringLiteral( "collect_geometries" ), -1, fcnCollectGeometries, QStringLiteral( "GeometryGroup" ) )
8889 << new QgsStaticExpressionFunction( QStringLiteral( "make_point" ), -1, fcnMakePoint, QStringLiteral( "GeometryGroup" ) )
8890 << new QgsStaticExpressionFunction( QStringLiteral( "make_point_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
8891 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) )
8892 << QgsExpressionFunction::Parameter( QStringLiteral( "m" ) ),
8893 fcnMakePointM, QStringLiteral( "GeometryGroup" ) )
8894 << new QgsStaticExpressionFunction( QStringLiteral( "make_line" ), -1, fcnMakeLine, QStringLiteral( "GeometryGroup" ) )
8895 << new QgsStaticExpressionFunction( QStringLiteral( "make_polygon" ), -1, fcnMakePolygon, QStringLiteral( "GeometryGroup" ) )
8896 << new QgsStaticExpressionFunction( QStringLiteral( "make_triangle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8897 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8898 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) ),
8899 fcnMakeTriangle, QStringLiteral( "GeometryGroup" ) )
8900 << new QgsStaticExpressionFunction( QStringLiteral( "make_circle" ), QgsExpressionFunction::ParameterList()
8901 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8902 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8903 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8904 fcnMakeCircle, QStringLiteral( "GeometryGroup" ) )
8905 << new QgsStaticExpressionFunction( QStringLiteral( "make_ellipse" ), QgsExpressionFunction::ParameterList()
8906 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8907 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_major_axis" ) )
8908 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_minor_axis" ) )
8909 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
8910 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8911 fcnMakeEllipse, QStringLiteral( "GeometryGroup" ) )
8912 << new QgsStaticExpressionFunction( QStringLiteral( "make_regular_polygon" ), QgsExpressionFunction::ParameterList()
8913 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8914 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8915 << QgsExpressionFunction::Parameter( QStringLiteral( "number_sides" ) )
8916 << QgsExpressionFunction::Parameter( QStringLiteral( "circle" ), true, 0 ),
8917 fcnMakeRegularPolygon, QStringLiteral( "GeometryGroup" ) )
8918 << new QgsStaticExpressionFunction( QStringLiteral( "make_square" ), QgsExpressionFunction::ParameterList()
8919 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8920 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) ),
8921 fcnMakeSquare, QStringLiteral( "GeometryGroup" ) )
8922 << new QgsStaticExpressionFunction( QStringLiteral( "make_rectangle_3points" ), QgsExpressionFunction::ParameterList()
8923 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8924 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8925 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) )
8926 << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, 0 ),
8927 fcnMakeRectangleFrom3Points, QStringLiteral( "GeometryGroup" ) )
8928 << new QgsStaticExpressionFunction( QStringLiteral( "make_valid" ), QgsExpressionFunction::ParameterList
8929 {
8930 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8931#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
8932 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "linework" ) ),
8933#else
8934 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "structure" ) ),
8935#endif
8936 QgsExpressionFunction::Parameter( QStringLiteral( "keep_collapsed" ), true, false )
8937 }, fcnGeomMakeValid, QStringLiteral( "GeometryGroup" ) );
8938
8939 functions << new QgsStaticExpressionFunction( QStringLiteral( "x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnXat, QStringLiteral( "GeometryGroup" ) );
8940 functions << new QgsStaticExpressionFunction( QStringLiteral( "y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnYat, QStringLiteral( "GeometryGroup" ) );
8941 functions << new QgsStaticExpressionFunction( QStringLiteral( "z_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnZat, QStringLiteral( "GeometryGroup" ) );
8942 functions << new QgsStaticExpressionFunction( QStringLiteral( "m_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnMat, QStringLiteral( "GeometryGroup" ) );
8943
8944 QgsStaticExpressionFunction *xAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldXat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "xat" ) );
8945 xAtFunc->setIsStatic( false );
8946 functions << xAtFunc;
8947
8948
8949 QgsStaticExpressionFunction *yAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldYat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "yat" ) );
8950 yAtFunc->setIsStatic( false );
8951 functions << yAtFunc;
8952
8953 functions
8954 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_type" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeometryType, QStringLiteral( "GeometryGroup" ) )
8955 << new QgsStaticExpressionFunction( QStringLiteral( "x_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmin" ) )
8956 << new QgsStaticExpressionFunction( QStringLiteral( "x_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmax" ) )
8957 << new QgsStaticExpressionFunction( QStringLiteral( "y_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymin" ) )
8958 << new QgsStaticExpressionFunction( QStringLiteral( "y_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymax" ) )
8959 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ), fcnGeomFromWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromWKT" ) )
8960 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "binary" ) ), fcnGeomFromWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
8961 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_gml" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "gml" ) ), fcnGeomFromGML, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromGML" ) )
8962 << new QgsStaticExpressionFunction( QStringLiteral( "flip_coordinates" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnFlipCoordinates, QStringLiteral( "GeometryGroup" ) )
8963 << new QgsStaticExpressionFunction( QStringLiteral( "relate" ), -1, fcnRelate, QStringLiteral( "GeometryGroup" ) )
8964 << 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" ) )
8965 << new QgsStaticExpressionFunction( QStringLiteral( "disjoint" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8966 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8967 fcnDisjoint, QStringLiteral( "GeometryGroup" ) )
8968 << new QgsStaticExpressionFunction( QStringLiteral( "intersects" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8969 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8970 fcnIntersects, QStringLiteral( "GeometryGroup" ) )
8971 << new QgsStaticExpressionFunction( QStringLiteral( "touches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8972 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8973 fcnTouches, QStringLiteral( "GeometryGroup" ) )
8974 << new QgsStaticExpressionFunction( QStringLiteral( "crosses" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8975 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8976 fcnCrosses, QStringLiteral( "GeometryGroup" ) )
8977 << new QgsStaticExpressionFunction( QStringLiteral( "contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8978 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8979 fcnContains, QStringLiteral( "GeometryGroup" ) )
8980 << new QgsStaticExpressionFunction( QStringLiteral( "overlaps" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8981 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8982 fcnOverlaps, QStringLiteral( "GeometryGroup" ) )
8983 << new QgsStaticExpressionFunction( QStringLiteral( "within" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8984 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8985 fcnWithin, QStringLiteral( "GeometryGroup" ) )
8986 << new QgsStaticExpressionFunction( QStringLiteral( "translate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8987 << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) )
8988 << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ),
8989 fcnTranslate, QStringLiteral( "GeometryGroup" ) )
8990 << new QgsStaticExpressionFunction( QStringLiteral( "rotate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8991 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation" ) )
8992 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true )
8993 << QgsExpressionFunction::Parameter( QStringLiteral( "per_part" ), true, false ),
8994 fcnRotate, QStringLiteral( "GeometryGroup" ) )
8995 << new QgsStaticExpressionFunction( QStringLiteral( "scale" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8996 << QgsExpressionFunction::Parameter( QStringLiteral( "x_scale" ) )
8997 << QgsExpressionFunction::Parameter( QStringLiteral( "y_scale" ) )
8998 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true ),
8999 fcnScale, QStringLiteral( "GeometryGroup" ) )
9000 << new QgsStaticExpressionFunction( QStringLiteral( "affine_transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9001 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_x" ) )
9002 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_y" ) )
9003 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation_z" ) )
9004 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_x" ) )
9005 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_y" ) )
9006 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_z" ), true, 0 )
9007 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_m" ), true, 0 )
9008 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_z" ), true, 1 )
9009 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_m" ), true, 1 ),
9010 fcnAffineTransform, QStringLiteral( "GeometryGroup" ) )
9011 << new QgsStaticExpressionFunction( QStringLiteral( "buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9012 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
9013 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8 )
9014 << QgsExpressionFunction::Parameter( QStringLiteral( "cap" ), true, QStringLiteral( "round" ) )
9015 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, QStringLiteral( "round" ) )
9016 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2 ),
9017 fcnBuffer, QStringLiteral( "GeometryGroup" ) )
9018 << new QgsStaticExpressionFunction( QStringLiteral( "force_rhr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9019 fcnForceRHR, QStringLiteral( "GeometryGroup" ) )
9020 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_cw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9021 fcnForcePolygonCW, QStringLiteral( "GeometryGroup" ) )
9022 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_ccw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9023 fcnForcePolygonCCW, QStringLiteral( "GeometryGroup" ) )
9024 << new QgsStaticExpressionFunction( QStringLiteral( "wedge_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
9025 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
9026 << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) )
9027 << QgsExpressionFunction::Parameter( QStringLiteral( "outer_radius" ) )
9028 << QgsExpressionFunction::Parameter( QStringLiteral( "inner_radius" ), true, 0.0 ), fcnWedgeBuffer, QStringLiteral( "GeometryGroup" ) )
9029 << new QgsStaticExpressionFunction( QStringLiteral( "tapered_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9030 << QgsExpressionFunction::Parameter( QStringLiteral( "start_width" ) )
9031 << QgsExpressionFunction::Parameter( QStringLiteral( "end_width" ) )
9032 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
9033 , fcnTaperedBuffer, QStringLiteral( "GeometryGroup" ) )
9034 << new QgsStaticExpressionFunction( QStringLiteral( "buffer_by_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9035 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
9036 , fcnBufferByM, QStringLiteral( "GeometryGroup" ) )
9037 << new QgsStaticExpressionFunction( QStringLiteral( "offset_curve" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9038 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
9039 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
9040 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
9041 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
9042 fcnOffsetCurve, QStringLiteral( "GeometryGroup" ) )
9043 << new QgsStaticExpressionFunction( QStringLiteral( "single_sided_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9044 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
9045 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
9046 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
9047 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
9048 fcnSingleSidedBuffer, QStringLiteral( "GeometryGroup" ) )
9049 << new QgsStaticExpressionFunction( QStringLiteral( "extend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9050 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) )
9051 << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ),
9052 fcnExtend, QStringLiteral( "GeometryGroup" ) )
9053 << new QgsStaticExpressionFunction( QStringLiteral( "centroid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCentroid, QStringLiteral( "GeometryGroup" ) )
9054 << new QgsStaticExpressionFunction( QStringLiteral( "point_on_surface" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) )
9055 << new QgsStaticExpressionFunction( QStringLiteral( "pole_of_inaccessibility" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9056 << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnPoleOfInaccessibility, QStringLiteral( "GeometryGroup" ) )
9057 << new QgsStaticExpressionFunction( QStringLiteral( "reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnReverse, QStringLiteral( "GeometryGroup" ) )
9058 << new QgsStaticExpressionFunction( QStringLiteral( "exterior_ring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnExteriorRing, QStringLiteral( "GeometryGroup" ) )
9059 << new QgsStaticExpressionFunction( QStringLiteral( "interior_ring_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9060 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
9061 fcnInteriorRingN, QStringLiteral( "GeometryGroup" ) )
9062 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9063 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
9064 fcnGeometryN, QStringLiteral( "GeometryGroup" ) )
9065 << new QgsStaticExpressionFunction( QStringLiteral( "boundary" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundary, QStringLiteral( "GeometryGroup" ) )
9066 << new QgsStaticExpressionFunction( QStringLiteral( "line_merge" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLineMerge, QStringLiteral( "GeometryGroup" ) )
9067 << new QgsStaticExpressionFunction( QStringLiteral( "shared_paths" ), QgsExpressionFunction::ParameterList
9068 {
9069 QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ),
9070 QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
9071 }, fcnSharedPaths, QStringLiteral( "GeometryGroup" ) )
9072 << new QgsStaticExpressionFunction( QStringLiteral( "bounds" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBounds, QStringLiteral( "GeometryGroup" ) )
9073 << new QgsStaticExpressionFunction( QStringLiteral( "simplify" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplify, QStringLiteral( "GeometryGroup" ) )
9074 << new QgsStaticExpressionFunction( QStringLiteral( "simplify_vw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplifyVW, QStringLiteral( "GeometryGroup" ) )
9075 << new QgsStaticExpressionFunction( QStringLiteral( "smooth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "iterations" ), true, 1 )
9076 << QgsExpressionFunction::Parameter( QStringLiteral( "offset" ), true, 0.25 )
9077 << QgsExpressionFunction::Parameter( QStringLiteral( "min_length" ), true, -1 )
9078 << QgsExpressionFunction::Parameter( QStringLiteral( "max_angle" ), true, 180 ), fcnSmooth, QStringLiteral( "GeometryGroup" ) )
9079 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave" ),
9080 {
9081 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9082 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
9083 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
9084 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
9085 }, fcnTriangularWave, QStringLiteral( "GeometryGroup" ) )
9086 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave_randomized" ),
9087 {
9088 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9089 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
9090 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
9091 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
9092 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
9093 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
9094 }, fcnTriangularWaveRandomized, QStringLiteral( "GeometryGroup" ) )
9095 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave" ),
9096 {
9097 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9098 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
9099 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
9100 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
9101 }, fcnSquareWave, QStringLiteral( "GeometryGroup" ) )
9102 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave_randomized" ),
9103 {
9104 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9105 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
9106 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
9107 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
9108 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
9109 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
9110 }, fcnSquareWaveRandomized, QStringLiteral( "GeometryGroup" ) )
9111 << new QgsStaticExpressionFunction( QStringLiteral( "wave" ),
9112 {
9113 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9114 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
9115 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
9116 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
9117 }, fcnRoundWave, QStringLiteral( "GeometryGroup" ) )
9118 << new QgsStaticExpressionFunction( QStringLiteral( "wave_randomized" ),
9119 {
9120 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9121 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
9122 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
9123 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
9124 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
9125 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
9126 }, fcnRoundWaveRandomized, QStringLiteral( "GeometryGroup" ) )
9127 << new QgsStaticExpressionFunction( QStringLiteral( "apply_dash_pattern" ),
9128 {
9129 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9130 QgsExpressionFunction::Parameter( QStringLiteral( "pattern" ) ),
9131 QgsExpressionFunction::Parameter( QStringLiteral( "start_rule" ), true, QStringLiteral( "no_rule" ) ),
9132 QgsExpressionFunction::Parameter( QStringLiteral( "end_rule" ), true, QStringLiteral( "no_rule" ) ),
9133 QgsExpressionFunction::Parameter( QStringLiteral( "adjustment" ), true, QStringLiteral( "both" ) ),
9134 QgsExpressionFunction::Parameter( QStringLiteral( "pattern_offset" ), true, 0 ),
9135 }, fcnApplyDashPattern, QStringLiteral( "GeometryGroup" ) )
9136 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_count" ),
9137 {
9138 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9139 QgsExpressionFunction::Parameter( QStringLiteral( "vertices" ) )
9140 }, fcnDensifyByCount, QStringLiteral( "GeometryGroup" ) )
9141 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_distance" ),
9142 {
9143 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9144 QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
9145 }, fcnDensifyByDistance, QStringLiteral( "GeometryGroup" ) )
9146 << new QgsStaticExpressionFunction( QStringLiteral( "num_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumPoints, QStringLiteral( "GeometryGroup" ) )
9147 << new QgsStaticExpressionFunction( QStringLiteral( "num_interior_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumInteriorRings, QStringLiteral( "GeometryGroup" ) )
9148 << new QgsStaticExpressionFunction( QStringLiteral( "num_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumRings, QStringLiteral( "GeometryGroup" ) )
9149 << new QgsStaticExpressionFunction( QStringLiteral( "num_geometries" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumGeometries, QStringLiteral( "GeometryGroup" ) )
9150 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_width" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsWidth, QStringLiteral( "GeometryGroup" ) )
9151 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_height" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsHeight, QStringLiteral( "GeometryGroup" ) )
9152 << new QgsStaticExpressionFunction( QStringLiteral( "is_closed" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsClosed, QStringLiteral( "GeometryGroup" ) )
9153 << new QgsStaticExpressionFunction( QStringLiteral( "close_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCloseLine, QStringLiteral( "GeometryGroup" ) )
9154 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmpty, QStringLiteral( "GeometryGroup" ) )
9155 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty_or_null" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmptyOrNull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList(), true )
9156 << new QgsStaticExpressionFunction( QStringLiteral( "convex_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnConvexHull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "convexHull" ) )
9157#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
9158 << new QgsStaticExpressionFunction( QStringLiteral( "concave_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9159 << QgsExpressionFunction::Parameter( QStringLiteral( "target_percent" ) )
9160 << QgsExpressionFunction::Parameter( QStringLiteral( "allow_holes" ), true, false ), fcnConcaveHull, QStringLiteral( "GeometryGroup" ) )
9161#endif
9162 << new QgsStaticExpressionFunction( QStringLiteral( "oriented_bbox" ), QgsExpressionFunction::ParameterList()
9163 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9164 fcnOrientedBBox, QStringLiteral( "GeometryGroup" ) )
9165 << new QgsStaticExpressionFunction( QStringLiteral( "main_angle" ), QgsExpressionFunction::ParameterList()
9166 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9167 fcnMainAngle, QStringLiteral( "GeometryGroup" ) )
9168 << new QgsStaticExpressionFunction( QStringLiteral( "minimal_circle" ), QgsExpressionFunction::ParameterList()
9169 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9170 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
9171 fcnMinimalCircle, QStringLiteral( "GeometryGroup" ) )
9172 << new QgsStaticExpressionFunction( QStringLiteral( "difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9173 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9174 fcnDifference, QStringLiteral( "GeometryGroup" ) )
9175 << new QgsStaticExpressionFunction( QStringLiteral( "distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9176 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9177 fcnDistance, QStringLiteral( "GeometryGroup" ) )
9178 << new QgsStaticExpressionFunction( QStringLiteral( "hausdorff_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
9179 << QgsExpressionFunction::Parameter( QStringLiteral( "densify_fraction" ), true ),
9180 fcnHausdorffDistance, QStringLiteral( "GeometryGroup" ) )
9181 << new QgsStaticExpressionFunction( QStringLiteral( "intersection" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9182 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9183 fcnIntersection, QStringLiteral( "GeometryGroup" ) )
9184 << new QgsStaticExpressionFunction( QStringLiteral( "sym_difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9185 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9186 fcnSymDifference, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "symDifference" ) )
9187 << new QgsStaticExpressionFunction( QStringLiteral( "combine" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9188 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9189 fcnCombine, QStringLiteral( "GeometryGroup" ) )
9190 << new QgsStaticExpressionFunction( QStringLiteral( "union" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9191 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9192 fcnCombine, QStringLiteral( "GeometryGroup" ) )
9193 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9194 << QgsExpressionFunction::Parameter( QStringLiteral( "precision" ), true, 8.0 ),
9195 fcnGeomToWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomToWKT" ) )
9196 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9197 fcnGeomToWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
9198 << new QgsStaticExpressionFunction( QStringLiteral( "geometry" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetGeometry, QStringLiteral( "GeometryGroup" ), QString(), true )
9199 << new QgsStaticExpressionFunction( QStringLiteral( "transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9200 << QgsExpressionFunction::Parameter( QStringLiteral( "source_auth_id" ) )
9201 << QgsExpressionFunction::Parameter( QStringLiteral( "dest_auth_id" ) ),
9202 fcnTransformGeometry, QStringLiteral( "GeometryGroup" ) )
9203 << new QgsStaticExpressionFunction( QStringLiteral( "extrude" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9204 << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
9205 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) ),
9206 fcnExtrude, QStringLiteral( "GeometryGroup" ), QString() )
9207 << new QgsStaticExpressionFunction( QStringLiteral( "is_multipart" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9208 fcnGeomIsMultipart, QStringLiteral( "GeometryGroup" ) )
9209 << new QgsStaticExpressionFunction( QStringLiteral( "z_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9210 fcnZMax, QStringLiteral( "GeometryGroup" ) )
9211 << new QgsStaticExpressionFunction( QStringLiteral( "z_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9212 fcnZMin, QStringLiteral( "GeometryGroup" ) )
9213 << new QgsStaticExpressionFunction( QStringLiteral( "m_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9214 fcnMMax, QStringLiteral( "GeometryGroup" ) )
9215 << new QgsStaticExpressionFunction( QStringLiteral( "m_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9216 fcnMMin, QStringLiteral( "GeometryGroup" ) )
9217 << new QgsStaticExpressionFunction( QStringLiteral( "sinuosity" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9218 fcnSinuosity, QStringLiteral( "GeometryGroup" ) )
9219 << new QgsStaticExpressionFunction( QStringLiteral( "straight_distance_2d" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
9220 fcnStraightDistance2d, QStringLiteral( "GeometryGroup" ) );
9221
9222
9223 QgsStaticExpressionFunction *orderPartsFunc = new QgsStaticExpressionFunction( QStringLiteral( "order_parts" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9224 << QgsExpressionFunction::Parameter( QStringLiteral( "orderby" ) )
9225 << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ),
9226 fcnOrderParts, QStringLiteral( "GeometryGroup" ), QString() );
9227
9228 orderPartsFunc->setIsStaticFunction(
9229 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9230 {
9231 const QList< QgsExpressionNode *> argList = node->args()->list();
9232 for ( QgsExpressionNode *argNode : argList )
9233 {
9234 if ( !argNode->isStatic( parent, context ) )
9235 return false;
9236 }
9237
9238 if ( node->args()->count() > 1 )
9239 {
9240 QgsExpressionNode *argNode = node->args()->at( 1 );
9241
9242 QString expString = argNode->eval( parent, context ).toString();
9243
9244 QgsExpression e( expString );
9245
9246 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
9247 return true;
9248 }
9249
9250 return true;
9251 } );
9252
9253 orderPartsFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9254 {
9255 if ( node->args()->count() > 1 )
9256 {
9257 QgsExpressionNode *argNode = node->args()->at( 1 );
9258 QString expression = argNode->eval( parent, context ).toString();
9260 e.prepare( context );
9261 context->setCachedValue( expression, QVariant::fromValue( e ) );
9262 }
9263 return true;
9264 }
9265 );
9266 functions << orderPartsFunc;
9267
9268 functions
9269 << new QgsStaticExpressionFunction( QStringLiteral( "closest_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9270 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9271 fcnClosestPoint, QStringLiteral( "GeometryGroup" ) )
9272 << new QgsStaticExpressionFunction( QStringLiteral( "shortest_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
9273 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
9274 fcnShortestLine, QStringLiteral( "GeometryGroup" ) )
9275 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9276 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolatePoint, QStringLiteral( "GeometryGroup" ) )
9277 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_point_by_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9278 << QgsExpressionFunction::Parameter( QStringLiteral( "m" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "use_3d_distance" ), true, false ),
9279 fcnLineInterpolatePointByM, QStringLiteral( "GeometryGroup" ) )
9280 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_angle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9281 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolateAngle, QStringLiteral( "GeometryGroup" ) )
9282 << new QgsStaticExpressionFunction( QStringLiteral( "line_locate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9283 << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnLineLocatePoint, QStringLiteral( "GeometryGroup" ) )
9284 << new QgsStaticExpressionFunction( QStringLiteral( "line_locate_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9285 << QgsExpressionFunction::Parameter( QStringLiteral( "m" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "use_3d_distance" ), true, false ),
9286 fcnLineLocateM, QStringLiteral( "GeometryGroup" ) )
9287 << new QgsStaticExpressionFunction( QStringLiteral( "angle_at_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9288 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnAngleAtVertex, QStringLiteral( "GeometryGroup" ) )
9289 << new QgsStaticExpressionFunction( QStringLiteral( "distance_to_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9290 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnDistanceToVertex, QStringLiteral( "GeometryGroup" ) )
9291 << new QgsStaticExpressionFunction( QStringLiteral( "line_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
9292 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ), fcnLineSubset, QStringLiteral( "GeometryGroup" ) );
9293
9294
9295 // **Record** functions
9296
9297 QgsStaticExpressionFunction *idFunc = new QgsStaticExpressionFunction( QStringLiteral( "$id" ), 0, fcnFeatureId, QStringLiteral( "Record and Attributes" ) );
9298 idFunc->setIsStatic( false );
9299 functions << idFunc;
9300
9301 QgsStaticExpressionFunction *currentFeatureFunc = new QgsStaticExpressionFunction( QStringLiteral( "$currentfeature" ), 0, fcnFeature, QStringLiteral( "Record and Attributes" ) );
9302 currentFeatureFunc->setIsStatic( false );
9303 functions << currentFeatureFunc;
9304
9305 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" ) );
9306 uuidFunc->setIsStatic( false );
9307 functions << uuidFunc;
9308
9309 functions
9310 << new QgsStaticExpressionFunction( QStringLiteral( "feature_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetFeatureId, QStringLiteral( "Record and Attributes" ), QString(), true )
9311 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9312 << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) )
9313 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ), true ),
9314 fcnGetFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "QgsExpressionUtils::getFeature" ) )
9315 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature_by_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9316 << QgsExpressionFunction::Parameter( QStringLiteral( "feature_id" ) ),
9317 fcnGetFeatureById, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false );
9318
9319 QgsStaticExpressionFunction *attributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true ),
9320 fcnAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9321 attributesFunc->setIsStatic( false );
9322 functions << attributesFunc;
9323 QgsStaticExpressionFunction *representAttributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_attributes" ), -1,
9324 fcnRepresentAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9325 representAttributesFunc->setIsStatic( false );
9326 functions << representAttributesFunc;
9327
9328 QgsStaticExpressionFunction *validateFeature = new QgsStaticExpressionFunction( QStringLiteral( "is_feature_valid" ),
9329 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
9330 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
9331 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
9332 fcnValidateFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9333 validateFeature->setIsStatic( false );
9334 functions << validateFeature;
9335
9336 QgsStaticExpressionFunction *validateAttribute = new QgsStaticExpressionFunction( QStringLiteral( "is_attribute_valid" ),
9337 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ), false )
9338 << QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
9339 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
9340 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
9341 fcnValidateAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9342 validateAttribute->setIsStatic( false );
9343 functions << validateAttribute;
9344
9346 QStringLiteral( "maptip" ),
9347 -1,
9348 fcnFeatureMaptip,
9349 QStringLiteral( "Record and Attributes" ),
9350 QString(),
9351 false,
9352 QSet<QString>()
9353 );
9354 maptipFunc->setIsStatic( false );
9355 functions << maptipFunc;
9356
9358 QStringLiteral( "display_expression" ),
9359 -1,
9360 fcnFeatureDisplayExpression,
9361 QStringLiteral( "Record and Attributes" ),
9362 QString(),
9363 false,
9364 QSet<QString>()
9365 );
9366 displayFunc->setIsStatic( false );
9367 functions << displayFunc;
9368
9370 QStringLiteral( "is_selected" ),
9371 -1,
9372 fcnIsSelected,
9373 QStringLiteral( "Record and Attributes" ),
9374 QString(),
9375 false,
9376 QSet<QString>()
9377 );
9378 isSelectedFunc->setIsStatic( false );
9379 functions << isSelectedFunc;
9380
9381 functions
9383 QStringLiteral( "num_selected" ),
9384 -1,
9385 fcnNumSelected,
9386 QStringLiteral( "Record and Attributes" ),
9387 QString(),
9388 false,
9389 QSet<QString>()
9390 );
9391
9392 functions
9394 QStringLiteral( "sqlite_fetch_and_increment" ),
9396 << QgsExpressionFunction::Parameter( QStringLiteral( "database" ) )
9397 << QgsExpressionFunction::Parameter( QStringLiteral( "table" ) )
9398 << QgsExpressionFunction::Parameter( QStringLiteral( "id_field" ) )
9399 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_attribute" ) )
9400 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_value" ) )
9401 << QgsExpressionFunction::Parameter( QStringLiteral( "default_values" ), true ),
9402 fcnSqliteFetchAndIncrement,
9403 QStringLiteral( "Record and Attributes" )
9404 );
9405
9406 // **CRS** functions
9407 functions
9408 << new QgsStaticExpressionFunction( QStringLiteral( "crs_to_authid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "crs" ) ), fcnCrsToAuthid, QStringLiteral( "CRS" ), QString(), true )
9409 << new QgsStaticExpressionFunction( QStringLiteral( "crs_from_text" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "definition" ) ), fcnCrsFromText, QStringLiteral( "CRS" ) );
9410
9411
9412 // **Fields and Values** functions
9413 QgsStaticExpressionFunction *representValueFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "field_name" ), true ), fcnRepresentValue, QStringLiteral( "Record and Attributes" ) );
9414
9415 representValueFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9416 {
9417 Q_UNUSED( context )
9418 if ( node->args()->count() == 1 )
9419 {
9420 QgsExpressionNodeColumnRef *colRef = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
9421 if ( colRef )
9422 {
9423 return true;
9424 }
9425 else
9426 {
9427 parent->setEvalErrorString( tr( "If represent_value is called with 1 parameter, it must be an attribute." ) );
9428 return false;
9429 }
9430 }
9431 else if ( node->args()->count() == 2 )
9432 {
9433 return true;
9434 }
9435 else
9436 {
9437 parent->setEvalErrorString( tr( "represent_value must be called with exactly 1 or 2 parameters." ) );
9438 return false;
9439 }
9440 }
9441 );
9442
9443 functions << representValueFunc;
9444
9445 // **General** functions
9446 functions
9447 << new QgsStaticExpressionFunction( QStringLiteral( "layer_property" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9448 << QgsExpressionFunction::Parameter( QStringLiteral( "property" ) ),
9449 fcnGetLayerProperty, QStringLiteral( "Map Layers" ) )
9450 << new QgsStaticExpressionFunction( QStringLiteral( "decode_uri" ),
9452 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9453 << QgsExpressionFunction::Parameter( QStringLiteral( "part" ), true ),
9454 fcnDecodeUri, QStringLiteral( "Map Layers" ) )
9455 << new QgsStaticExpressionFunction( QStringLiteral( "mime_type" ),
9457 << QgsExpressionFunction::Parameter( QStringLiteral( "binary_data" ) ),
9458 fcnMimeType, QStringLiteral( "General" ) )
9459 << new QgsStaticExpressionFunction( QStringLiteral( "raster_statistic" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9460 << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) )
9461 << QgsExpressionFunction::Parameter( QStringLiteral( "statistic" ) ), fcnGetRasterBandStat, QStringLiteral( "Rasters" ) );
9462
9463 // **var** function
9464 QgsStaticExpressionFunction *varFunction = new QgsStaticExpressionFunction( QStringLiteral( "var" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnGetVariable, QStringLiteral( "General" ) );
9465 varFunction->setIsStaticFunction(
9466 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9467 {
9468 /* A variable node is static if it has a static name and the name can be found at prepare
9469 * time and is tagged with isStatic.
9470 * It is not static if a variable is set during iteration or not tagged isStatic.
9471 * (e.g. geom_part variable)
9472 */
9473 if ( node->args()->count() > 0 )
9474 {
9475 QgsExpressionNode *argNode = node->args()->at( 0 );
9476
9477 if ( !argNode->isStatic( parent, context ) )
9478 return false;
9479
9480 const QString varName = argNode->eval( parent, context ).toString();
9481 if ( varName == QLatin1String( "feature" ) || varName == QLatin1String( "id" ) || varName == QLatin1String( "geometry" ) )
9482 return false;
9483
9484 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
9485 return scope ? scope->isStatic( varName ) : false;
9486 }
9487 return false;
9488 }
9489 );
9490 varFunction->setUsesGeometryFunction(
9491 []( const QgsExpressionNodeFunction * node ) -> bool
9492 {
9493 if ( node && node->args()->count() > 0 )
9494 {
9495 QgsExpressionNode *argNode = node->args()->at( 0 );
9496 if ( QgsExpressionNodeLiteral *literal = dynamic_cast<QgsExpressionNodeLiteral *>( argNode ) )
9497 {
9498 if ( literal->value() == QLatin1String( "geometry" ) || literal->value() == QLatin1String( "feature" ) )
9499 return true;
9500 }
9501 }
9502 return false;
9503 }
9504 );
9505
9506 functions
9507 << varFunction;
9508
9509 QgsStaticExpressionFunction *evalTemplateFunction = new QgsStaticExpressionFunction( QStringLiteral( "eval_template" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "template" ) ), fcnEvalTemplate, QStringLiteral( "General" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9510 evalTemplateFunction->setIsStaticFunction(
9511 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9512 {
9513 if ( node->args()->count() > 0 )
9514 {
9515 QgsExpressionNode *argNode = node->args()->at( 0 );
9516
9517 if ( argNode->isStatic( parent, context ) )
9518 {
9519 QString expString = argNode->eval( parent, context ).toString();
9520
9521 QgsExpression e( expString );
9522
9523 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
9524 return true;
9525 }
9526 }
9527
9528 return false;
9529 } );
9530 functions << evalTemplateFunction;
9531
9532 QgsStaticExpressionFunction *evalFunc = new QgsStaticExpressionFunction( QStringLiteral( "eval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ), fcnEval, QStringLiteral( "General" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9533 evalFunc->setIsStaticFunction(
9534 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9535 {
9536 if ( node->args()->count() > 0 )
9537 {
9538 QgsExpressionNode *argNode = node->args()->at( 0 );
9539
9540 if ( argNode->isStatic( parent, context ) )
9541 {
9542 QString expString = argNode->eval( parent, context ).toString();
9543
9544 QgsExpression e( expString );
9545
9546 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
9547 return true;
9548 }
9549 }
9550
9551 return false;
9552 } );
9553
9554 functions << evalFunc;
9555
9556 QgsStaticExpressionFunction *attributeFunc = new QgsStaticExpressionFunction( QStringLiteral( "attribute" ), -1, fcnAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9557 attributeFunc->setIsStaticFunction(
9558 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9559 {
9560 const QList< QgsExpressionNode *> argList = node->args()->list();
9561 for ( QgsExpressionNode *argNode : argList )
9562 {
9563 if ( !argNode->isStatic( parent, context ) )
9564 return false;
9565 }
9566
9567 if ( node->args()->count() == 1 )
9568 {
9569 // not static -- this is the variant which uses the current feature taken direct from the expression context
9570 return false;
9571 }
9572
9573 return true;
9574 } );
9575 functions << attributeFunc;
9576
9577 functions
9578 << new QgsStaticExpressionFunction( QStringLiteral( "env" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnEnvVar, QStringLiteral( "General" ), QString() )
9580 << new QgsStaticExpressionFunction( QStringLiteral( "raster_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterValue, QStringLiteral( "Rasters" ) )
9581 << new QgsStaticExpressionFunction( QStringLiteral( "raster_attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterAttributes, QStringLiteral( "Rasters" ) )
9582
9583 // functions for arrays
9586 << new QgsStaticExpressionFunction( QStringLiteral( "array" ), -1, fcnArray, QStringLiteral( "Arrays" ), QString(), false, QSet<QString>(), false, QStringList(), true )
9587 << new QgsStaticExpressionFunction( QStringLiteral( "array_sort" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ), fcnArraySort, QStringLiteral( "Arrays" ) )
9588 << new QgsStaticExpressionFunction( QStringLiteral( "array_length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLength, QStringLiteral( "Arrays" ) )
9589 << new QgsStaticExpressionFunction( QStringLiteral( "array_contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayContains, QStringLiteral( "Arrays" ) )
9590 << new QgsStaticExpressionFunction( QStringLiteral( "array_count" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayCount, QStringLiteral( "Arrays" ) )
9591 << new QgsStaticExpressionFunction( QStringLiteral( "array_all" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_b" ) ), fcnArrayAll, QStringLiteral( "Arrays" ) )
9592 << new QgsStaticExpressionFunction( QStringLiteral( "array_find" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayFind, QStringLiteral( "Arrays" ) )
9593 << new QgsStaticExpressionFunction( QStringLiteral( "array_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayGet, QStringLiteral( "Arrays" ) )
9594 << new QgsStaticExpressionFunction( QStringLiteral( "array_first" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayFirst, QStringLiteral( "Arrays" ) )
9595 << new QgsStaticExpressionFunction( QStringLiteral( "array_last" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLast, QStringLiteral( "Arrays" ) )
9596 << new QgsStaticExpressionFunction( QStringLiteral( "array_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMinimum, QStringLiteral( "Arrays" ) )
9597 << new QgsStaticExpressionFunction( QStringLiteral( "array_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMaximum, QStringLiteral( "Arrays" ) )
9598 << new QgsStaticExpressionFunction( QStringLiteral( "array_mean" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMean, QStringLiteral( "Arrays" ) )
9599 << new QgsStaticExpressionFunction( QStringLiteral( "array_median" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMedian, QStringLiteral( "Arrays" ) )
9600 << new QgsStaticExpressionFunction( QStringLiteral( "array_majority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMajority, QStringLiteral( "Arrays" ) )
9601 << new QgsStaticExpressionFunction( QStringLiteral( "array_minority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMinority, QStringLiteral( "Arrays" ) )
9602 << new QgsStaticExpressionFunction( QStringLiteral( "array_sum" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArraySum, QStringLiteral( "Arrays" ) )
9603 << new QgsStaticExpressionFunction( QStringLiteral( "array_append" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayAppend, QStringLiteral( "Arrays" ) )
9604 << new QgsStaticExpressionFunction( QStringLiteral( "array_prepend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayPrepend, QStringLiteral( "Arrays" ) )
9605 << new QgsStaticExpressionFunction( QStringLiteral( "array_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayInsert, QStringLiteral( "Arrays" ) )
9606 << new QgsStaticExpressionFunction( QStringLiteral( "array_remove_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayRemoveAt, QStringLiteral( "Arrays" ) )
9607 << 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 )
9608 << new QgsStaticExpressionFunction( QStringLiteral( "array_replace" ), -1, fcnArrayReplace, QStringLiteral( "Arrays" ) )
9609 << new QgsStaticExpressionFunction( QStringLiteral( "array_prioritize" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_prioritize" ) ), fcnArrayPrioritize, QStringLiteral( "Arrays" ) )
9610 << new QgsStaticExpressionFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) )
9611 << new QgsStaticExpressionFunction( QStringLiteral( "array_slice" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start_pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_pos" ) ), fcnArraySlice, QStringLiteral( "Arrays" ) )
9612 << new QgsStaticExpressionFunction( QStringLiteral( "array_reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayReverse, QStringLiteral( "Arrays" ) )
9613 << new QgsStaticExpressionFunction( QStringLiteral( "array_intersect" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) )
9614 << new QgsStaticExpressionFunction( QStringLiteral( "array_distinct" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayDistinct, QStringLiteral( "Arrays" ) )
9615 << 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" ) )
9616 << 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" ) )
9617 << 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" ) )
9618 << new QgsStaticExpressionFunction( QStringLiteral( "geometries_to_array" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometries" ) ), fcnGeometryCollectionAsArray, QStringLiteral( "Arrays" ) )
9619
9620 //functions for maps
9621 << new QgsStaticExpressionFunction( QStringLiteral( "from_json" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLoadJson, QStringLiteral( "Maps" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "json_to_map" ) )
9622 << 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" ) )
9623 << new QgsStaticExpressionFunction( QStringLiteral( "hstore_to_map" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnHstoreToMap, QStringLiteral( "Maps" ) )
9624 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_hstore" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapToHstore, QStringLiteral( "Maps" ) )
9625 << new QgsStaticExpressionFunction( QStringLiteral( "map" ), -1, fcnMap, QStringLiteral( "Maps" ) )
9626 << new QgsStaticExpressionFunction( QStringLiteral( "map_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapGet, QStringLiteral( "Maps" ) )
9627 << new QgsStaticExpressionFunction( QStringLiteral( "map_exist" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapExist, QStringLiteral( "Maps" ) )
9628 << new QgsStaticExpressionFunction( QStringLiteral( "map_delete" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapDelete, QStringLiteral( "Maps" ) )
9629 << new QgsStaticExpressionFunction( QStringLiteral( "map_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnMapInsert, QStringLiteral( "Maps" ) )
9630 << new QgsStaticExpressionFunction( QStringLiteral( "map_concat" ), -1, fcnMapConcat, QStringLiteral( "Maps" ) )
9631 << new QgsStaticExpressionFunction( QStringLiteral( "map_akeys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAKeys, QStringLiteral( "Maps" ) )
9632 << new QgsStaticExpressionFunction( QStringLiteral( "map_avals" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAVals, QStringLiteral( "Maps" ) )
9633 << new QgsStaticExpressionFunction( QStringLiteral( "map_prefix_keys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
9634 << QgsExpressionFunction::Parameter( QStringLiteral( "prefix" ) ),
9635 fcnMapPrefixKeys, QStringLiteral( "Maps" ) )
9636 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_table" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9637 fcnMapToHtmlTable, QStringLiteral( "Maps" ) )
9638 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_dl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9639 fcnMapToHtmlDefinitionList, QStringLiteral( "Maps" ) )
9640 << new QgsStaticExpressionFunction( QStringLiteral( "url_encode" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9641 fcnToFormUrlEncode, QStringLiteral( "Maps" ) )
9642
9643 ;
9644
9646
9647 //QgsExpression has ownership of all built-in functions
9648 for ( QgsExpressionFunction *func : std::as_const( functions ) )
9649 {
9650 *sOwnedFunctions() << func;
9651 *sBuiltinFunctions() << func->name();
9652 sBuiltinFunctions()->append( func->aliases() );
9653 }
9654 }
9655 return functions;
9656}
9657
9658bool QgsExpression::registerFunction( QgsExpressionFunction *function, bool transferOwnership )
9659{
9660 int fnIdx = functionIndex( function->name() );
9661 if ( fnIdx != -1 )
9662 {
9663 return false;
9664 }
9665
9666 QMutexLocker locker( &sFunctionsMutex );
9667 sFunctions()->append( function );
9668 if ( transferOwnership )
9669 sOwnedFunctions()->append( function );
9670
9671 return true;
9672}
9673
9674bool QgsExpression::unregisterFunction( const QString &name )
9675{
9676 // You can never override the built in functions.
9677 if ( QgsExpression::BuiltinFunctions().contains( name ) )
9678 {
9679 return false;
9680 }
9681 int fnIdx = functionIndex( name );
9682 if ( fnIdx != -1 )
9683 {
9684 QMutexLocker locker( &sFunctionsMutex );
9685 sFunctions()->removeAt( fnIdx );
9686 sFunctionIndexMap.clear();
9687 return true;
9688 }
9689 return false;
9690}
9691
9693{
9694 qDeleteAll( *sOwnedFunctions() );
9695 sOwnedFunctions()->clear();
9697
9698const QStringList &QgsExpression::BuiltinFunctions()
9699{
9700 if ( sBuiltinFunctions()->isEmpty() )
9701 {
9702 Functions(); // this method builds the gmBuiltinFunctions as well
9703 }
9704 return *sBuiltinFunctions();
9706
9708 : QgsExpressionFunction( QStringLiteral( "array_foreach" ), QgsExpressionFunction::ParameterList() // skip-keyword-check
9709 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9710 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9711 QStringLiteral( "Arrays" ) )
9712{
9713
9714}
9715
9717{
9718 bool isStatic = false;
9719
9720 QgsExpressionNode::NodeList *args = node->args();
9722 if ( args->count() < 2 )
9723 return false;
9724
9725 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9726 {
9727 isStatic = true;
9728 }
9729 return isStatic;
9730}
9731
9733{
9734 Q_UNUSED( node )
9735 QVariantList result;
9736
9737 if ( args->count() < 2 )
9738 // error
9739 return result;
9740
9741 QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9742
9743 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9744 std::unique_ptr< QgsExpressionContext > tempContext;
9745 if ( !subContext )
9746 {
9747 tempContext = std::make_unique< QgsExpressionContext >();
9748 subContext = tempContext.get();
9749 }
9750
9752 subContext->appendScope( subScope );
9753
9754 int i = 0;
9755 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it, ++i )
9756 {
9757 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), *it, true ) );
9758 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "counter" ), i, true ) );
9759 result << args->at( 1 )->eval( parent, subContext );
9760 }
9761
9762 if ( context )
9763 delete subContext->popScope();
9764
9765 return result;
9766}
9767
9768QVariant QgsArrayForeachExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9770 // This is a dummy function, all the real handling is in run
9771 Q_UNUSED( values )
9772 Q_UNUSED( context )
9773 Q_UNUSED( parent )
9774 Q_UNUSED( node )
9775
9776 Q_ASSERT( false );
9777 return QVariant();
9778}
9779
9781{
9782 QgsExpressionNode::NodeList *args = node->args();
9783
9784 if ( args->count() < 2 )
9785 // error
9786 return false;
9787
9788 args->at( 0 )->prepare( parent, context );
9789
9790 QgsExpressionContext subContext;
9791 if ( context )
9792 subContext = *context;
9795 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9796 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "counter" ), QVariant(), true ) );
9797 subContext.appendScope( subScope );
9798
9799 args->at( 1 )->prepare( parent, &subContext );
9800
9801 return true;
9802}
9805 : QgsExpressionFunction( QStringLiteral( "array_filter" ), QgsExpressionFunction::ParameterList()
9806 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9807 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
9808 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, 0 ),
9809 QStringLiteral( "Arrays" ) )
9810{
9811
9812}
9813
9815{
9816 bool isStatic = false;
9817
9818 QgsExpressionNode::NodeList *args = node->args();
9820 if ( args->count() < 2 )
9821 return false;
9822
9823 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9824 {
9825 isStatic = true;
9826 }
9827 return isStatic;
9828}
9829
9831{
9832 Q_UNUSED( node )
9833 QVariantList result;
9834
9835 if ( args->count() < 2 )
9836 // error
9837 return result;
9838
9839 const QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9840
9841 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9842 std::unique_ptr< QgsExpressionContext > tempContext;
9843 if ( !subContext )
9844 {
9845 tempContext = std::make_unique< QgsExpressionContext >();
9846 subContext = tempContext.get();
9847 }
9848
9850 subContext->appendScope( subScope );
9851
9852 int limit = 0;
9853 if ( args->count() >= 3 )
9854 {
9855 const QVariant limitVar = args->at( 2 )->eval( parent, context );
9856
9857 if ( QgsExpressionUtils::isIntSafe( limitVar ) )
9858 {
9859 limit = limitVar.toInt();
9860 }
9861 else
9862 {
9863 return result;
9864 }
9865 }
9866
9867 for ( const QVariant &value : array )
9868 {
9869 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), value, true ) );
9870 if ( args->at( 1 )->eval( parent, subContext ).toBool() )
9871 {
9872 result << value;
9873
9874 if ( limit > 0 && limit == result.size() )
9875 break;
9876 }
9877 }
9878
9879 if ( context )
9880 delete subContext->popScope();
9881
9882 return result;
9883}
9884
9885QVariant QgsArrayFilterExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9887 // This is a dummy function, all the real handling is in run
9888 Q_UNUSED( values )
9889 Q_UNUSED( context )
9890 Q_UNUSED( parent )
9891 Q_UNUSED( node )
9892
9893 Q_ASSERT( false );
9894 return QVariant();
9895}
9896
9898{
9899 QgsExpressionNode::NodeList *args = node->args();
9900
9901 if ( args->count() < 2 )
9902 // error
9903 return false;
9904
9905 args->at( 0 )->prepare( parent, context );
9906
9907 QgsExpressionContext subContext;
9908 if ( context )
9909 subContext = *context;
9910
9912 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9913 subContext.appendScope( subScope );
9914
9915 args->at( 1 )->prepare( parent, &subContext );
9916
9917 return true;
9920 : QgsExpressionFunction( QStringLiteral( "with_variable" ), QgsExpressionFunction::ParameterList() <<
9921 QgsExpressionFunction::Parameter( QStringLiteral( "name" ) )
9922 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
9923 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9924 QStringLiteral( "General" ) )
9925{
9926
9927}
9928
9930{
9931 bool isStatic = false;
9932
9933 QgsExpressionNode::NodeList *args = node->args();
9934
9935 if ( args->count() < 3 )
9936 return false;
9937
9938 // We only need to check if the node evaluation is static, if both - name and value - are static.
9939 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9940 {
9941 QVariant name = args->at( 0 )->eval( parent, context );
9942 QVariant value = args->at( 1 )->eval( parent, context );
9944 // Temporarily append a new scope to provide the variable
9945 appendTemporaryVariable( context, name.toString(), value );
9946 if ( args->at( 2 )->isStatic( parent, context ) )
9947 isStatic = true;
9948 popTemporaryVariable( context );
9949 }
9950
9951 return isStatic;
9952}
9953
9955{
9956 Q_UNUSED( node )
9957 QVariant result;
9958
9959 if ( args->count() < 3 )
9960 // error
9961 return result;
9962
9963 QVariant name = args->at( 0 )->eval( parent, context );
9964 QVariant value = args->at( 1 )->eval( parent, context );
9965
9966 const QgsExpressionContext *updatedContext = context;
9967 std::unique_ptr< QgsExpressionContext > tempContext;
9968 if ( !updatedContext )
9969 {
9970 tempContext = std::make_unique< QgsExpressionContext >();
9971 updatedContext = tempContext.get();
9973
9974 appendTemporaryVariable( updatedContext, name.toString(), value );
9975 result = args->at( 2 )->eval( parent, updatedContext );
9976
9977 if ( context )
9978 popTemporaryVariable( updatedContext );
9979
9980 return result;
9981}
9982
9983QVariant QgsWithVariableExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9985 // This is a dummy function, all the real handling is in run
9986 Q_UNUSED( values )
9987 Q_UNUSED( context )
9988 Q_UNUSED( parent )
9989 Q_UNUSED( node )
9990
9991 Q_ASSERT( false );
9992 return QVariant();
9993}
9994
9996{
9997 QgsExpressionNode::NodeList *args = node->args();
9998
9999 if ( args->count() < 3 )
10000 // error
10001 return false;
10002
10003 QVariant name = args->at( 0 )->prepare( parent, context );
10004 QVariant value = args->at( 1 )->prepare( parent, context );
10005
10006 const QgsExpressionContext *updatedContext = context;
10007 std::unique_ptr< QgsExpressionContext > tempContext;
10008 if ( !updatedContext )
10009 {
10010 tempContext = std::make_unique< QgsExpressionContext >();
10011 updatedContext = tempContext.get();
10012 }
10013
10014 appendTemporaryVariable( updatedContext, name.toString(), value );
10015 args->at( 2 )->prepare( parent, updatedContext );
10016
10017 if ( context )
10018 popTemporaryVariable( updatedContext );
10019
10020 return true;
10021}
10022
10023void QgsWithVariableExpressionFunction::popTemporaryVariable( const QgsExpressionContext *context ) const
10024{
10025 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
10026 delete updatedContext->popScope();
10027}
10028
10029void QgsWithVariableExpressionFunction::appendTemporaryVariable( const QgsExpressionContext *context, const QString &name, const QVariant &value ) const
10030{
10033
10034 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
10035 updatedContext->appendScope( scope );
10036}
@ Left
Buffer to left of line.
DashPatternSizeAdjustment
Dash pattern size adjustment options.
Definition qgis.h:3151
@ 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:2051
@ Bevel
Use beveled joins.
@ Round
Use rounded joins.
@ Miter
Use mitered joins.
RasterBandStatistic
Available raster band statistics.
Definition qgis.h:5620
@ 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:2038
@ 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:5497
@ 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:3136
@ 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:2097
@ 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.
@ GeometryCollection
GeometryCollection.
@ 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:45
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).
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.
QString uniqueHash(bool &ok, const QSet< QString > &variables=QSet< QString >()) const
Returns a unique hash representing the current state of the 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:746
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.
static QgsGeometry fromMultiPolylineXY(const QgsMultiPolylineXY &multiline)
Creates a new geometry from a QgsMultiPolylineXY object.
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.
static QgsGeometry fromMultiPointXY(const QgsMultiPointXY &multipoint)
Creates a new geometry from a QgsMultiPointXY object.
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 ...
static QgsGeometry fromMultiPolygonXY(const QgsMultiPolygonXY &multipoly)
Creates a new geometry from a QgsMultiPolygonXY.
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.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
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, and exception handling.
Definition qgsgeos.h:139
std::unique_ptr< QgsAbstractGeometry > maximumInscribedCircle(double tolerance, QString *errorMsg=nullptr) const
Returns the maximum inscribed circle.
Definition qgsgeos.cpp:2806
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.
bool lineLocatePointByM(double m, double &x, double &y, double &z, double &distanceFromStart, bool use3DDistance=true) const
Attempts to locate a point on the linestring by m value.
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:76
QString name
Definition qgsmaplayer.h:80
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:83
QgsMapLayerServerProperties * serverProperties()
Returns QGIS Server Properties for the map layer.
QString id
Definition qgsmaplayer.h:79
QgsLayerMetadata metadata
Definition qgsmaplayer.h:82
Qgis::LayerType type
Definition qgsmaplayer.h:86
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:89
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, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
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:242
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:694
bool addZValue(double zValue=0) override
Adds a z-dimension to the geometry, initialized to a preset value.
Definition qgspoint.cpp:558
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:426
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:105
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:706
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
double yMinimum
double xMaximum
void grow(double delta)
Grows the rectangle in place by the specified amount.
double yMaximum
QgsPointXY center
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.
Represents a relationship between two vector layers.
Definition qgsrelation.h:44
QgsVectorLayer * referencedLayer
Definition qgsrelation.h:49
QgsVectorLayer * referencingLayer
Definition qgsrelation.h:48
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:501
static QgsStyle * defaultStyle(bool initialize=true)
Returns the default application-wide style.
Definition qgsstyle.cpp:146
Contains utility functions for working with symbols and symbol layers.
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.
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
Returns the editor widget setup for the field at the specified index.
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 bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
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
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:121
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6702
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6701
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
Definition qgis.h:6166
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:6125
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
QVariant fcnRampColor(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node)
#define ENSURE_GEOM_TYPE(f, g, geomtype)
QVariant fcnRampColorObject(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< QgsPolylineXY > QgsMultiPolylineXY
A collection of QgsPolylines that share a common collection of attributes.
Definition qgsgeometry.h:84
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:80
QVector< QgsPolygonXY > QgsMultiPolygonXY
A collection of QgsPolygons that share a common collection of attributes.
Definition qgsgeometry.h:91
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
QLineF segment(int index, QRectF rect, double radius)
const QgsCoordinateReferenceSystem & crs
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