QGIS API Documentation 3.32.0-Lima (311a8cb8a6)
qgsexpressionfunction.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsexpressionfunction.cpp
3 -------------------
4 begin : May 2017
5 copyright : (C) 2017 Matthias Kuhn
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16
17#include <random>
18
20#include "qgscoordinateutils.h"
22#include "qgsexpressionutils.h"
24#include "qgsexiftools.h"
25#include "qgsfeaturerequest.h"
26#include "qgsgeos.h"
27#include "qgsstringutils.h"
28#include "qgsmultipoint.h"
29#include "qgsgeometryutils.h"
30#include "qgshstoreutils.h"
31#include "qgsmultilinestring.h"
32#include "qgslinestring.h"
33#include "qgscurvepolygon.h"
35#include "qgspolygon.h"
36#include "qgstriangle.h"
37#include "qgscurve.h"
38#include "qgsregularpolygon.h"
39#include "qgsquadrilateral.h"
40#include "qgsvariantutils.h"
41#include "qgsogcutils.h"
42#include "qgsdistancearea.h"
43#include "qgsgeometryengine.h"
45#include "qgssymbollayerutils.h"
46#include "qgsstyle.h"
47#include "qgsexception.h"
48#include "qgsmessagelog.h"
49#include "qgsrasterlayer.h"
50#include "qgsvectorlayer.h"
51#include "qgsvectorlayerutils.h"
52#include "qgsrasterbandstats.h"
53#include "qgscolorramp.h"
55#include "qgsfieldformatter.h"
57#include "qgsproviderregistry.h"
58#include "sqlite3.h"
59#include "qgstransaction.h"
60#include "qgsthreadingutils.h"
61#include "qgsapplication.h"
62#include "qgis.h"
64#include "qgsunittypes.h"
65#include "qgsspatialindex.h"
66#include "qgscolorrampimpl.h"
67
68#include <QMimeDatabase>
69#include <QProcessEnvironment>
70#include <QCryptographicHash>
71#include <QRegularExpression>
72#include <QUuid>
73#include <QUrlQuery>
74
75typedef QList<QgsExpressionFunction *> ExpressionFunctionList;
76
78Q_GLOBAL_STATIC( QStringList, sBuiltinFunctions )
80
83Q_DECLARE_METATYPE( std::shared_ptr<QgsVectorLayer> )
84
85const QString QgsExpressionFunction::helpText() const
86{
87 return mHelpText.isEmpty() ? QgsExpression::helpText( mName ) : mHelpText;
88}
89
91{
92 Q_UNUSED( node )
93 // evaluate arguments
94 QVariantList argValues;
95 if ( args )
96 {
97 int arg = 0;
98 const QList< QgsExpressionNode * > argList = args->list();
99 for ( QgsExpressionNode *n : argList )
100 {
101 QVariant v;
102 if ( lazyEval() )
103 {
104 // Pass in the node for the function to eval as it needs.
105 v = QVariant::fromValue( n );
106 }
107 else
108 {
109 v = n->eval( parent, context );
111 bool defaultParamIsNull = mParameterList.count() > arg && mParameterList.at( arg ).optional() && !mParameterList.at( arg ).defaultValue().isValid();
112 if ( QgsExpressionUtils::isNull( v ) && !defaultParamIsNull && !handlesNull() )
113 return QVariant(); // all "normal" functions return NULL, when any QgsExpressionFunction::Parameter is NULL (so coalesce is abnormal)
114 }
115 argValues.append( v );
116 arg++;
117 }
118 }
119
120 return func( argValues, context, parent, node );
121}
122
124{
125 Q_UNUSED( node )
126 return true;
127}
128
130{
131 return QStringList();
132}
133
135{
136 Q_UNUSED( parent )
137 Q_UNUSED( context )
138 Q_UNUSED( node )
139 return false;
140}
141
143{
144 Q_UNUSED( parent )
145 Q_UNUSED( context )
146 Q_UNUSED( node )
147 return true;
148}
149
151{
152 Q_UNUSED( node )
153 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
154}
155
157{
158 return mGroups.isEmpty() ? false : mGroups.contains( QStringLiteral( "deprecated" ) );
159}
160
162{
163 return ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 );
164}
165
167{
168 return mHandlesNull;
169}
170
171// doxygen doesn't like this constructor for some reason (maybe the function arguments?)
174 FcnEval fcn,
175 const QString &group,
176 const QString &helpText,
177 const std::function < bool ( const QgsExpressionNodeFunction *node ) > &usesGeometry,
178 const std::function < QSet<QString>( const QgsExpressionNodeFunction *node ) > &referencedColumns,
179 bool lazyEval,
180 const QStringList &aliases,
181 bool handlesNull )
182 : QgsExpressionFunction( fnname, params, group, helpText, lazyEval, handlesNull, false )
183 , mFnc( fcn )
184 , mAliases( aliases )
185 , mUsesGeometry( false )
186 , mUsesGeometryFunc( usesGeometry )
187 , mReferencedColumnsFunc( referencedColumns )
188{
189}
191
193{
194 return mAliases;
195}
196
198{
199 if ( mUsesGeometryFunc )
200 return mUsesGeometryFunc( node );
201 else
202 return mUsesGeometry;
203}
204
205void QgsStaticExpressionFunction::setUsesGeometryFunction( const std::function<bool ( const QgsExpressionNodeFunction * )> &usesGeometry )
206{
207 mUsesGeometryFunc = usesGeometry;
208}
209
211{
212 if ( mReferencedColumnsFunc )
213 return mReferencedColumnsFunc( node );
214 else
215 return mReferencedColumns;
216}
217
219{
220 if ( mIsStaticFunc )
221 return mIsStaticFunc( node, parent, context );
222 else
223 return mIsStatic;
224}
225
227{
228 if ( mPrepareFunc )
229 return mPrepareFunc( node, parent, context );
230
231 return true;
232}
233
235{
236 mIsStaticFunc = isStatic;
237}
238
240{
241 mIsStaticFunc = nullptr;
242 mIsStatic = isStatic;
243}
244
245void QgsStaticExpressionFunction::setPrepareFunction( const std::function<bool ( const QgsExpressionNodeFunction *, QgsExpression *, const QgsExpressionContext * )> &prepareFunc )
246{
247 mPrepareFunc = prepareFunc;
248}
249
251{
252 if ( node && node->args() )
253 {
254 const QList< QgsExpressionNode * > argList = node->args()->list();
255 for ( QgsExpressionNode *argNode : argList )
256 {
257 if ( !argNode->isStatic( parent, context ) )
258 return false;
259 }
260 }
261
262 return true;
263}
264
265static QVariant fcnGenerateSeries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
266{
267 double start = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
268 double stop = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
269 double step = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
270
271 if ( step == 0.0 || ( step > 0.0 && start > stop ) || ( step < 0.0 && start < stop ) )
272 return QVariant();
273
274 QVariantList array;
275 int length = 1;
276
277 array << start;
278 double current = start + step;
279 while ( ( ( step > 0.0 && current <= stop ) || ( step < 0.0 && current >= stop ) ) && length <= 1000000 )
280 {
281 array << current;
282 current += step;
283 length++;
284 }
285
286 return array;
287}
288
289static QVariant fcnGetVariable( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
290{
291 if ( !context )
292 return QVariant();
293
294 const QString name = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
295
296 if ( name == QLatin1String( "feature" ) )
297 {
298 return context->hasFeature() ? QVariant::fromValue( context->feature() ) : QVariant();
299 }
300 else if ( name == QLatin1String( "id" ) )
301 {
302 return context->hasFeature() ? QVariant::fromValue( context->feature().id() ) : QVariant();
303 }
304 else if ( name == QLatin1String( "geometry" ) )
305 {
306 if ( !context->hasFeature() )
307 return QVariant();
308
309 const QgsFeature feature = context->feature();
310 return feature.hasGeometry() ? QVariant::fromValue( feature.geometry() ) : QVariant();
311 }
312 else
313 {
314 return context->variable( name );
315 }
316}
317
318static QVariant fcnEvalTemplate( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
319{
320 QString templateString = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
321 return QgsExpression::replaceExpressionText( templateString, context );
322}
323
324static QVariant fcnEval( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
325{
326 if ( !context )
327 return QVariant();
328
329 QString expString = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
330 QgsExpression expression( expString );
331 return expression.evaluate( context );
332}
333
334static QVariant fcnSqrt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
335{
336 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
337 return QVariant( std::sqrt( x ) );
338}
339
340static QVariant fcnAbs( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
341{
342 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
343 return QVariant( std::fabs( val ) );
344}
345
346static QVariant fcnRadians( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
347{
348 double deg = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
349 return ( deg * M_PI ) / 180;
350}
351static QVariant fcnDegrees( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
352{
353 double rad = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
354 return ( 180 * rad ) / M_PI;
355}
356static QVariant fcnSin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
357{
358 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
359 return QVariant( std::sin( x ) );
360}
361static QVariant fcnCos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
362{
363 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
364 return QVariant( std::cos( x ) );
365}
366static QVariant fcnTan( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
367{
368 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
369 return QVariant( std::tan( x ) );
370}
371static QVariant fcnAsin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
372{
373 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
374 return QVariant( std::asin( x ) );
375}
376static QVariant fcnAcos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
377{
378 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
379 return QVariant( std::acos( x ) );
380}
381static QVariant fcnAtan( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
382{
383 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
384 return QVariant( std::atan( x ) );
385}
386static QVariant fcnAtan2( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
387{
388 double y = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
389 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
390 return QVariant( std::atan2( y, x ) );
391}
392static QVariant fcnExp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
393{
394 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
395 return QVariant( std::exp( x ) );
396}
397static QVariant fcnLn( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
398{
399 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
400 if ( x <= 0 )
401 return QVariant();
402 return QVariant( std::log( x ) );
403}
404static QVariant fcnLog10( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
405{
406 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
407 if ( x <= 0 )
408 return QVariant();
409 return QVariant( log10( x ) );
410}
411static QVariant fcnLog( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
412{
413 double b = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
414 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
415 if ( x <= 0 || b <= 0 )
416 return QVariant();
417 return QVariant( std::log( x ) / std::log( b ) );
418}
419static QVariant fcnRndF( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
420{
421 double min = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
422 double max = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
423 if ( max < min )
424 return QVariant();
425
426 std::random_device rd;
427 std::mt19937_64 generator( rd() );
428
429 if ( !QgsExpressionUtils::isNull( values.at( 2 ) ) )
430 {
431 quint32 seed;
432 if ( QgsExpressionUtils::isIntSafe( values.at( 2 ) ) )
433 {
434 // if seed can be converted to int, we use as is
435 seed = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
436 }
437 else
438 {
439 // if not, we hash string representation to int
440 QString seedStr = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
441 std::hash<std::string> hasher;
442 seed = hasher( seedStr.toStdString() );
443 }
444 generator.seed( seed );
445 }
446
447 // Return a random double in the range [min, max] (inclusive)
448 double f = static_cast< double >( generator() ) / static_cast< double >( std::mt19937_64::max() );
449 return QVariant( min + f * ( max - min ) );
450}
451static QVariant fcnRnd( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
452{
453 qlonglong min = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
454 qlonglong max = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
455 if ( max < min )
456 return QVariant();
457
458 std::random_device rd;
459 std::mt19937_64 generator( rd() );
460
461 if ( !QgsExpressionUtils::isNull( values.at( 2 ) ) )
462 {
463 quint32 seed;
464 if ( QgsExpressionUtils::isIntSafe( values.at( 2 ) ) )
465 {
466 // if seed can be converted to int, we use as is
467 seed = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
468 }
469 else
470 {
471 // if not, we hash string representation to int
472 QString seedStr = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
473 std::hash<std::string> hasher;
474 seed = hasher( seedStr.toStdString() );
475 }
476 generator.seed( seed );
477 }
478
479 qint64 randomInteger = min + ( generator() % ( max - min + 1 ) );
480 if ( randomInteger > std::numeric_limits<int>::max() || randomInteger < -std::numeric_limits<int>::max() )
481 return QVariant( randomInteger );
482
483 // Prevent wrong conversion of QVariant. See #36412
484 return QVariant( int( randomInteger ) );
485}
486
487static QVariant fcnLinearScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
488{
489 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
490 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
491 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
492 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
493 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
494
495 if ( domainMin >= domainMax )
496 {
497 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
498 return QVariant();
499 }
500
501 // outside of domain?
502 if ( val >= domainMax )
503 {
504 return rangeMax;
505 }
506 else if ( val <= domainMin )
507 {
508 return rangeMin;
509 }
510
511 // calculate linear scale
512 double m = ( rangeMax - rangeMin ) / ( domainMax - domainMin );
513 double c = rangeMin - ( domainMin * m );
514
515 // Return linearly scaled value
516 return QVariant( m * val + c );
517}
518
519static QVariant fcnPolynomialScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
520{
521 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
522 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
523 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
524 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
525 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
526 double exponent = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
527
528 if ( domainMin >= domainMax )
529 {
530 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
531 return QVariant();
532 }
533 if ( exponent <= 0 )
534 {
535 parent->setEvalErrorString( QObject::tr( "Exponent must be greater than 0" ) );
536 return QVariant();
537 }
538
539 // outside of domain?
540 if ( val >= domainMax )
541 {
542 return rangeMax;
543 }
544 else if ( val <= domainMin )
545 {
546 return rangeMin;
547 }
548
549 // Return polynomially scaled value
550 return QVariant( ( ( rangeMax - rangeMin ) / std::pow( domainMax - domainMin, exponent ) ) * std::pow( val - domainMin, exponent ) + rangeMin );
551}
552
553static QVariant fcnExponentialScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
554{
555 double val = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
556 double domainMin = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
557 double domainMax = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
558 double rangeMin = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
559 double rangeMax = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
560 double exponent = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
561
562 if ( domainMin >= domainMax )
563 {
564 parent->setEvalErrorString( QObject::tr( "Domain max must be greater than domain min" ) );
565 return QVariant();
566 }
567 if ( exponent <= 0 )
568 {
569 parent->setEvalErrorString( QObject::tr( "Exponent must be greater than 0" ) );
570 return QVariant();
571 }
572
573 // outside of domain?
574 if ( val >= domainMax )
575 {
576 return rangeMax;
577 }
578 else if ( val <= domainMin )
579 {
580 return rangeMin;
581 }
582
583 // Return exponentially scaled value
584 double ratio = ( std::pow( exponent, val - domainMin ) - 1 ) / ( std::pow( exponent, domainMax - domainMin ) - 1 );
585 return QVariant( ( rangeMax - rangeMin ) * ratio + rangeMin );
586}
587
588static QVariant fcnMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
589{
590 QVariant result( QVariant::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( QVariant::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 QgsAggregateCalculator::Aggregate aggregate = QgsAggregateCalculator::stringToAggregate( QgsExpressionUtils::getStringValue( value, parent ), &ok );
663 if ( !ok )
664 {
665 parent->setEvalErrorString( QObject::tr( "No such aggregate '%1'" ).arg( value.toString() ) );
666 return QVariant();
667 }
668
669 // third node is subexpression (or field name)
670 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
672 QString subExpression = node->dump();
673
675 //optional forth node is filter
676 if ( values.count() > 3 )
677 {
678 node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
680 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
681 if ( !nl || nl->value().isValid() )
682 parameters.filter = node->dump();
683 }
684
685 //optional fifth node is concatenator
686 if ( values.count() > 4 )
687 {
688 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
690 value = node->eval( parent, context );
692 parameters.delimiter = value.toString();
693 }
694
695 //optional sixth node is order by
696 QString orderBy;
697 if ( values.count() > 5 )
698 {
699 node = QgsExpressionUtils::getNode( values.at( 5 ), parent );
701 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
702 if ( !nl || nl->value().isValid() )
703 {
704 orderBy = node->dump();
705 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
706 }
707 }
708
709 QString aggregateError;
710 QVariant result;
711 if ( context )
712 {
713 QString cacheKey;
714 QgsExpression subExp( subExpression );
715 QgsExpression filterExp( parameters.filter );
716
717 bool isStatic = true;
718 if ( filterExp.referencedVariables().contains( QStringLiteral( "parent" ) )
719 || filterExp.referencedVariables().contains( QString() )
720 || subExp.referencedVariables().contains( QStringLiteral( "parent" ) )
721 || subExp.referencedVariables().contains( QString() ) )
722 {
723 isStatic = false;
724 }
725 else
726 {
727 const QSet<QString> refVars = filterExp.referencedVariables() + subExp.referencedVariables();
728 for ( const QString &varName : refVars )
729 {
730 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
731 if ( scope && !scope->isStatic( varName ) )
732 {
733 isStatic = false;
734 break;
735 }
736 }
737 }
738
739 if ( !isStatic )
740 {
741 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5%6:%7" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter,
742 QString::number( context->feature().id() ), QString::number( qHash( context->feature() ) ), orderBy );
743 }
744 else
745 {
746 cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter, orderBy );
747 }
748
749 if ( context->hasCachedValue( cacheKey ) )
750 {
751 return context->cachedValue( cacheKey );
752 }
753
754 QgsExpressionContext subContext( *context );
756 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
757 subContext.appendScope( subScope );
758 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &aggregateError );
759
760 if ( ok )
761 {
762 // important -- we should only store cached values when the expression is successfully calculated. Otherwise subsequent
763 // use of the expression context will happily grab the invalid QVariant cached value without realising that there was actually an error
764 // associated with it's calculation!
765 context->setCachedValue( cacheKey, result );
766 }
767 }
768 else
769 {
770 result = vl->aggregate( aggregate, subExpression, parameters, nullptr, &ok, nullptr, nullptr, &aggregateError );
771 }
772 if ( !ok )
773 {
774 if ( !aggregateError.isEmpty() )
775 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, aggregateError ) );
776 else
777 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
778 return QVariant();
779 }
780
781 return result;
782}
783
784static QVariant fcnAggregateRelation( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
785{
786 if ( !context )
787 {
788 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
789 return QVariant();
790 }
791
792 // first step - find current layer
793
794 // TODO this expression function is NOT thread safe
796 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
798 if ( !vl )
799 {
800 parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) );
801 return QVariant();
802 }
803
804 //lazy eval, so we need to evaluate nodes now
805
806 //first node is relation name
807 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
809 QVariant value = node->eval( parent, context );
811 QString relationId = value.toString();
812 // check relation exists
813 QgsRelation relation = QgsProject::instance()->relationManager()->relation( relationId );
814 if ( !relation.isValid() || relation.referencedLayer() != vl )
815 {
816 // check for relations by name
817 QList< QgsRelation > relations = QgsProject::instance()->relationManager()->relationsByName( relationId );
818 if ( relations.isEmpty() || relations.at( 0 ).referencedLayer() != vl )
819 {
820 parent->setEvalErrorString( QObject::tr( "Cannot find relation with id '%1'" ).arg( relationId ) );
821 return QVariant();
822 }
823 else
824 {
825 relation = relations.at( 0 );
826 }
827 }
828
829 QgsVectorLayer *childLayer = relation.referencingLayer();
830
831 // second node is aggregate type
832 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
834 value = node->eval( parent, context );
836 bool ok = false;
837 QgsAggregateCalculator::Aggregate aggregate = QgsAggregateCalculator::stringToAggregate( QgsExpressionUtils::getStringValue( value, parent ), &ok );
838 if ( !ok )
839 {
840 parent->setEvalErrorString( QObject::tr( "No such aggregate '%1'" ).arg( value.toString() ) );
841 return QVariant();
842 }
843
844 //third node is subexpression (or field name)
845 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
847 QString subExpression = node->dump();
848
849 //optional fourth node is concatenator
851 if ( values.count() > 3 )
852 {
853 node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
855 value = node->eval( parent, context );
857 parameters.delimiter = value.toString();
858 }
859
860 //optional fifth node is order by
861 QString orderBy;
862 if ( values.count() > 4 )
863 {
864 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
866 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
867 if ( !nl || nl->value().isValid() )
868 {
869 orderBy = node->dump();
870 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
871 }
872 }
873
874 if ( !context->hasFeature() )
875 return QVariant();
876 QgsFeature f = context->feature();
877
878 parameters.filter = relation.getRelatedFeaturesFilter( f );
879
880 QString cacheKey = QStringLiteral( "relagg:%1:%2:%3:%4:%5" ).arg( vl->id(),
881 QString::number( static_cast< int >( aggregate ) ),
882 subExpression,
883 parameters.filter,
884 orderBy );
885 if ( context->hasCachedValue( cacheKey ) )
886 return context->cachedValue( cacheKey );
887
888 QVariant result;
889 ok = false;
890
891
892 QgsExpressionContext subContext( *context );
893 QString error;
894 result = childLayer->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
895
896 if ( !ok )
897 {
898 if ( !error.isEmpty() )
899 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
900 else
901 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
902 return QVariant();
903 }
904
905 // cache value
906 context->setCachedValue( cacheKey, result );
907 return result;
908}
909
910
911static QVariant fcnAggregateGeneric( QgsAggregateCalculator::Aggregate aggregate, const QVariantList &values, QgsAggregateCalculator::AggregateParameters parameters, const QgsExpressionContext *context, QgsExpression *parent, int orderByPos = -1 )
912{
913 if ( !context )
914 {
915 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
916 return QVariant();
917 }
918
919 // first step - find current layer
920
921 // TODO this expression function is NOT thread safe
923 QgsVectorLayer *vl = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
925 if ( !vl )
926 {
927 parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) );
928 return QVariant();
929 }
930
931 //lazy eval, so we need to evaluate nodes now
932
933 //first node is subexpression (or field name)
934 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
936 QString subExpression = node->dump();
937
938 //optional second node is group by
939 QString groupBy;
940 if ( values.count() > 1 )
941 {
942 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
944 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
945 if ( !nl || nl->value().isValid() )
946 groupBy = node->dump();
947 }
948
949 //optional third node is filter
950 if ( values.count() > 2 )
951 {
952 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
954 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
955 if ( !nl || nl->value().isValid() )
956 parameters.filter = node->dump();
957 }
958
959 //optional order by node, if supported
960 QString orderBy;
961 if ( orderByPos >= 0 && values.count() > orderByPos )
962 {
963 node = QgsExpressionUtils::getNode( values.at( orderByPos ), parent );
965 QgsExpressionNodeLiteral *nl = dynamic_cast< QgsExpressionNodeLiteral * >( node );
966 if ( !nl || nl->value().isValid() )
967 {
968 orderBy = node->dump();
969 parameters.orderBy << QgsFeatureRequest::OrderByClause( orderBy );
970 }
971 }
972
973 // build up filter with group by
974
975 // find current group by value
976 if ( !groupBy.isEmpty() )
977 {
978 QgsExpression groupByExp( groupBy );
979 QVariant groupByValue = groupByExp.evaluate( context );
980 QString groupByClause = QStringLiteral( "%1 %2 %3" ).arg( groupBy,
981 QgsVariantUtils::isNull( groupByValue ) ? QStringLiteral( "is" ) : QStringLiteral( "=" ),
982 QgsExpression::quotedValue( groupByValue ) );
983 if ( !parameters.filter.isEmpty() )
984 parameters.filter = QStringLiteral( "(%1) AND (%2)" ).arg( parameters.filter, groupByClause );
985 else
986 parameters.filter = groupByClause;
987 }
988
989 QgsExpression subExp( subExpression );
990 QgsExpression filterExp( parameters.filter );
991
992 bool isStatic = true;
993 const QSet<QString> refVars = filterExp.referencedVariables() + subExp.referencedVariables();
994 for ( const QString &varName : refVars )
995 {
996 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
997 if ( scope && !scope->isStatic( varName ) )
998 {
999 isStatic = false;
1000 break;
1001 }
1002 }
1003
1004 QString cacheKey;
1005 if ( !isStatic )
1006 {
1007 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5%6:%7" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter,
1008 QString::number( context->feature().id() ), QString::number( qHash( context->feature() ) ), orderBy );
1009 }
1010 else
1011 {
1012 cacheKey = QStringLiteral( "agg:%1:%2:%3:%4:%5" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter, orderBy );
1013 }
1014
1015 if ( context->hasCachedValue( cacheKey ) )
1016 return context->cachedValue( cacheKey );
1017
1018 QVariant result;
1019 bool ok = false;
1020
1021 QgsExpressionContext subContext( *context );
1023 subScope->setVariable( QStringLiteral( "parent" ), context->feature(), true );
1024 subContext.appendScope( subScope );
1025 QString error;
1026 result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok, nullptr, context->feedback(), &error );
1027
1028 if ( !ok )
1029 {
1030 if ( !error.isEmpty() )
1031 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1 (%2)" ).arg( subExpression, error ) );
1032 else
1033 parent->setEvalErrorString( QObject::tr( "Could not calculate aggregate for: %1" ).arg( subExpression ) );
1034 return QVariant();
1035 }
1036
1037 // cache value
1038 context->setCachedValue( cacheKey, result );
1039 return result;
1040}
1041
1042
1043static QVariant fcnAggregateCount( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1044{
1045 return fcnAggregateGeneric( QgsAggregateCalculator::Count, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1046}
1047
1048static QVariant fcnAggregateCountDistinct( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1049{
1050 return fcnAggregateGeneric( QgsAggregateCalculator::CountDistinct, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1051}
1052
1053static QVariant fcnAggregateCountMissing( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1054{
1055 return fcnAggregateGeneric( QgsAggregateCalculator::CountMissing, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1056}
1057
1058static QVariant fcnAggregateMin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1059{
1060 return fcnAggregateGeneric( QgsAggregateCalculator::Min, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1061}
1062
1063static QVariant fcnAggregateMax( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1064{
1065 return fcnAggregateGeneric( QgsAggregateCalculator::Max, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1066}
1067
1068static QVariant fcnAggregateSum( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1069{
1070 return fcnAggregateGeneric( QgsAggregateCalculator::Sum, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1071}
1072
1073static QVariant fcnAggregateMean( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1074{
1075 return fcnAggregateGeneric( QgsAggregateCalculator::Mean, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1076}
1077
1078static QVariant fcnAggregateMedian( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1079{
1080 return fcnAggregateGeneric( QgsAggregateCalculator::Median, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1081}
1082
1083static QVariant fcnAggregateStdev( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1084{
1085 return fcnAggregateGeneric( QgsAggregateCalculator::StDevSample, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1086}
1087
1088static QVariant fcnAggregateRange( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1089{
1090 return fcnAggregateGeneric( QgsAggregateCalculator::Range, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1091}
1092
1093static QVariant fcnAggregateMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1094{
1095 return fcnAggregateGeneric( QgsAggregateCalculator::Minority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1096}
1097
1098static QVariant fcnAggregateMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1099{
1100 return fcnAggregateGeneric( QgsAggregateCalculator::Majority, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1101}
1102
1103static QVariant fcnAggregateQ1( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1104{
1105 return fcnAggregateGeneric( QgsAggregateCalculator::FirstQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1106}
1107
1108static QVariant fcnAggregateQ3( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1109{
1110 return fcnAggregateGeneric( QgsAggregateCalculator::ThirdQuartile, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1111}
1112
1113static QVariant fcnAggregateIQR( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1114{
1115 return fcnAggregateGeneric( QgsAggregateCalculator::InterQuartileRange, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1116}
1117
1118static QVariant fcnAggregateMinLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1119{
1120 return fcnAggregateGeneric( QgsAggregateCalculator::StringMinimumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1121}
1122
1123static QVariant fcnAggregateMaxLength( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1124{
1125 return fcnAggregateGeneric( QgsAggregateCalculator::StringMaximumLength, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1126}
1127
1128static QVariant fcnAggregateCollectGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1129{
1130 return fcnAggregateGeneric( QgsAggregateCalculator::GeometryCollect, values, QgsAggregateCalculator::AggregateParameters(), context, parent );
1131}
1132
1133static QVariant fcnAggregateStringConcat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1134{
1136
1137 //fourth node is concatenator
1138 if ( values.count() > 3 )
1139 {
1140 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1142 QVariant value = node->eval( parent, context );
1144 parameters.delimiter = value.toString();
1145 }
1146
1147 return fcnAggregateGeneric( QgsAggregateCalculator::StringConcatenate, values, parameters, context, parent, 4 );
1148}
1149
1150static QVariant fcnAggregateStringConcatUnique( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1151{
1153
1154 //fourth node is concatenator
1155 if ( values.count() > 3 )
1156 {
1157 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 3 ), parent );
1159 QVariant value = node->eval( parent, context );
1161 parameters.delimiter = value.toString();
1162 }
1163
1164 return fcnAggregateGeneric( QgsAggregateCalculator::StringConcatenateUnique, values, parameters, context, parent, 4 );
1165}
1166
1167static QVariant fcnAggregateArray( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1168{
1169 return fcnAggregateGeneric( QgsAggregateCalculator::ArrayAggregate, values, QgsAggregateCalculator::AggregateParameters(), context, parent, 3 );
1170}
1171
1172static QVariant fcnMapScale( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1173{
1174 if ( !context )
1175 return QVariant();
1176
1177 QVariant scale = context->variable( QStringLiteral( "map_scale" ) );
1178 bool ok = false;
1179 if ( QgsVariantUtils::isNull( scale ) )
1180 return QVariant();
1181
1182 const double v = scale.toDouble( &ok );
1183 if ( ok )
1184 return v;
1185 return QVariant();
1186}
1187
1188static QVariant fcnClamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1189{
1190 double minValue = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1191 double testValue = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1192 double maxValue = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1193
1194 // force testValue to sit inside the range specified by the min and max value
1195 if ( testValue <= minValue )
1196 {
1197 return QVariant( minValue );
1198 }
1199 else if ( testValue >= maxValue )
1200 {
1201 return QVariant( maxValue );
1202 }
1203 else
1204 {
1205 return QVariant( testValue );
1206 }
1207}
1208
1209static QVariant fcnFloor( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1210{
1211 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1212 return QVariant( std::floor( x ) );
1213}
1214
1215static QVariant fcnCeil( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1216{
1217 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1218 return QVariant( std::ceil( x ) );
1219}
1220
1221static QVariant fcnToInt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1222{
1223 return QVariant( QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) );
1224}
1225static QVariant fcnToReal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1226{
1227 return QVariant( QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent ) );
1228}
1229static QVariant fcnToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1230{
1231 return QVariant( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ) );
1232}
1233
1234static QVariant fcnToDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1235{
1236 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1237 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1238 if ( format.isEmpty() && !language.isEmpty() )
1239 {
1240 parent->setEvalErrorString( QObject::tr( "A format is required to convert to DateTime when the language is specified" ) );
1241 return QVariant( QDateTime() );
1242 }
1243
1244 if ( format.isEmpty() && language.isEmpty() )
1245 return QVariant( QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent ) );
1246
1247 QString datetimestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1248 QLocale locale = QLocale();
1249 if ( !language.isEmpty() )
1250 {
1251 locale = QLocale( language );
1252 }
1253
1254 QDateTime datetime = locale.toDateTime( datetimestring, format );
1255 if ( !datetime.isValid() )
1256 {
1257 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to DateTime" ).arg( datetimestring ) );
1258 datetime = QDateTime();
1259 }
1260 return QVariant( datetime );
1261}
1262
1263static QVariant fcnMakeDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1264{
1265 const int year = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1266 const int month = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1267 const int day = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
1268
1269 const QDate date( year, month, day );
1270 if ( !date.isValid() )
1271 {
1272 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1273 return QVariant();
1274 }
1275 return QVariant( date );
1276}
1277
1278static QVariant fcnMakeTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1279{
1280 const int hours = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1281 const int minutes = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1282 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1283
1284 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1285 if ( !time.isValid() )
1286 {
1287 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1288 return QVariant();
1289 }
1290 return QVariant( time );
1291}
1292
1293static QVariant fcnMakeDateTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1294{
1295 const int year = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
1296 const int month = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1297 const int day = QgsExpressionUtils::getIntValue( values.at( 2 ), parent );
1298 const int hours = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
1299 const int minutes = QgsExpressionUtils::getIntValue( values.at( 4 ), parent );
1300 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1301
1302 const QDate date( year, month, day );
1303 if ( !date.isValid() )
1304 {
1305 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid date" ).arg( year ).arg( month ).arg( day ) );
1306 return QVariant();
1307 }
1308 const QTime time( hours, minutes, std::floor( seconds ), ( seconds - std::floor( seconds ) ) * 1000 );
1309 if ( !time.isValid() )
1310 {
1311 parent->setEvalErrorString( QObject::tr( "'%1-%2-%3' is not a valid time" ).arg( hours ).arg( minutes ).arg( seconds ) );
1312 return QVariant();
1313 }
1314 return QVariant( QDateTime( date, time ) );
1315}
1316
1317static QVariant fcnMakeInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1318{
1319 const double years = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
1320 const double months = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
1321 const double weeks = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1322 const double days = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
1323 const double hours = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
1324 const double minutes = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
1325 const double seconds = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
1326
1327 return QVariant::fromValue( QgsInterval( years, months, weeks, days, hours, minutes, seconds ) );
1328}
1329
1330static QVariant fcnCoalesce( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1331{
1332 for ( const QVariant &value : values )
1333 {
1334 if ( QgsVariantUtils::isNull( value ) )
1335 continue;
1336 return value;
1337 }
1338 return QVariant();
1339}
1340
1341static QVariant fcnNullIf( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1342{
1343 const QVariant val1 = values.at( 0 );
1344 const QVariant val2 = values.at( 1 );
1345
1346 if ( val1 == val2 )
1347 return QVariant();
1348 else
1349 return val1;
1350}
1351
1352static QVariant fcnLower( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1353{
1354 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1355 return QVariant( str.toLower() );
1356}
1357static QVariant fcnUpper( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1358{
1359 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1360 return QVariant( str.toUpper() );
1361}
1362static QVariant fcnTitle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1363{
1364 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1365 QStringList elems = str.split( ' ' );
1366 for ( int i = 0; i < elems.size(); i++ )
1367 {
1368 if ( elems[i].size() > 1 )
1369 elems[i] = elems[i].at( 0 ).toUpper() + elems[i].mid( 1 ).toLower();
1370 }
1371 return QVariant( elems.join( QLatin1Char( ' ' ) ) );
1372}
1373
1374static QVariant fcnTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1375{
1376 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1377 return QVariant( str.trimmed() );
1378}
1379
1380static QVariant fcnLTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1381{
1382 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1383
1384 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1385
1386 const QRegularExpression re( QStringLiteral( "^([%1]*)" ).arg( QRegularExpression::escape( characters ) ) );
1387 str.replace( re, QString() );
1388 return QVariant( str );
1389}
1390
1391static QVariant fcnRTrim( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1392{
1393 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1394
1395 const QString characters = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1396
1397 const QRegularExpression re( QStringLiteral( "([%1]*)$" ).arg( QRegularExpression::escape( characters ) ) );
1398 str.replace( re, QString() );
1399 return QVariant( str );
1400}
1401
1402static QVariant fcnLevenshtein( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1403{
1404 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1405 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1406 return QVariant( QgsStringUtils::levenshteinDistance( string1, string2, true ) );
1407}
1408
1409static QVariant fcnLCS( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1410{
1411 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1412 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1413 return QVariant( QgsStringUtils::longestCommonSubstring( string1, string2, true ) );
1414}
1415
1416static QVariant fcnHamming( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1417{
1418 QString string1 = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1419 QString string2 = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1420 int dist = QgsStringUtils::hammingDistance( string1, string2 );
1421 return ( dist < 0 ? QVariant() : QVariant( QgsStringUtils::hammingDistance( string1, string2, true ) ) );
1422}
1423
1424static QVariant fcnSoundex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1425{
1426 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1427 return QVariant( QgsStringUtils::soundex( string ) );
1428}
1429
1430static QVariant fcnChar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1431{
1432 QChar character = QChar( QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent ) );
1433 return QVariant( QString( character ) );
1434}
1435
1436static QVariant fcnAscii( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1437{
1438 QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1439
1440 if ( value.isEmpty() )
1441 {
1442 return QVariant();
1443 }
1444
1445 int res = value.at( 0 ).unicode();
1446 return QVariant( res );
1447}
1448
1449static QVariant fcnWordwrap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1450{
1451 if ( values.length() == 2 || values.length() == 3 )
1452 {
1453 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1454 qlonglong wrap = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
1455
1456 QString customdelimiter = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1457
1458 return QgsStringUtils::wordWrap( str, static_cast< int >( wrap ), wrap > 0, customdelimiter );
1459 }
1460
1461 return QVariant();
1462}
1463
1464static QVariant fcnLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1465{
1466 // two variants, one for geometry, one for string
1467 if ( values.at( 0 ).userType() == QMetaType::type( "QgsGeometry" ) )
1468 {
1469 //geometry variant
1470 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
1471 if ( geom.type() != Qgis::GeometryType::Line )
1472 return QVariant();
1473
1474 return QVariant( geom.length() );
1475 }
1476
1477 //otherwise fall back to string variant
1478 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1479 return QVariant( str.length() );
1480}
1481
1482static QVariant fcnLength3D( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1483{
1484 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
1485
1486 if ( geom.type() != Qgis::GeometryType::Line )
1487 return QVariant();
1488
1489 double totalLength = 0;
1490 for ( auto it = geom.const_parts_begin(); it != geom.const_parts_end(); ++it )
1491 {
1492 if ( const QgsLineString *line = qgsgeometry_cast< const QgsLineString * >( *it ) )
1493 {
1494 totalLength += line->length3D();
1495 }
1496 else
1497 {
1498 std::unique_ptr< QgsLineString > segmentized( qgsgeometry_cast< const QgsCurve * >( *it )->curveToLine() );
1499 totalLength += segmentized->length3D();
1500 }
1501 }
1502
1503 return totalLength;
1504}
1505
1506static QVariant fcnReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1507{
1508 if ( values.count() == 2 && values.at( 1 ).type() == QVariant::Map )
1509 {
1510 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1511 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
1512 QVector< QPair< QString, QString > > mapItems;
1513
1514 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
1515 {
1516 mapItems.append( qMakePair( it.key(), it.value().toString() ) );
1517 }
1518
1519 // larger keys should be replaced first since they may contain whole smaller keys
1520 std::sort( mapItems.begin(),
1521 mapItems.end(),
1522 []( const QPair< QString, QString > &pair1,
1523 const QPair< QString, QString > &pair2 )
1524 {
1525 return ( pair1.first.length() > pair2.first.length() );
1526 } );
1527
1528 for ( auto it = mapItems.constBegin(); it != mapItems.constEnd(); ++it )
1529 {
1530 str = str.replace( it->first, it->second );
1531 }
1532
1533 return QVariant( str );
1534 }
1535 else if ( values.count() == 3 )
1536 {
1537 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1538 QVariantList before;
1539 QVariantList after;
1540 bool isSingleReplacement = false;
1541
1542 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).type() != QVariant::StringList )
1543 {
1544 before = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1545 }
1546 else
1547 {
1548 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
1549 }
1550
1551 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
1552 {
1553 after = QVariantList() << QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1554 isSingleReplacement = true;
1555 }
1556 else
1557 {
1558 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
1559 }
1560
1561 if ( !isSingleReplacement && before.length() != after.length() )
1562 {
1563 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
1564 return QVariant();
1565 }
1566
1567 for ( int i = 0; i < before.length(); i++ )
1568 {
1569 str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() );
1570 }
1571
1572 return QVariant( str );
1573 }
1574 else
1575 {
1576 parent->setEvalErrorString( QObject::tr( "Function replace requires 2 or 3 arguments" ) );
1577 return QVariant();
1578 }
1579}
1580
1581static QVariant fcnRegexpReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1582{
1583 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1584 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1585 QString after = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1586
1587 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1588 if ( !re.isValid() )
1589 {
1590 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1591 return QVariant();
1592 }
1593 return QVariant( str.replace( re, after ) );
1594}
1595
1596static QVariant fcnRegexpMatch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1597{
1598 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1599 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1600
1601 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1602 if ( !re.isValid() )
1603 {
1604 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1605 return QVariant();
1606 }
1607 return QVariant( ( str.indexOf( re ) + 1 ) );
1608}
1609
1610static QVariant fcnRegexpMatches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1611{
1612 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1613 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1614 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
1615
1616 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1617 if ( !re.isValid() )
1618 {
1619 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1620 return QVariant();
1621 }
1622
1623 QRegularExpressionMatch matches = re.match( str );
1624 if ( matches.hasMatch() )
1625 {
1626 QVariantList array;
1627 QStringList list = matches.capturedTexts();
1628
1629 // Skip the first string to only return captured groups
1630 for ( QStringList::const_iterator it = ++list.constBegin(); it != list.constEnd(); ++it )
1631 {
1632 array += ( !( *it ).isEmpty() ) ? *it : empty;
1633 }
1634
1635 return QVariant( array );
1636 }
1637 else
1638 {
1639 return QVariant();
1640 }
1641}
1642
1643static QVariant fcnRegexpSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1644{
1645 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1646 QString regexp = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1647
1648 QRegularExpression re( regexp, QRegularExpression::UseUnicodePropertiesOption );
1649 if ( !re.isValid() )
1650 {
1651 parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) );
1652 return QVariant();
1653 }
1654
1655 // extract substring
1656 QRegularExpressionMatch match = re.match( str );
1657 if ( match.hasMatch() )
1658 {
1659 // return first capture
1660 if ( match.lastCapturedIndex() > 0 )
1661 {
1662 // a capture group was present, so use that
1663 return QVariant( match.captured( 1 ) );
1664 }
1665 else
1666 {
1667 // no capture group, so using all match
1668 return QVariant( match.captured( 0 ) );
1669 }
1670 }
1671 else
1672 {
1673 return QVariant( "" );
1674 }
1675}
1676
1677static QVariant fcnUuid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
1678{
1679 QString uuid = QUuid::createUuid().toString();
1680 if ( values.at( 0 ).toString().compare( QStringLiteral( "WithoutBraces" ), Qt::CaseInsensitive ) == 0 )
1681 uuid = QUuid::createUuid().toString( QUuid::StringFormat::WithoutBraces );
1682 else if ( values.at( 0 ).toString().compare( QStringLiteral( "Id128" ), Qt::CaseInsensitive ) == 0 )
1683 uuid = QUuid::createUuid().toString( QUuid::StringFormat::Id128 );
1684 return uuid;
1685}
1686
1687static QVariant fcnSubstr( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1688{
1689 if ( !values.at( 0 ).isValid() || !values.at( 1 ).isValid() )
1690 return QVariant();
1691
1692 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1693 int from = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1694
1695 int len = 0;
1696 if ( values.at( 2 ).isValid() )
1697 len = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
1698 else
1699 len = str.size();
1700
1701 if ( from < 0 )
1702 {
1703 from = str.size() + from;
1704 if ( from < 0 )
1705 {
1706 from = 0;
1707 }
1708 }
1709 else if ( from > 0 )
1710 {
1711 //account for the fact that substr() starts at 1
1712 from -= 1;
1713 }
1714
1715 if ( len < 0 )
1716 {
1717 len = str.size() + len - from;
1718 if ( len < 0 )
1719 {
1720 len = 0;
1721 }
1722 }
1723
1724 return QVariant( str.mid( from, len ) );
1725}
1726static QVariant fcnFeatureId( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1727{
1728 FEAT_FROM_CONTEXT( context, f )
1729 // TODO: handling of 64-bit feature ids?
1730 return QVariant( static_cast< int >( f.id() ) );
1731}
1732
1733static QVariant fcnRasterValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1734{
1735 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1736 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
1737 bool foundLayer = false;
1738 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, geom]( QgsMapLayer * mapLayer )
1739 {
1740 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer * >( mapLayer );
1741 if ( !layer || !layer->dataProvider() )
1742 {
1743 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1744 return QVariant();
1745 }
1746
1747 if ( bandNb < 1 || bandNb > layer->bandCount() )
1748 {
1749 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster band number." ) );
1750 return QVariant();
1751 }
1752
1753 if ( geom.isNull() || geom.type() != Qgis::GeometryType::Point )
1754 {
1755 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid point geometry." ) );
1756 return QVariant();
1757 }
1758
1759 QgsPointXY point = geom.asPoint();
1760 if ( geom.isMultipart() )
1761 {
1762 QgsMultiPointXY multiPoint = geom.asMultiPoint();
1763 if ( multiPoint.count() == 1 )
1764 {
1765 point = multiPoint[0];
1766 }
1767 else
1768 {
1769 // if the geometry contains more than one part, return an undefined value
1770 return QVariant();
1771 }
1772 }
1773
1774 double value = layer->dataProvider()->sample( point, bandNb );
1775 return std::isnan( value ) ? QVariant() : value;
1776 },
1777 foundLayer );
1778
1779 if ( !foundLayer )
1780 {
1781 parent->setEvalErrorString( QObject::tr( "Function `raster_value` requires a valid raster layer." ) );
1782 return QVariant();
1783 }
1784 else
1785 {
1786 return res;
1787 }
1788}
1789
1790static QVariant fcnRasterAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1791{
1792 const int bandNb = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
1793 const double value = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
1794
1795 bool foundLayer = false;
1796 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, bandNb, value]( QgsMapLayer * mapLayer )-> QVariant
1797 {
1798 QgsRasterLayer *layer = qobject_cast< QgsRasterLayer *>( mapLayer );
1799 if ( !layer || !layer->dataProvider() )
1800 {
1801 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1802 return QVariant();
1803 }
1804
1805 if ( bandNb < 1 || bandNb > layer->bandCount() )
1806 {
1807 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster band number." ) );
1808 return QVariant();
1809 }
1810
1811 if ( std::isnan( value ) )
1812 {
1813 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster value." ) );
1814 return QVariant();
1815 }
1816
1817 if ( ! layer->dataProvider()->attributeTable( bandNb ) )
1818 {
1819 return QVariant();
1820 }
1821
1822 const QVariantList data = layer->dataProvider()->attributeTable( bandNb )->row( value );
1823 if ( data.isEmpty() )
1824 {
1825 return QVariant();
1826 }
1827
1828 QVariantMap result;
1829 const QList<QgsRasterAttributeTable::Field> fields { layer->dataProvider()->attributeTable( bandNb )->fields() };
1830 for ( int idx = 0; idx < static_cast<int>( fields.count( ) ) && idx < static_cast<int>( data.count() ); ++idx )
1831 {
1832 const QgsRasterAttributeTable::Field field { fields.at( idx ) };
1833 if ( field.isColor() || field.isRamp() )
1834 {
1835 continue;
1836 }
1837 result.insert( fields.at( idx ).name, data.at( idx ) );
1838 }
1839
1840 return result;
1841 }, foundLayer );
1842
1843 if ( !foundLayer )
1844 {
1845 parent->setEvalErrorString( QObject::tr( "Function `raster_attributes` requires a valid raster layer." ) );
1846 return QVariant();
1847 }
1848 else
1849 {
1850 return res;
1851 }
1852}
1853
1854static QVariant fcnFeature( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
1855{
1856 if ( !context )
1857 return QVariant();
1858
1859 return context->feature();
1860}
1861
1862static QVariant fcnAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1863{
1864 QgsFeature feature;
1865 QString attr;
1866 if ( values.size() == 1 )
1867 {
1868 attr = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
1869 feature = context->feature();
1870 }
1871 else if ( values.size() == 2 )
1872 {
1873 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
1874 attr = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
1875 }
1876 else
1877 {
1878 parent->setEvalErrorString( QObject::tr( "Function `attribute` requires one or two parameters. %n given.", nullptr, values.length() ) );
1879 return QVariant();
1880 }
1881
1882 return feature.attribute( attr );
1883}
1884
1885static QVariant fcnMapToHtmlTable( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1886{
1887 QString table { R"html(
1888 <table>
1889 <thead>
1890 <th>%1</th>
1891 </thead>
1892 <tbody>
1893 <tr><td>%2</td></tr>
1894 </tbody>
1895 </table>)html" };
1896 QVariantMap dict;
1897 if ( values.size() == 1 )
1898 {
1899 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1900 }
1901 else
1902 {
1903 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_table` requires one parameter. %n given.", nullptr, values.length() ) );
1904 return QVariant();
1905 }
1906
1907 if ( dict.isEmpty() )
1908 {
1909 return QVariant();
1910 }
1911
1912 QStringList headers;
1913 QStringList cells;
1914
1915 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1916 {
1917 headers.push_back( it.key().toHtmlEscaped() );
1918 cells.push_back( it.value().toString( ).toHtmlEscaped() );
1919 }
1920
1921 return table.arg( headers.join( QLatin1String( "</th><th>" ) ), cells.join( QLatin1String( "</td><td>" ) ) );
1922}
1923
1924static QVariant fcnMapToHtmlDefinitionList( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
1925{
1926 QString table { R"html(
1927 <dl>
1928 %1
1929 </dl>)html" };
1930 QVariantMap dict;
1931 if ( values.size() == 1 )
1932 {
1933 dict = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
1934 }
1935 else
1936 {
1937 parent->setEvalErrorString( QObject::tr( "Function `map_to_html_dl` requires one parameter. %n given.", nullptr, values.length() ) );
1938 return QVariant();
1939 }
1940
1941 if ( dict.isEmpty() )
1942 {
1943 return QVariant();
1944 }
1945
1946 QString rows;
1947
1948 for ( auto it = dict.cbegin(); it != dict.cend(); ++it )
1949 {
1950 rows.append( QStringLiteral( "<dt>%1</dt><dd>%2</dd>" ).arg( it.key().toHtmlEscaped(), it.value().toString().toHtmlEscaped() ) );
1951 }
1952
1953 return table.arg( rows );
1954}
1955
1956static QVariant fcnValidateFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
1957{
1958 QVariant layer;
1959 if ( values.size() < 1 || QgsVariantUtils::isNull( values.at( 0 ) ) )
1960 {
1961 layer = context->variable( QStringLiteral( "layer" ) );
1962 }
1963 else
1964 {
1965 //first node is layer id or name
1966 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
1968 layer = node->eval( parent, context );
1970 }
1971
1972 QgsFeature feature;
1973 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
1974 {
1975 feature = context->feature();
1976 }
1977 else
1978 {
1979 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
1980 }
1981
1983 const QString strength = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).toLower();
1984 if ( strength == QLatin1String( "hard" ) )
1985 {
1987 }
1988 else if ( strength == QLatin1String( "soft" ) )
1989 {
1991 }
1992
1993 bool foundLayer = false;
1994 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
1995 {
1996 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
1997 if ( !layer )
1998 {
1999 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2000 return QVariant();
2001 }
2002
2003 const QgsFields fields = layer->fields();
2004 bool valid = true;
2005 for ( int i = 0; i < fields.size(); i++ )
2006 {
2007 QStringList errors;
2008 valid = QgsVectorLayerUtils::validateAttribute( layer, feature, i, errors, constraintStrength );
2009 if ( !valid )
2010 {
2011 break;
2012 }
2013 }
2014
2015 return valid;
2016 }, foundLayer );
2017
2018 if ( !foundLayer )
2019 {
2020 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2021 return QVariant();
2022 }
2023
2024 return res;
2025}
2026
2027static QVariant fcnValidateAttribute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2028{
2029 QVariant layer;
2030 if ( values.size() < 2 || QgsVariantUtils::isNull( values.at( 1 ) ) )
2031 {
2032 layer = context->variable( QStringLiteral( "layer" ) );
2033 }
2034 else
2035 {
2036 //first node is layer id or name
2037 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
2039 layer = node->eval( parent, context );
2041 }
2042
2043 QgsFeature feature;
2044 if ( values.size() < 3 || QgsVariantUtils::isNull( values.at( 2 ) ) )
2045 {
2046 feature = context->feature();
2047 }
2048 else
2049 {
2050 feature = QgsExpressionUtils::getFeature( values.at( 2 ), parent );
2051 }
2052
2054 const QString strength = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).toLower();
2055 if ( strength == QLatin1String( "hard" ) )
2056 {
2058 }
2059 else if ( strength == QLatin1String( "soft" ) )
2060 {
2062 }
2063
2064 const QString attributeName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2065
2066 bool foundLayer = false;
2067 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [parent, feature, attributeName, constraintStrength]( QgsMapLayer * mapLayer ) -> QVariant
2068 {
2069 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2070 if ( !layer )
2071 {
2072 return QVariant();
2073 }
2074
2075 const int fieldIndex = layer->fields().indexFromName( attributeName );
2076 if ( fieldIndex == -1 )
2077 {
2078 parent->setEvalErrorString( QObject::tr( "The attribute name did not match any field for the given feature" ) );
2079 return QVariant();
2080 }
2081
2082 QStringList errors;
2083 bool valid = QgsVectorLayerUtils::validateAttribute( layer, feature, fieldIndex, errors, constraintStrength );
2084 return valid;
2085 }, foundLayer );
2086
2087 if ( !foundLayer )
2088 {
2089 parent->setEvalErrorString( QObject::tr( "No layer provided to conduct constraints checks" ) );
2090 return QVariant();
2091 }
2092
2093 return res;
2094}
2095
2096static QVariant fcnAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2097{
2098 QgsFeature feature;
2099 if ( values.size() == 0 || QgsVariantUtils::isNull( values.at( 0 ) ) )
2100 {
2101 feature = context->feature();
2102 }
2103 else
2104 {
2105 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2106 }
2107
2108 const QgsFields fields = feature.fields();
2109 QVariantMap result;
2110 for ( int i = 0; i < fields.count(); ++i )
2111 {
2112 result.insert( fields.at( i ).name(), feature.attribute( i ) );
2113 }
2114 return result;
2115}
2116
2117static QVariant fcnRepresentAttributes( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2118{
2119 QgsVectorLayer *layer = nullptr;
2120 QgsFeature feature;
2121
2122 // TODO this expression function is NOT thread safe
2124 if ( values.isEmpty() )
2125 {
2126 feature = context->feature();
2127 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2128 }
2129 else if ( values.size() == 1 )
2130 {
2131 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2132 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2133 }
2134 else if ( values.size() == 2 )
2135 {
2136 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2137 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2138 }
2139 else
2140 {
2141 parent->setEvalErrorString( QObject::tr( "Function `represent_attributes` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2142 return QVariant();
2143 }
2145
2146 if ( !layer )
2147 {
2148 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: layer could not be resolved." ) );
2149 return QVariant();
2150 }
2151
2152 if ( !feature.isValid() )
2153 {
2154 parent->setEvalErrorString( QObject::tr( "Cannot use represent attributes function: feature could not be resolved." ) );
2155 return QVariant();
2156 }
2157
2158 const QgsFields fields = feature.fields();
2159 QVariantMap result;
2160 for ( int fieldIndex = 0; fieldIndex < fields.count(); ++fieldIndex )
2161 {
2162 const QString fieldName { fields.at( fieldIndex ).name() };
2163 const QVariant attributeVal = feature.attribute( fieldIndex );
2164 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer->id(), fieldName, attributeVal.toString() );
2165 if ( context && context->hasCachedValue( cacheValueKey ) )
2166 {
2167 result.insert( fieldName, context->cachedValue( cacheValueKey ) );
2168 }
2169 else
2170 {
2171 const QgsEditorWidgetSetup setup = layer->editorWidgetSetup( fieldIndex );
2173 QVariant cache;
2174 if ( context )
2175 {
2176 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer->id(), fieldName );
2177
2178 if ( !context->hasCachedValue( cacheKey ) )
2179 {
2180 cache = fieldFormatter->createCache( layer, fieldIndex, setup.config() );
2181 context->setCachedValue( cacheKey, cache );
2182 }
2183 else
2184 {
2185 cache = context->cachedValue( cacheKey );
2186 }
2187 }
2188 QString value( fieldFormatter->representValue( layer, fieldIndex, setup.config(), cache, attributeVal ) );
2189
2190 result.insert( fields.at( fieldIndex ).name(), value );
2191
2192 if ( context )
2193 {
2194 context->setCachedValue( cacheValueKey, value );
2195 }
2196
2197 }
2198 }
2199 return result;
2200}
2201
2202static QVariant fcnCoreFeatureMaptipDisplay( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const bool isMaptip )
2203{
2204 QgsVectorLayer *layer = nullptr;
2205 QgsFeature feature;
2206 bool evaluate = true;
2207
2208 // TODO this expression function is NOT thread safe
2210 if ( values.isEmpty() )
2211 {
2212 feature = context->feature();
2213 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2214 }
2215 else if ( values.size() == 1 )
2216 {
2217 layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
2218 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2219 }
2220 else if ( values.size() == 2 )
2221 {
2222 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2223 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2224 }
2225 else if ( values.size() == 3 )
2226 {
2227 layer = QgsExpressionUtils::getVectorLayer( values.at( 0 ), context, parent );
2228 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2229 evaluate = values.value( 2 ).toBool();
2230 }
2231 else
2232 {
2233 if ( isMaptip )
2234 {
2235 parent->setEvalErrorString( QObject::tr( "Function `maptip` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2236 }
2237 else
2238 {
2239 parent->setEvalErrorString( QObject::tr( "Function `display` requires no more than three parameters. %n given.", nullptr, values.length() ) );
2240 }
2241 return QVariant();
2242 }
2243
2244 if ( !layer )
2245 {
2246 parent->setEvalErrorString( QObject::tr( "The layer is not valid." ) );
2247 return QVariant( );
2248 }
2250
2251 if ( !feature.isValid() )
2252 {
2253 parent->setEvalErrorString( QObject::tr( "The feature is not valid." ) );
2254 return QVariant( );
2255 }
2256
2257 if ( ! evaluate )
2258 {
2259 if ( isMaptip )
2260 {
2261 return layer->mapTipTemplate();
2262 }
2263 else
2264 {
2265 return layer->displayExpression();
2266 }
2267 }
2268
2269 QgsExpressionContext subContext( *context );
2270 subContext.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( layer ) );
2271 subContext.setFeature( feature );
2272
2273 if ( isMaptip )
2274 {
2275 return QgsExpression::replaceExpressionText( layer->mapTipTemplate(), &subContext );
2276 }
2277 else
2278 {
2279 QgsExpression exp( layer->displayExpression() );
2280 exp.prepare( &subContext );
2281 return exp.evaluate( &subContext ).toString();
2282 }
2283}
2284
2285static QVariant fcnFeatureDisplayExpression( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2286{
2287 return fcnCoreFeatureMaptipDisplay( values, context, parent, false );
2288}
2289
2290static QVariant fcnFeatureMaptip( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2291{
2292 return fcnCoreFeatureMaptipDisplay( values, context, parent, true );
2293}
2294
2295static QVariant fcnIsSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2296{
2297 QgsFeature feature;
2298 QVariant layer;
2299 if ( values.isEmpty() )
2300 {
2301 feature = context->feature();
2302 layer = context->variable( QStringLiteral( "layer" ) );
2303 }
2304 else if ( values.size() == 1 )
2305 {
2306 feature = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
2307 layer = context->variable( QStringLiteral( "layer" ) );
2308 }
2309 else if ( values.size() == 2 )
2310 {
2311 feature = QgsExpressionUtils::getFeature( values.at( 1 ), parent );
2312 layer = values.at( 0 );
2313 }
2314 else
2315 {
2316 parent->setEvalErrorString( QObject::tr( "Function `is_selected` requires no more than two parameters. %n given.", nullptr, values.length() ) );
2317 return QVariant();
2318 }
2319
2320 bool foundLayer = false;
2321 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, [feature]( QgsMapLayer * mapLayer ) -> QVariant
2322 {
2323 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2324 if ( !layer || !feature.isValid() )
2325 {
2326 return QVariant( QVariant::Bool );
2327 }
2328
2329 return layer->selectedFeatureIds().contains( feature.id() );
2330 }, foundLayer );
2331 if ( !foundLayer )
2332 return QVariant( QVariant::Bool );
2333 else
2334 return res;
2335}
2336
2337static QVariant fcnNumSelected( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2338{
2339 QVariant layer;
2340
2341 if ( values.isEmpty() )
2342 layer = context->variable( QStringLiteral( "layer" ) );
2343 else if ( values.count() == 1 )
2344 layer = values.at( 0 );
2345 else
2346 {
2347 parent->setEvalErrorString( QObject::tr( "Function `num_selected` requires no more than one parameter. %n given.", nullptr, values.length() ) );
2348 return QVariant();
2349 }
2350
2351 bool foundLayer = false;
2352 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( layer, context, parent, []( QgsMapLayer * mapLayer ) -> QVariant
2353 {
2354 QgsVectorLayer *layer = qobject_cast< QgsVectorLayer * >( mapLayer );
2355 if ( !layer )
2356 {
2357 return QVariant( QVariant::LongLong );
2358 }
2359
2360 return layer->selectedFeatureCount();
2361 }, foundLayer );
2362 if ( !foundLayer )
2363 return QVariant( QVariant::LongLong );
2364 else
2365 return res;
2366}
2367
2368static QVariant fcnSqliteFetchAndIncrement( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2369{
2370 static QMap<QString, qlonglong> counterCache;
2371 QVariant functionResult;
2372
2373 auto fetchAndIncrementFunc = [ values, parent, &functionResult ]( QgsMapLayer * mapLayer, const QString & databaseArgument )
2374 {
2375 QString database;
2376
2377 const QgsVectorLayer *layer = qobject_cast< QgsVectorLayer *>( mapLayer );
2378
2379 if ( layer )
2380 {
2381 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
2382 database = decodedUri.value( QStringLiteral( "path" ) ).toString();
2383 if ( database.isEmpty() )
2384 {
2385 parent->setEvalErrorString( QObject::tr( "Could not extract file path from layer `%1`." ).arg( layer->name() ) );
2386 }
2387 }
2388 else
2389 {
2390 database = databaseArgument;
2391 }
2392
2393 const QString table = values.at( 1 ).toString();
2394 const QString idColumn = values.at( 2 ).toString();
2395 const QString filterAttribute = values.at( 3 ).toString();
2396 const QVariant filterValue = values.at( 4 ).toString();
2397 const QVariantMap defaultValues = values.at( 5 ).toMap();
2398
2399 // read from database
2401 sqlite3_statement_unique_ptr sqliteStatement;
2402
2403 if ( sqliteDb.open_v2( database, SQLITE_OPEN_READWRITE, nullptr ) != SQLITE_OK )
2404 {
2405 parent->setEvalErrorString( QObject::tr( "Could not open sqlite database %1. Error %2. " ).arg( database, sqliteDb.errorMessage() ) );
2406 functionResult = QVariant();
2407 return;
2408 }
2409
2410 QString errorMessage;
2411 QString currentValSql;
2412
2413 qlonglong nextId = 0;
2414 bool cachedMode = false;
2415 bool valueRetrieved = false;
2416
2417 QString cacheString = QStringLiteral( "%1:%2:%3:%4:%5" ).arg( database, table, idColumn, filterAttribute, filterValue.toString() );
2418
2419 // Running in transaction mode, check for cached value first
2420 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2421 {
2422 cachedMode = true;
2423
2424 auto cachedCounter = counterCache.find( cacheString );
2425
2426 if ( cachedCounter != counterCache.end() )
2427 {
2428 qlonglong &cachedValue = cachedCounter.value();
2429 nextId = cachedValue;
2430 nextId += 1;
2431 cachedValue = nextId;
2432 valueRetrieved = true;
2433 }
2434 }
2435
2436 // Either not in cached mode or no cached value found, obtain from DB
2437 if ( !cachedMode || !valueRetrieved )
2438 {
2439 int result = SQLITE_ERROR;
2440
2441 currentValSql = QStringLiteral( "SELECT %1 FROM %2" ).arg( QgsSqliteUtils::quotedIdentifier( idColumn ), QgsSqliteUtils::quotedIdentifier( table ) );
2442 if ( !filterAttribute.isNull() )
2443 {
2444 currentValSql += QStringLiteral( " WHERE %1 = %2" ).arg( QgsSqliteUtils::quotedIdentifier( filterAttribute ), QgsSqliteUtils::quotedValue( filterValue ) );
2445 }
2446
2447 sqliteStatement = sqliteDb.prepare( currentValSql, result );
2448
2449 if ( result == SQLITE_OK )
2450 {
2451 nextId = 0;
2452 if ( sqliteStatement.step() == SQLITE_ROW )
2453 {
2454 nextId = sqliteStatement.columnAsInt64( 0 ) + 1;
2455 }
2456
2457 // If in cached mode: add value to cache and connect to transaction
2458 if ( cachedMode && result == SQLITE_OK )
2459 {
2460 counterCache.insert( cacheString, nextId );
2461
2462 QObject::connect( layer->dataProvider()->transaction(), &QgsTransaction::destroyed, [cacheString]()
2463 {
2464 counterCache.remove( cacheString );
2465 } );
2466 }
2467 valueRetrieved = true;
2468 }
2469 }
2470
2471 if ( valueRetrieved )
2472 {
2473 QString upsertSql;
2474 upsertSql = QStringLiteral( "INSERT OR REPLACE INTO %1" ).arg( QgsSqliteUtils::quotedIdentifier( table ) );
2475 QStringList cols;
2476 QStringList vals;
2477 cols << QgsSqliteUtils::quotedIdentifier( idColumn );
2478 vals << QgsSqliteUtils::quotedValue( nextId );
2479
2480 if ( !filterAttribute.isNull() )
2481 {
2482 cols << QgsSqliteUtils::quotedIdentifier( filterAttribute );
2483 vals << QgsSqliteUtils::quotedValue( filterValue );
2484 }
2485
2486 for ( QVariantMap::const_iterator iter = defaultValues.constBegin(); iter != defaultValues.constEnd(); ++iter )
2487 {
2488 cols << QgsSqliteUtils::quotedIdentifier( iter.key() );
2489 vals << iter.value().toString();
2490 }
2491
2492 upsertSql += QLatin1String( " (" ) + cols.join( ',' ) + ')';
2493 upsertSql += QLatin1String( " VALUES " );
2494 upsertSql += '(' + vals.join( ',' ) + ')';
2495
2496 int result = SQLITE_ERROR;
2497 if ( layer && layer->dataProvider() && layer->dataProvider()->transaction() )
2498 {
2499 QgsTransaction *transaction = layer->dataProvider()->transaction();
2500 if ( transaction->executeSql( upsertSql, errorMessage ) )
2501 {
2502 result = SQLITE_OK;
2503 }
2504 }
2505 else
2506 {
2507 result = sqliteDb.exec( upsertSql, errorMessage );
2508 }
2509 if ( result == SQLITE_OK )
2510 {
2511 functionResult = QVariant( nextId );
2512 return;
2513 }
2514 else
2515 {
2516 parent->setEvalErrorString( QStringLiteral( "Could not increment value: SQLite error: \"%1\" (%2)." ).arg( errorMessage, QString::number( result ) ) );
2517 functionResult = QVariant();
2518 return;
2519 }
2520 }
2521
2522 functionResult = QVariant();
2523 };
2524
2525 bool foundLayer = false;
2526 QgsExpressionUtils::executeLambdaForMapLayer( values.at( 0 ), context, parent, [&fetchAndIncrementFunc]( QgsMapLayer * layer )
2527 {
2528 fetchAndIncrementFunc( layer, QString() );
2529 }, foundLayer );
2530 if ( !foundLayer )
2531 {
2532 const QString databasePath = values.at( 0 ).toString();
2533 QgsThreadingUtils::runOnMainThread( [&fetchAndIncrementFunc, databasePath]
2534 {
2535 fetchAndIncrementFunc( nullptr, databasePath );
2536 } );
2537 }
2538
2539 return functionResult;
2540}
2541
2542static QVariant fcnConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2543{
2544 QString concat;
2545 for ( const QVariant &value : values )
2546 {
2547 if ( !QgsVariantUtils::isNull( value ) )
2548 concat += QgsExpressionUtils::getStringValue( value, parent );
2549 }
2550 return concat;
2551}
2552
2553static QVariant fcnStrpos( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2554{
2555 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2556 return string.indexOf( QgsExpressionUtils::getStringValue( values.at( 1 ), parent ) ) + 1;
2557}
2558
2559static QVariant fcnRight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2560{
2561 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2562 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2563 return string.right( pos );
2564}
2565
2566static QVariant fcnLeft( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2567{
2568 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2569 int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2570 return string.left( pos );
2571}
2572
2573static QVariant fcnRPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2574{
2575 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2576 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2577 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2578 return string.leftJustified( length, fill.at( 0 ), true );
2579}
2580
2581static QVariant fcnLPad( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2582{
2583 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2584 int length = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
2585 QString fill = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2586 return string.rightJustified( length, fill.at( 0 ), true );
2587}
2588
2589static QVariant fcnFormatString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2590{
2591 if ( values.size() < 1 )
2592 {
2593 parent->setEvalErrorString( QObject::tr( "Function format requires at least 1 argument" ) );
2594 return QVariant();
2595 }
2596
2597 QString string = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2598 for ( int n = 1; n < values.length(); n++ )
2599 {
2600 string = string.arg( QgsExpressionUtils::getStringValue( values.at( n ), parent ) );
2601 }
2602 return string;
2603}
2604
2605
2606static QVariant fcnNow( const QVariantList &, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
2607{
2608 return QVariant( QDateTime::currentDateTime() );
2609}
2610
2611static QVariant fcnToDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2612{
2613 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2614 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2615 if ( format.isEmpty() && !language.isEmpty() )
2616 {
2617 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Date when the language is specified" ) );
2618 return QVariant( QDate() );
2619 }
2620
2621 if ( format.isEmpty() && language.isEmpty() )
2622 return QVariant( QgsExpressionUtils::getDateValue( values.at( 0 ), parent ) );
2623
2624 QString datestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2625 QLocale locale = QLocale();
2626 if ( !language.isEmpty() )
2627 {
2628 locale = QLocale( language );
2629 }
2630
2631 QDate date = locale.toDate( datestring, format );
2632 if ( !date.isValid() )
2633 {
2634 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Date" ).arg( datestring ) );
2635 date = QDate();
2636 }
2637 return QVariant( date );
2638}
2639
2640static QVariant fcnToTime( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2641{
2642 QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2643 QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
2644 if ( format.isEmpty() && !language.isEmpty() )
2645 {
2646 parent->setEvalErrorString( QObject::tr( "A format is required to convert to Time when the language is specified" ) );
2647 return QVariant( QTime() );
2648 }
2649
2650 if ( format.isEmpty() && language.isEmpty() )
2651 return QVariant( QgsExpressionUtils::getTimeValue( values.at( 0 ), parent ) );
2652
2653 QString timestring = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
2654 QLocale locale = QLocale();
2655 if ( !language.isEmpty() )
2656 {
2657 locale = QLocale( language );
2658 }
2659
2660 QTime time = locale.toTime( timestring, format );
2661 if ( !time.isValid() )
2662 {
2663 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to Time" ).arg( timestring ) );
2664 time = QTime();
2665 }
2666 return QVariant( time );
2667}
2668
2669static QVariant fcnToInterval( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2670{
2671 return QVariant::fromValue( QgsExpressionUtils::getInterval( values.at( 0 ), parent ) );
2672}
2673
2674/*
2675 * DMS functions
2676 */
2677
2678static QVariant floatToDegreeFormat( const QgsCoordinateFormatter::Format format, const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2679{
2680 double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
2681 QString axis = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2682 int precision = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
2683
2684 QString formatString;
2685 if ( values.count() > 3 )
2686 formatString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent );
2687
2688 QgsCoordinateFormatter::FormatFlags flags = QgsCoordinateFormatter::FormatFlags();
2689 if ( formatString.compare( QLatin1String( "suffix" ), Qt::CaseInsensitive ) == 0 )
2690 {
2692 }
2693 else if ( formatString.compare( QLatin1String( "aligned" ), Qt::CaseInsensitive ) == 0 )
2694 {
2696 }
2697 else if ( ! formatString.isEmpty() )
2698 {
2699 parent->setEvalErrorString( QObject::tr( "Invalid formatting parameter: '%1'. It must be empty, or 'suffix' or 'aligned'." ).arg( formatString ) );
2700 return QVariant();
2701 }
2702
2703 if ( axis.compare( QLatin1String( "x" ), Qt::CaseInsensitive ) == 0 )
2704 {
2705 return QVariant::fromValue( QgsCoordinateFormatter::formatX( value, format, precision, flags ) );
2706 }
2707 else if ( axis.compare( QLatin1String( "y" ), Qt::CaseInsensitive ) == 0 )
2708 {
2709 return QVariant::fromValue( QgsCoordinateFormatter::formatY( value, format, precision, flags ) );
2710 }
2711 else
2712 {
2713 parent->setEvalErrorString( QObject::tr( "Invalid axis name: '%1'. It must be either 'x' or 'y'." ).arg( axis ) );
2714 return QVariant();
2715 }
2716}
2717
2718static QVariant fcnToDegreeMinute( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2719{
2721 return floatToDegreeFormat( format, values, context, parent, node );
2722}
2723
2724static QVariant fcnToDecimal( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2725{
2726 double value = 0.0;
2727 bool ok = false;
2728 value = QgsCoordinateUtils::dmsToDecimal( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), &ok );
2729
2730 return ok ? QVariant( value ) : QVariant();
2731}
2732
2733static QVariant fcnToDegreeMinuteSecond( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
2734{
2736 return floatToDegreeFormat( format, values, context, parent, node );
2737}
2738
2739static QVariant fcnAge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2740{
2741 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2742 QDateTime d2 = QgsExpressionUtils::getDateTimeValue( values.at( 1 ), parent );
2743 qint64 seconds = d2.secsTo( d1 );
2744 return QVariant::fromValue( QgsInterval( seconds ) );
2745}
2746
2747static QVariant fcnDayOfWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2748{
2749 if ( !values.at( 0 ).canConvert<QDate>() )
2750 return QVariant();
2751
2752 QDate date = QgsExpressionUtils::getDateValue( values.at( 0 ), parent );
2753 if ( !date.isValid() )
2754 return QVariant();
2755
2756 // return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
2757 // (to match PostgreSQL behavior)
2758 return date.dayOfWeek() % 7;
2759}
2760
2761static QVariant fcnDay( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2762{
2763 QVariant value = values.at( 0 );
2764 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2765 if ( inter.isValid() )
2766 {
2767 return QVariant( inter.days() );
2768 }
2769 else
2770 {
2771 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2772 return QVariant( d1.date().day() );
2773 }
2774}
2775
2776static QVariant fcnYear( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2777{
2778 QVariant value = values.at( 0 );
2779 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2780 if ( inter.isValid() )
2781 {
2782 return QVariant( inter.years() );
2783 }
2784 else
2785 {
2786 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2787 return QVariant( d1.date().year() );
2788 }
2789}
2790
2791static QVariant fcnMonth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2792{
2793 QVariant value = values.at( 0 );
2794 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2795 if ( inter.isValid() )
2796 {
2797 return QVariant( inter.months() );
2798 }
2799 else
2800 {
2801 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2802 return QVariant( d1.date().month() );
2803 }
2804}
2805
2806static QVariant fcnWeek( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2807{
2808 QVariant value = values.at( 0 );
2809 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2810 if ( inter.isValid() )
2811 {
2812 return QVariant( inter.weeks() );
2813 }
2814 else
2815 {
2816 QDateTime d1 = QgsExpressionUtils::getDateTimeValue( value, parent );
2817 return QVariant( d1.date().weekNumber() );
2818 }
2819}
2820
2821static QVariant fcnHour( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2822{
2823 QVariant value = values.at( 0 );
2824 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2825 if ( inter.isValid() )
2826 {
2827 return QVariant( inter.hours() );
2828 }
2829 else
2830 {
2831 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2832 return QVariant( t1.hour() );
2833 }
2834}
2835
2836static QVariant fcnMinute( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2837{
2838 QVariant value = values.at( 0 );
2839 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2840 if ( inter.isValid() )
2841 {
2842 return QVariant( inter.minutes() );
2843 }
2844 else
2845 {
2846 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2847 return QVariant( t1.minute() );
2848 }
2849}
2850
2851static QVariant fcnSeconds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2852{
2853 QVariant value = values.at( 0 );
2854 QgsInterval inter = QgsExpressionUtils::getInterval( value, parent, false );
2855 if ( inter.isValid() )
2856 {
2857 return QVariant( inter.seconds() );
2858 }
2859 else
2860 {
2861 QTime t1 = QgsExpressionUtils::getTimeValue( value, parent );
2862 return QVariant( t1.second() );
2863 }
2864}
2865
2866static QVariant fcnEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2867{
2868 QDateTime dt = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
2869 if ( dt.isValid() )
2870 {
2871 return QVariant( dt.toMSecsSinceEpoch() );
2872 }
2873 else
2874 {
2875 return QVariant();
2876 }
2877}
2878
2879static QVariant fcnDateTimeFromEpoch( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2880{
2881 long long millisecs_since_epoch = QgsExpressionUtils::getIntValue( values.at( 0 ), parent );
2882 // no sense to check for strange values, as Qt behavior is undefined anyway (see docs)
2883 return QVariant( QDateTime::fromMSecsSinceEpoch( millisecs_since_epoch ) );
2884}
2885
2886static QVariant fcnExif( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2887{
2888 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2889 if ( parent->hasEvalError() )
2890 {
2891 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif" ) ) );
2892 return QVariant();
2893 }
2894 QString tag = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
2895 return !tag.isNull() ? QgsExifTools::readTag( filepath, tag ) : QVariant( QgsExifTools::readTags( filepath ) );
2896}
2897
2898static QVariant fcnExifGeoTag( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
2900 const QString filepath = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
2901 if ( parent->hasEvalError() )
2902 {
2903 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "exif_geotag" ) ) );
2904 return QVariant();
2905 }
2906 bool ok;
2907 return QVariant::fromValue( QgsGeometry( new QgsPoint( QgsExifTools::getGeoTag( filepath, ok ) ) ) );
2908}
2909
2910#define ENSURE_GEOM_TYPE(f, g, geomtype) \
2911 if ( !(f).hasGeometry() ) \
2912 return QVariant(); \
2913 QgsGeometry g = (f).geometry(); \
2914 if ( (g).type() != (geomtype) ) \
2915 return QVariant();
2916
2917static QVariant fcnX( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2918{
2919 FEAT_FROM_CONTEXT( context, f )
2920 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Point )
2921 if ( g.isMultipart() )
2922 {
2923 return g.asMultiPoint().at( 0 ).x();
2924 }
2925 else
2926 {
2927 return g.asPoint().x();
2928 }
2929}
2930
2931static QVariant fcnY( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2932{
2933 FEAT_FROM_CONTEXT( context, f )
2934 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Point )
2935 if ( g.isMultipart() )
2936 {
2937 return g.asMultiPoint().at( 0 ).y();
2938 }
2939 else
2940 {
2941 return g.asPoint().y();
2942 }
2943}
2944
2945static QVariant fcnZ( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
2946{
2947 FEAT_FROM_CONTEXT( context, f )
2948 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Point )
2949
2950 if ( g.isEmpty() )
2951 return QVariant();
2952
2953 const QgsAbstractGeometry *abGeom = g.constGet();
2954
2955 if ( g.isEmpty() || !abGeom->is3D() )
2956 return QVariant();
2957
2958 if ( g.type() == Qgis::GeometryType::Point && !g.isMultipart() )
2959 {
2960 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( g.constGet() );
2961 if ( point )
2962 return point->z();
2963 }
2964 else if ( g.type() == Qgis::GeometryType::Point && g.isMultipart() )
2965 {
2966 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( g.constGet() ) )
2967 {
2968 if ( collection->numGeometries() > 0 )
2969 {
2970 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
2971 return point->z();
2972 }
2973 }
2974 }
2975
2976 return QVariant();
2977}
2978
2979static QVariant fcnGeomIsValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2980{
2981 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
2982 if ( geom.isNull() )
2983 return QVariant();
2984
2985 bool isValid = geom.isGeosValid();
2986
2987 return QVariant( isValid );
2988}
2989
2990static QVariant fcnGeomMakeValid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
2991{
2992 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
2993 if ( geom.isNull() )
2994 return QVariant();
2995
2996 const QString methodString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).trimmed();
2997#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
2999#else
3001#endif
3002 if ( methodString.compare( QLatin1String( "linework" ), Qt::CaseInsensitive ) == 0 )
3004 else if ( methodString.compare( QLatin1String( "structure" ), Qt::CaseInsensitive ) == 0 )
3006
3007 const bool keepCollapsed = values.value( 2 ).toBool();
3008
3009 QgsGeometry valid;
3010 try
3011 {
3012 valid = geom.makeValid( method, keepCollapsed );
3013 }
3014 catch ( QgsNotSupportedException & )
3015 {
3016 parent->setEvalErrorString( QObject::tr( "The make_valid parameters require a newer GEOS library version" ) );
3017 return QVariant();
3018 }
3019
3020 return QVariant::fromValue( valid );
3021}
3022
3023static QVariant fcnGeometryCollectionAsArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3024{
3025 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3026 if ( geom.isNull() )
3027 return QVariant();
3028
3029 QVector<QgsGeometry> multiGeom = geom.asGeometryCollection();
3030 QVariantList array;
3031 for ( int i = 0; i < multiGeom.size(); ++i )
3032 {
3033 array += QVariant::fromValue( multiGeom.at( i ) );
3034 }
3035
3036 return array;
3037}
3038
3039static QVariant fcnGeomX( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3040{
3041 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3042 if ( geom.isNull() )
3043 return QVariant();
3044
3045 //if single point, return the point's x coordinate
3046 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3047 {
3048 return geom.asPoint().x();
3049 }
3050
3051 //otherwise return centroid x
3052 QgsGeometry centroid = geom.centroid();
3053 QVariant result( centroid.asPoint().x() );
3054 return result;
3055}
3056
3057static QVariant fcnGeomY( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3058{
3059 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3060 if ( geom.isNull() )
3061 return QVariant();
3062
3063 //if single point, return the point's y coordinate
3064 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3065 {
3066 return geom.asPoint().y();
3067 }
3068
3069 //otherwise return centroid y
3070 QgsGeometry centroid = geom.centroid();
3071 QVariant result( centroid.asPoint().y() );
3072 return result;
3073}
3074
3075static QVariant fcnGeomZ( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3076{
3077 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3078 if ( geom.isNull() )
3079 return QVariant(); //or 0?
3080
3081 if ( !geom.constGet()->is3D() )
3082 return QVariant();
3083
3084 //if single point, return the point's z coordinate
3085 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3086 {
3087 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3088 if ( point )
3089 return point->z();
3090 }
3091 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3092 {
3093 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3094 {
3095 if ( collection->numGeometries() == 1 )
3096 {
3097 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3098 return point->z();
3099 }
3100 }
3101 }
3102
3103 return QVariant();
3104}
3105
3106static QVariant fcnGeomM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3107{
3108 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3109 if ( geom.isNull() )
3110 return QVariant(); //or 0?
3111
3112 if ( !geom.constGet()->isMeasure() )
3113 return QVariant();
3114
3115 //if single point, return the point's m value
3116 if ( geom.type() == Qgis::GeometryType::Point && !geom.isMultipart() )
3117 {
3118 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3119 if ( point )
3120 return point->m();
3121 }
3122 else if ( geom.type() == Qgis::GeometryType::Point && geom.isMultipart() )
3123 {
3124 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3125 {
3126 if ( collection->numGeometries() == 1 )
3127 {
3128 if ( const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) ) )
3129 return point->m();
3130 }
3131 }
3132 }
3133
3134 return QVariant();
3135}
3136
3137static QVariant fcnPointN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3138{
3139 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3140
3141 if ( geom.isNull() )
3142 return QVariant();
3143
3144 int idx = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
3145
3146 if ( idx < 0 )
3147 {
3148 //negative idx
3149 int count = geom.constGet()->nCoordinates();
3150 idx = count + idx;
3151 }
3152 else
3153 {
3154 //positive idx is 1 based
3155 idx -= 1;
3156 }
3157
3158 QgsVertexId vId;
3159 if ( idx < 0 || !geom.vertexIdFromVertexNr( idx, vId ) )
3160 {
3161 parent->setEvalErrorString( QObject::tr( "Point index is out of range" ) );
3162 return QVariant();
3163 }
3164
3165 QgsPoint point = geom.constGet()->vertexAt( vId );
3166 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3167}
3168
3169static QVariant fcnStartPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3170{
3171 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3172
3173 if ( geom.isNull() )
3174 return QVariant();
3175
3176 QgsVertexId vId;
3177 if ( !geom.vertexIdFromVertexNr( 0, vId ) )
3178 {
3179 return QVariant();
3180 }
3181
3182 QgsPoint point = geom.constGet()->vertexAt( vId );
3183 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3184}
3185
3186static QVariant fcnEndPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3187{
3188 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3189
3190 if ( geom.isNull() )
3191 return QVariant();
3192
3193 QgsVertexId vId;
3194 if ( !geom.vertexIdFromVertexNr( geom.constGet()->nCoordinates() - 1, vId ) )
3195 {
3196 return QVariant();
3197 }
3198
3199 QgsPoint point = geom.constGet()->vertexAt( vId );
3200 return QVariant::fromValue( QgsGeometry( new QgsPoint( point ) ) );
3201}
3202
3203static QVariant fcnNodesToPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3204{
3205 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3206
3207 if ( geom.isNull() )
3208 return QVariant();
3209
3210 bool ignoreClosing = false;
3211 if ( values.length() > 1 )
3212 {
3213 ignoreClosing = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3214 }
3215
3216 QgsMultiPoint *mp = new QgsMultiPoint();
3217
3218 const QgsCoordinateSequence sequence = geom.constGet()->coordinateSequence();
3219 for ( const QgsRingSequence &part : sequence )
3220 {
3221 for ( const QgsPointSequence &ring : part )
3222 {
3223 bool skipLast = false;
3224 if ( ignoreClosing && ring.count() > 2 && ring.first() == ring.last() )
3225 {
3226 skipLast = true;
3227 }
3228
3229 for ( int i = 0; i < ( skipLast ? ring.count() - 1 : ring.count() ); ++ i )
3230 {
3231 mp->addGeometry( ring.at( i ).clone() );
3232 }
3233 }
3234 }
3235
3236 return QVariant::fromValue( QgsGeometry( mp ) );
3237}
3238
3239static QVariant fcnSegmentsToLines( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3240{
3241 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3242
3243 if ( geom.isNull() )
3244 return QVariant();
3245
3246 const QVector< QgsLineString * > linesToProcess = QgsGeometryUtils::extractLineStrings( geom.constGet() );
3247
3248 //OK, now we have a complete list of segmentized lines from the geometry
3250 for ( QgsLineString *line : linesToProcess )
3251 {
3252 for ( int i = 0; i < line->numPoints() - 1; ++i )
3253 {
3255 segment->setPoints( QgsPointSequence()
3256 << line->pointN( i )
3257 << line->pointN( i + 1 ) );
3258 ml->addGeometry( segment );
3259 }
3260 delete line;
3261 }
3262
3263 return QVariant::fromValue( QgsGeometry( ml ) );
3264}
3265
3266static QVariant fcnInteriorRingN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3267{
3268 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3269
3270 if ( geom.isNull() )
3271 return QVariant();
3272
3273 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
3274 if ( !curvePolygon && geom.isMultipart() )
3275 {
3276 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3277 {
3278 if ( collection->numGeometries() == 1 )
3279 {
3280 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
3281 }
3282 }
3283 }
3284
3285 if ( !curvePolygon )
3286 return QVariant();
3287
3288 //idx is 1 based
3289 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3290
3291 if ( idx >= curvePolygon->numInteriorRings() || idx < 0 )
3292 return QVariant();
3293
3294 QgsCurve *curve = static_cast< QgsCurve * >( curvePolygon->interiorRing( static_cast< int >( idx ) )->clone() );
3295 QVariant result = curve ? QVariant::fromValue( QgsGeometry( curve ) ) : QVariant();
3296 return result;
3297}
3298
3299static QVariant fcnGeometryN( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3300{
3301 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3302
3303 if ( geom.isNull() )
3304 return QVariant();
3305
3306 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
3307 if ( !collection )
3308 return QVariant();
3309
3310 //idx is 1 based
3311 qlonglong idx = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) - 1;
3312
3313 if ( idx < 0 || idx >= collection->numGeometries() )
3314 return QVariant();
3315
3316 QgsAbstractGeometry *part = collection->geometryN( static_cast< int >( idx ) )->clone();
3317 QVariant result = part ? QVariant::fromValue( QgsGeometry( part ) ) : QVariant();
3318 return result;
3319}
3320
3321static QVariant fcnBoundary( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3322{
3323 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3324
3325 if ( geom.isNull() )
3326 return QVariant();
3327
3328 QgsAbstractGeometry *boundary = geom.constGet()->boundary();
3329 if ( !boundary )
3330 return QVariant();
3331
3332 return QVariant::fromValue( QgsGeometry( boundary ) );
3333}
3334
3335static QVariant fcnLineMerge( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3336{
3337 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3338
3339 if ( geom.isNull() )
3340 return QVariant();
3341
3342 QgsGeometry merged = geom.mergeLines();
3343 if ( merged.isNull() )
3344 return QVariant();
3345
3346 return QVariant::fromValue( merged );
3347}
3348
3349static QVariant fcnSharedPaths( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3350{
3351 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3352 if ( geom.isNull() )
3353 return QVariant();
3354
3355 const QgsGeometry geom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
3356 if ( geom2.isNull() )
3357 return QVariant();
3358
3359 const QgsGeometry sharedPaths = geom.sharedPaths( geom2 );
3360 if ( sharedPaths.isNull() )
3361 return QVariant();
3362
3363 return QVariant::fromValue( sharedPaths );
3364}
3365
3366
3367static QVariant fcnSimplify( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3368{
3369 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3370
3371 if ( geom.isNull() )
3372 return QVariant();
3373
3374 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3375
3376 QgsGeometry simplified = geom.simplify( tolerance );
3377 if ( simplified.isNull() )
3378 return QVariant();
3379
3380 return simplified;
3381}
3382
3383static QVariant fcnSimplifyVW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3384{
3385 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3386
3387 if ( geom.isNull() )
3388 return QVariant();
3389
3390 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3391
3393
3394 QgsGeometry simplified = simplifier.simplify( geom );
3395 if ( simplified.isNull() )
3396 return QVariant();
3397
3398 return simplified;
3399}
3400
3401static QVariant fcnSmooth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3402{
3403 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3404
3405 if ( geom.isNull() )
3406 return QVariant();
3407
3408 int iterations = std::min( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), 10 );
3409 double offset = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ), 0.0, 0.5 );
3410 double minLength = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3411 double maxAngle = std::clamp( QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent ), 0.0, 180.0 );
3412
3413 QgsGeometry smoothed = geom.smooth( static_cast<unsigned int>( iterations ), offset, minLength, maxAngle );
3414 if ( smoothed.isNull() )
3415 return QVariant();
3416
3417 return smoothed;
3418}
3419
3420static QVariant fcnTriangularWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3421{
3422 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3423
3424 if ( geom.isNull() )
3425 return QVariant();
3426
3427 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3428 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3429 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3430
3431 const QgsGeometry waved = geom.triangularWaves( wavelength, amplitude, strict );
3432 if ( waved.isNull() )
3433 return QVariant();
3434
3435 return waved;
3436}
3437
3438static QVariant fcnTriangularWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3439{
3440 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3441
3442 if ( geom.isNull() )
3443 return QVariant();
3444
3445 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3446 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3447 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3448 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3449 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3450
3451 const QgsGeometry waved = geom.triangularWavesRandomized( minWavelength, maxWavelength,
3452 minAmplitude, maxAmplitude, seed );
3453 if ( waved.isNull() )
3454 return QVariant();
3455
3456 return waved;
3457}
3458
3459static QVariant fcnSquareWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3460{
3461 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3462
3463 if ( geom.isNull() )
3464 return QVariant();
3465
3466 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3467 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3468 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3469
3470 const QgsGeometry waved = geom.squareWaves( wavelength, amplitude, strict );
3471 if ( waved.isNull() )
3472 return QVariant();
3473
3474 return waved;
3475}
3476
3477static QVariant fcnSquareWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3478{
3479 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3480
3481 if ( geom.isNull() )
3482 return QVariant();
3483
3484 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3485 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3486 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3487 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3488 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3489
3490 const QgsGeometry waved = geom.squareWavesRandomized( minWavelength, maxWavelength,
3491 minAmplitude, maxAmplitude, seed );
3492 if ( waved.isNull() )
3493 return QVariant();
3494
3495 return waved;
3496}
3497
3498static QVariant fcnRoundWave( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3499{
3500 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3501
3502 if ( geom.isNull() )
3503 return QVariant();
3504
3505 const double wavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3506 const double amplitude = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3507 const bool strict = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
3508
3509 const QgsGeometry waved = geom.roundWaves( wavelength, amplitude, strict );
3510 if ( waved.isNull() )
3511 return QVariant();
3512
3513 return waved;
3514}
3515
3516static QVariant fcnRoundWaveRandomized( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3517{
3518 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3519
3520 if ( geom.isNull() )
3521 return QVariant();
3522
3523 const double minWavelength = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3524 const double maxWavelength = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3525 const double minAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3526 const double maxAmplitude = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
3527 const long long seed = QgsExpressionUtils::getIntValue( values.at( 5 ), parent );
3528
3529 const QgsGeometry waved = geom.roundWavesRandomized( minWavelength, maxWavelength,
3530 minAmplitude, maxAmplitude, seed );
3531 if ( waved.isNull() )
3532 return QVariant();
3533
3534 return waved;
3535}
3536
3537static QVariant fcnApplyDashPattern( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3538{
3539 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3540
3541 if ( geom.isNull() )
3542 return QVariant();
3543
3544 const QVariantList pattern = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
3545 QVector< double > dashPattern;
3546 dashPattern.reserve( pattern.size() );
3547 for ( const QVariant &value : std::as_const( pattern ) )
3548 {
3549 bool ok = false;
3550 double v = value.toDouble( &ok );
3551 if ( ok )
3552 {
3553 dashPattern << v;
3554 }
3555 else
3556 {
3557 parent->setEvalErrorString( QStringLiteral( "Dash pattern must be an array of numbers" ) );
3558 return QgsGeometry();
3559 }
3560 }
3561
3562 if ( dashPattern.size() % 2 != 0 )
3563 {
3564 parent->setEvalErrorString( QStringLiteral( "Dash pattern must contain an even number of elements" ) );
3565 return QgsGeometry();
3566 }
3567
3568 const QString startRuleString = QgsExpressionUtils::getStringValue( values.at( 2 ), parent ).trimmed();
3570 if ( startRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3572 else if ( startRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3574 else if ( startRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3576 else if ( startRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3578 else if ( startRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3580 else
3581 {
3582 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( startRuleString ) );
3583 return QgsGeometry();
3584 }
3585
3586 const QString endRuleString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
3588 if ( endRuleString.compare( QLatin1String( "no_rule" ), Qt::CaseInsensitive ) == 0 )
3590 else if ( endRuleString.compare( QLatin1String( "full_dash" ), Qt::CaseInsensitive ) == 0 )
3592 else if ( endRuleString.compare( QLatin1String( "half_dash" ), Qt::CaseInsensitive ) == 0 )
3594 else if ( endRuleString.compare( QLatin1String( "full_gap" ), Qt::CaseInsensitive ) == 0 )
3596 else if ( endRuleString.compare( QLatin1String( "half_gap" ), Qt::CaseInsensitive ) == 0 )
3598 else
3599 {
3600 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern rule" ).arg( endRuleString ) );
3601 return QgsGeometry();
3602 }
3603
3604 const QString adjustString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
3606 if ( adjustString.compare( QLatin1String( "both" ), Qt::CaseInsensitive ) == 0 )
3608 else if ( adjustString.compare( QLatin1String( "dash" ), Qt::CaseInsensitive ) == 0 )
3610 else if ( adjustString.compare( QLatin1String( "gap" ), Qt::CaseInsensitive ) == 0 )
3612 else
3613 {
3614 parent->setEvalErrorString( QStringLiteral( "'%1' is not a valid dash pattern size adjustment" ).arg( adjustString ) );
3615 return QgsGeometry();
3616 }
3617
3618 const double patternOffset = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
3619
3620 const QgsGeometry result = geom.applyDashPattern( dashPattern, startRule, endRule, adjustment, patternOffset );
3621 if ( result.isNull() )
3622 return QVariant();
3623
3624 return result;
3625}
3626
3627static QVariant fcnDensifyByCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3628{
3629 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3630
3631 if ( geom.isNull() )
3632 return QVariant();
3633
3634 const long long count = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
3635 const QgsGeometry densified = geom.densifyByCount( static_cast< int >( count ) );
3636 if ( densified.isNull() )
3637 return QVariant();
3638
3639 return densified;
3640}
3641
3642static QVariant fcnDensifyByDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3643{
3644 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3645
3646 if ( geom.isNull() )
3647 return QVariant();
3648
3649 const double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3650 const QgsGeometry densified = geom.densifyByDistance( distance );
3651 if ( densified.isNull() )
3652 return QVariant();
3653
3654 return densified;
3655}
3656
3657static QVariant fcnCollectGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3658{
3659 QVariantList list;
3660 if ( values.size() == 1 && QgsExpressionUtils::isList( values.at( 0 ) ) )
3661 {
3662 list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
3663 }
3664 else
3665 {
3666 list = values;
3667 }
3668
3669 QVector< QgsGeometry > parts;
3670 parts.reserve( list.size() );
3671 for ( const QVariant &value : std::as_const( list ) )
3672 {
3673 if ( value.userType() == QMetaType::type( "QgsGeometry" ) )
3674 {
3675 parts << value.value<QgsGeometry>();
3676 }
3677 else
3678 {
3679 parent->setEvalErrorString( QStringLiteral( "Cannot convert to geometry" ) );
3680 return QgsGeometry();
3681 }
3682 }
3683
3684 return QgsGeometry::collectGeometry( parts );
3685}
3686
3687static QVariant fcnMakePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3688{
3689 if ( values.count() < 2 || values.count() > 4 )
3690 {
3691 parent->setEvalErrorString( QObject::tr( "Function make_point requires 2-4 arguments" ) );
3692 return QVariant();
3693 }
3694
3695 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3696 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3697 double z = values.count() >= 3 ? QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent ) : 0.0;
3698 double m = values.count() >= 4 ? QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent ) : 0.0;
3699 switch ( values.count() )
3700 {
3701 case 2:
3702 return QVariant::fromValue( QgsGeometry( new QgsPoint( x, y ) ) );
3703 case 3:
3704 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZ, x, y, z ) ) );
3705 case 4:
3706 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointZM, x, y, z, m ) ) );
3707 }
3708 return QVariant(); //avoid warning
3709}
3710
3711static QVariant fcnMakePointM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3712{
3713 double x = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
3714 double y = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3715 double m = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3716 return QVariant::fromValue( QgsGeometry( new QgsPoint( Qgis::WkbType::PointM, x, y, 0.0, m ) ) );
3717}
3718
3719static QVariant fcnMakeLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3720{
3721 if ( values.empty() )
3722 {
3723 return QVariant();
3724 }
3725
3726 QVector<QgsPoint> points;
3727 points.reserve( values.count() );
3728
3729 auto addPoint = [&points]( const QgsGeometry & geom )
3730 {
3731 if ( geom.isNull() )
3732 return;
3733
3734 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3735 return;
3736
3737 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3738 if ( !point )
3739 return;
3740
3741 points << *point;
3742 };
3743
3744 for ( const QVariant &value : values )
3745 {
3746 if ( value.type() == QVariant::List )
3747 {
3748 const QVariantList list = value.toList();
3749 for ( const QVariant &v : list )
3750 {
3751 addPoint( QgsExpressionUtils::getGeometry( v, parent ) );
3752 }
3753 }
3754 else
3755 {
3756 addPoint( QgsExpressionUtils::getGeometry( value, parent ) );
3757 }
3758 }
3759
3760 if ( points.count() < 2 )
3761 return QVariant();
3762
3763 return QgsGeometry( new QgsLineString( points ) );
3764}
3765
3766static QVariant fcnMakePolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3767{
3768 if ( values.count() < 1 )
3769 {
3770 parent->setEvalErrorString( QObject::tr( "Function make_polygon requires an argument" ) );
3771 return QVariant();
3772 }
3773
3774 QgsGeometry outerRing = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3775
3776 if ( outerRing.type() == Qgis::GeometryType::Polygon )
3777 return outerRing; // if it's already a polygon we have nothing to do
3778
3779 if ( outerRing.type() != Qgis::GeometryType::Line || outerRing.isNull() )
3780 return QVariant();
3781
3782 std::unique_ptr< QgsPolygon > polygon = std::make_unique< QgsPolygon >();
3783
3784 const QgsCurve *exteriorRing = qgsgeometry_cast< QgsCurve * >( outerRing.constGet() );
3785 if ( !exteriorRing && outerRing.isMultipart() )
3786 {
3787 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( outerRing.constGet() ) )
3788 {
3789 if ( collection->numGeometries() == 1 )
3790 {
3791 exteriorRing = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3792 }
3793 }
3794 }
3795
3796 if ( !exteriorRing )
3797 return QVariant();
3798
3799 polygon->setExteriorRing( exteriorRing->segmentize() );
3800
3801
3802 for ( int i = 1; i < values.count(); ++i )
3803 {
3804 QgsGeometry ringGeom = QgsExpressionUtils::getGeometry( values.at( i ), parent );
3805 if ( ringGeom.isNull() )
3806 continue;
3807
3808 if ( ringGeom.type() != Qgis::GeometryType::Line || ringGeom.isNull() )
3809 continue;
3810
3811 const QgsCurve *ring = qgsgeometry_cast< QgsCurve * >( ringGeom.constGet() );
3812 if ( !ring && ringGeom.isMultipart() )
3813 {
3814 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( ringGeom.constGet() ) )
3815 {
3816 if ( collection->numGeometries() == 1 )
3817 {
3818 ring = qgsgeometry_cast< QgsCurve * >( collection->geometryN( 0 ) );
3819 }
3820 }
3821 }
3822
3823 if ( !ring )
3824 continue;
3825
3826 polygon->addInteriorRing( ring->segmentize() );
3827 }
3828
3829 return QVariant::fromValue( QgsGeometry( std::move( polygon ) ) );
3830}
3831
3832static QVariant fcnMakeTriangle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3833{
3834 std::unique_ptr<QgsTriangle> tr( new QgsTriangle() );
3835 std::unique_ptr<QgsLineString> lineString( new QgsLineString() );
3836 lineString->clear();
3837
3838 for ( const QVariant &value : values )
3839 {
3840 QgsGeometry geom = QgsExpressionUtils::getGeometry( value, parent );
3841 if ( geom.isNull() )
3842 return QVariant();
3843
3844 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3845 return QVariant();
3846
3847 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3848 if ( !point && geom.isMultipart() )
3849 {
3850 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3851 {
3852 if ( collection->numGeometries() == 1 )
3853 {
3854 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3855 }
3856 }
3857 }
3858
3859 if ( !point )
3860 return QVariant();
3861
3862 lineString->addVertex( *point );
3863 }
3864
3865 tr->setExteriorRing( lineString.release() );
3866
3867 return QVariant::fromValue( QgsGeometry( tr.release() ) );
3868}
3869
3870static QVariant fcnMakeCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3871{
3872 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3873 if ( geom.isNull() )
3874 return QVariant();
3875
3876 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3877 return QVariant();
3878
3879 double radius = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3880 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
3881
3882 if ( segment < 3 )
3883 {
3884 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3885 return QVariant();
3886 }
3887 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3888 if ( !point && geom.isMultipart() )
3889 {
3890 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3891 {
3892 if ( collection->numGeometries() == 1 )
3893 {
3894 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3895 }
3896 }
3897 }
3898 if ( !point )
3899 return QVariant();
3900
3901 QgsCircle circ( *point, radius );
3902 return QVariant::fromValue( QgsGeometry( circ.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3903}
3904
3905static QVariant fcnMakeEllipse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3906{
3907 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3908 if ( geom.isNull() )
3909 return QVariant();
3910
3911 if ( geom.type() != Qgis::GeometryType::Point || geom.isMultipart() )
3912 return QVariant();
3913
3914 double majorAxis = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
3915 double minorAxis = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
3916 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
3917 int segment = QgsExpressionUtils::getNativeIntValue( values.at( 4 ), parent );
3918 if ( segment < 3 )
3919 {
3920 parent->setEvalErrorString( QObject::tr( "Segment must be greater than 2" ) );
3921 return QVariant();
3922 }
3923 const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( geom.constGet() );
3924 if ( !point && geom.isMultipart() )
3925 {
3926 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() ) )
3927 {
3928 if ( collection->numGeometries() == 1 )
3929 {
3930 point = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3931 }
3932 }
3933 }
3934 if ( !point )
3935 return QVariant();
3936
3937 QgsEllipse elp( *point, majorAxis, minorAxis, azimuth );
3938 return QVariant::fromValue( QgsGeometry( elp.toPolygon( static_cast<unsigned int>( segment ) ) ) );
3939}
3940
3941static QVariant fcnMakeRegularPolygon( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
3942{
3943
3944 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
3945 if ( pt1.isNull() )
3946 return QVariant();
3947
3948 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
3949 return QVariant();
3950
3951 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
3952 if ( pt2.isNull() )
3953 return QVariant();
3954
3955 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
3956 return QVariant();
3957
3958 unsigned int nbEdges = static_cast<unsigned int>( QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) );
3959 if ( nbEdges < 3 )
3960 {
3961 parent->setEvalErrorString( QObject::tr( "Number of edges/sides must be greater than 2" ) );
3962 return QVariant();
3963 }
3964
3965 QgsRegularPolygon::ConstructionOption option = static_cast< QgsRegularPolygon::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
3967 {
3968 parent->setEvalErrorString( QObject::tr( "Option can be 0 (inscribed) or 1 (circumscribed)" ) );
3969 return QVariant();
3970 }
3971
3972 const QgsPoint *center = qgsgeometry_cast< const QgsPoint * >( pt1.constGet() );
3973 if ( !center && pt1.isMultipart() )
3974 {
3975 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt1.constGet() ) )
3976 {
3977 if ( collection->numGeometries() == 1 )
3978 {
3979 center = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3980 }
3981 }
3982 }
3983 if ( !center )
3984 return QVariant();
3985
3986 const QgsPoint *corner = qgsgeometry_cast< const QgsPoint * >( pt2.constGet() );
3987 if ( !corner && pt2.isMultipart() )
3988 {
3989 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( pt2.constGet() ) )
3990 {
3991 if ( collection->numGeometries() == 1 )
3992 {
3993 corner = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
3994 }
3995 }
3996 }
3997 if ( !corner )
3998 return QVariant();
3999
4000 QgsRegularPolygon rp = QgsRegularPolygon( *center, *corner, nbEdges, option );
4001
4002 return QVariant::fromValue( QgsGeometry( rp.toPolygon() ) );
4003
4004}
4005
4006static QVariant fcnMakeSquare( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4007{
4008 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4009 if ( pt1.isNull() )
4010 return QVariant();
4011 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4012 return QVariant();
4013
4014 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4015 if ( pt2.isNull() )
4016 return QVariant();
4017 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4018 return QVariant();
4019
4020 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4021 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4022 QgsQuadrilateral square = QgsQuadrilateral::squareFromDiagonal( *point1, *point2 );
4023
4024 return QVariant::fromValue( QgsGeometry( square.toPolygon() ) );
4025}
4026
4027static QVariant fcnMakeRectangleFrom3Points( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4028{
4029 QgsGeometry pt1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4030 if ( pt1.isNull() )
4031 return QVariant();
4032 if ( pt1.type() != Qgis::GeometryType::Point || pt1.isMultipart() )
4033 return QVariant();
4034
4035 QgsGeometry pt2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4036 if ( pt2.isNull() )
4037 return QVariant();
4038 if ( pt2.type() != Qgis::GeometryType::Point || pt2.isMultipart() )
4039 return QVariant();
4040
4041 QgsGeometry pt3 = QgsExpressionUtils::getGeometry( values.at( 2 ), parent );
4042 if ( pt3.isNull() )
4043 return QVariant();
4044 if ( pt3.type() != Qgis::GeometryType::Point || pt3.isMultipart() )
4045 return QVariant();
4046
4047 QgsQuadrilateral::ConstructionOption option = static_cast< QgsQuadrilateral::ConstructionOption >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4048 if ( ( option < QgsQuadrilateral::Distance ) || ( option > QgsQuadrilateral::Projected ) )
4049 {
4050 parent->setEvalErrorString( QObject::tr( "Option can be 0 (distance) or 1 (projected)" ) );
4051 return QVariant();
4052 }
4053 const QgsPoint *point1 = qgsgeometry_cast< const QgsPoint *>( pt1.constGet() );
4054 const QgsPoint *point2 = qgsgeometry_cast< const QgsPoint *>( pt2.constGet() );
4055 const QgsPoint *point3 = qgsgeometry_cast< const QgsPoint *>( pt3.constGet() );
4056 QgsQuadrilateral rect = QgsQuadrilateral::rectangleFrom3Points( *point1, *point2, *point3, option );
4057 return QVariant::fromValue( QgsGeometry( rect.toPolygon() ) );
4058}
4059
4060static QVariant pointAt( const QgsGeometry &geom, int idx, QgsExpression *parent ) // helper function
4061{
4062 if ( geom.isNull() )
4063 return QVariant();
4064
4065 if ( idx < 0 )
4066 {
4067 idx += geom.constGet()->nCoordinates();
4068 }
4069 if ( idx < 0 || idx >= geom.constGet()->nCoordinates() )
4070 {
4071 parent->setEvalErrorString( QObject::tr( "Index is out of range" ) );
4072 return QVariant();
4073 }
4074 return QVariant::fromValue( geom.vertexAt( idx ) );
4075}
4076
4077// function used for the old $ style
4078static QVariant fcnOldXat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4079{
4080 FEAT_FROM_CONTEXT( context, feature )
4081 const QgsGeometry geom = feature.geometry();
4082 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4083
4084 const QVariant v = pointAt( geom, idx, parent );
4085
4086 if ( !v.isNull() )
4087 return QVariant( v.value<QgsPoint>().x() );
4088 else
4089 return QVariant();
4090}
4091static QVariant fcnXat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4092{
4093 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))
4094 {
4095 return fcnOldXat( values, f, parent, node );
4096 }
4097 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)
4098 {
4099 return fcnOldXat( QVariantList() << values[1], f, parent, node );
4100 }
4101
4102 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4103 if ( geom.isNull() )
4104 {
4105 return QVariant();
4106 }
4107
4108 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4109
4110 const QVariant v = pointAt( geom, vertexNumber, parent );
4111 if ( !v.isNull() )
4112 return QVariant( v.value<QgsPoint>().x() );
4113 else
4114 return QVariant();
4115}
4116
4117// function used for the old $ style
4118static QVariant fcnOldYat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4119{
4120 FEAT_FROM_CONTEXT( context, feature )
4121 const QgsGeometry geom = feature.geometry();
4122 const int idx = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
4123
4124 const QVariant v = pointAt( geom, idx, parent );
4125
4126 if ( !v.isNull() )
4127 return QVariant( v.value<QgsPoint>().y() );
4128 else
4129 return QVariant();
4130}
4131static QVariant fcnYat( const QVariantList &values, const QgsExpressionContext *f, QgsExpression *parent, const QgsExpressionNodeFunction *node )
4132{
4133 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))
4134 {
4135 return fcnOldYat( values, f, parent, node );
4136 }
4137 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)
4138 {
4139 return fcnOldYat( QVariantList() << values[1], f, parent, node );
4140 }
4141
4142 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4143 if ( geom.isNull() )
4144 {
4145 return QVariant();
4146 }
4147
4148 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4149
4150 const QVariant v = pointAt( geom, vertexNumber, parent );
4151 if ( !v.isNull() )
4152 return QVariant( v.value<QgsPoint>().y() );
4153 else
4154 return QVariant();
4155}
4156
4157static QVariant fcnZat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4158{
4159 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4160 if ( geom.isNull() )
4161 {
4162 return QVariant();
4163 }
4164
4165 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4166
4167 const QVariant v = pointAt( geom, vertexNumber, parent );
4168 if ( !v.isNull() && v.value<QgsPoint>().is3D() )
4169 return QVariant( v.value<QgsPoint>().z() );
4170 else
4171 return QVariant();
4172}
4173
4174static QVariant fcnMat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4175{
4176 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4177 if ( geom.isNull() )
4178 {
4179 return QVariant();
4180 }
4181
4182 const int vertexNumber = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
4183
4184 const QVariant v = pointAt( geom, vertexNumber, parent );
4185 if ( !v.isNull() && v.value<QgsPoint>().isMeasure() )
4186 return QVariant( v.value<QgsPoint>().m() );
4187 else
4188 return QVariant();
4189}
4190
4191
4192static QVariant fcnGeometry( const QVariantList &, const QgsExpressionContext *context, QgsExpression *, const QgsExpressionNodeFunction * )
4193{
4194 if ( !context )
4195 return QVariant();
4196
4197 // prefer geometry from context if it's present, otherwise fallback to context's feature's geometry
4198 if ( context->hasGeometry() )
4199 return context->geometry();
4200 else
4201 {
4202 FEAT_FROM_CONTEXT( context, f )
4203 QgsGeometry geom = f.geometry();
4204 if ( !geom.isNull() )
4205 return QVariant::fromValue( geom );
4206 else
4207 return QVariant();
4208 }
4209}
4210
4211static QVariant fcnGeomFromWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4212{
4213 QString wkt = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4214 QgsGeometry geom = QgsGeometry::fromWkt( wkt );
4215 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4216 return result;
4217}
4218
4219static QVariant fcnGeomFromWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4220{
4221 const QByteArray wkb = QgsExpressionUtils::getBinaryValue( values.at( 0 ), parent );
4222 if ( wkb.isNull() )
4223 return QVariant();
4224
4225 QgsGeometry geom;
4226 geom.fromWkb( wkb );
4227 return !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4228}
4229
4230static QVariant fcnGeomFromGML( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4231{
4232 QString gml = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
4233 QgsOgcUtils::Context ogcContext;
4234 if ( context )
4235 {
4236 QgsWeakMapLayerPointer mapLayerPtr {context->variable( QStringLiteral( "layer" ) ).value<QgsWeakMapLayerPointer>() };
4237 if ( mapLayerPtr )
4238 {
4239 ogcContext.layer = mapLayerPtr.data();
4240 ogcContext.transformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
4241 }
4242 }
4243 QgsGeometry geom = QgsOgcUtils::geometryFromGML( gml, ogcContext );
4244 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4245 return result;
4246}
4247
4248static QVariant fcnGeomArea( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4249{
4250 FEAT_FROM_CONTEXT( context, f )
4251 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Polygon )
4252 QgsDistanceArea *calc = parent->geomCalculator();
4253 if ( calc )
4254 {
4255 double area = calc->measureArea( f.geometry() );
4256 area = calc->convertAreaMeasurement( area, parent->areaUnits() );
4257 return QVariant( area );
4258 }
4259 else
4260 {
4261 return QVariant( f.geometry().area() );
4262 }
4263}
4264
4265static QVariant fcnArea( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4266{
4267 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4268
4269 if ( geom.type() != Qgis::GeometryType::Polygon )
4270 return QVariant();
4271
4272 return QVariant( geom.area() );
4273}
4274
4275static QVariant fcnGeomLength( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4276{
4277 FEAT_FROM_CONTEXT( context, f )
4278 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Line )
4279 QgsDistanceArea *calc = parent->geomCalculator();
4280 if ( calc )
4281 {
4282 double len = calc->measureLength( f.geometry() );
4283 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4284 return QVariant( len );
4285 }
4286 else
4287 {
4288 return QVariant( f.geometry().length() );
4289 }
4290}
4291
4292static QVariant fcnGeomPerimeter( const QVariantList &, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
4293{
4294 FEAT_FROM_CONTEXT( context, f )
4295 ENSURE_GEOM_TYPE( f, g, Qgis::GeometryType::Polygon )
4296 QgsDistanceArea *calc = parent->geomCalculator();
4297 if ( calc )
4298 {
4299 double len = calc->measurePerimeter( f.geometry() );
4300 len = calc->convertLengthMeasurement( len, parent->distanceUnits() );
4301 return QVariant( len );
4302 }
4303 else
4304 {
4305 return f.geometry().isNull() ? QVariant( 0 ) : QVariant( f.geometry().constGet()->perimeter() );
4306 }
4307}
4308
4309static QVariant fcnPerimeter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4310{
4311 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4312
4313 if ( geom.type() != Qgis::GeometryType::Polygon )
4314 return QVariant();
4315
4316 //length for polygons = perimeter
4317 return QVariant( geom.length() );
4318}
4319
4320static QVariant fcnGeomNumPoints( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4321{
4322 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4323 return QVariant( geom.isNull() ? 0 : geom.constGet()->nCoordinates() );
4324}
4325
4326static QVariant fcnGeomNumGeometries( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4327{
4328 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4329 if ( geom.isNull() )
4330 return QVariant();
4331
4332 return QVariant( geom.constGet()->partCount() );
4333}
4334
4335static QVariant fcnGeomIsMultipart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4336{
4337 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4338 if ( geom.isNull() )
4339 return QVariant();
4340
4341 return QVariant( geom.isMultipart() );
4342}
4343
4344static QVariant fcnGeomNumInteriorRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4345{
4346 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4347
4348 if ( geom.isNull() )
4349 return QVariant();
4350
4351 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4352 if ( curvePolygon )
4353 return QVariant( curvePolygon->numInteriorRings() );
4354
4355 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4356 if ( collection )
4357 {
4358 //find first CurvePolygon in collection
4359 for ( int i = 0; i < collection->numGeometries(); ++i )
4360 {
4361 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon *>( collection->geometryN( i ) );
4362 if ( !curvePolygon )
4363 continue;
4364
4365 return QVariant( curvePolygon->isEmpty() ? 0 : curvePolygon->numInteriorRings() );
4366 }
4367 }
4368
4369 return QVariant();
4370}
4371
4372static QVariant fcnGeomNumRings( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4373{
4374 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4375
4376 if ( geom.isNull() )
4377 return QVariant();
4378
4379 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet() );
4380 if ( curvePolygon )
4381 return QVariant( curvePolygon->ringCount() );
4382
4383 bool foundPoly = false;
4384 int ringCount = 0;
4385 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
4386 if ( collection )
4387 {
4388 //find CurvePolygons in collection
4389 for ( int i = 0; i < collection->numGeometries(); ++i )
4390 {
4391 curvePolygon = qgsgeometry_cast< QgsCurvePolygon *>( collection->geometryN( i ) );
4392 if ( !curvePolygon )
4393 continue;
4394
4395 foundPoly = true;
4396 ringCount += curvePolygon->ringCount();
4397 }
4398 }
4399
4400 if ( !foundPoly )
4401 return QVariant();
4402
4403 return QVariant( ringCount );
4404}
4405
4406static QVariant fcnBounds( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4407{
4408 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4409 QgsGeometry geomBounds = QgsGeometry::fromRect( geom.boundingBox() );
4410 QVariant result = !geomBounds.isNull() ? QVariant::fromValue( geomBounds ) : QVariant();
4411 return result;
4412}
4413
4414static QVariant fcnBoundsWidth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4415{
4416 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4417 return QVariant::fromValue( geom.boundingBox().width() );
4418}
4419
4420static QVariant fcnBoundsHeight( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4421{
4422 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4423 return QVariant::fromValue( geom.boundingBox().height() );
4424}
4425
4426static QVariant fcnGeometryType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4427{
4428 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4429 if ( geom.isNull() )
4430 return QVariant();
4431
4433}
4434
4435static QVariant fcnXMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4436{
4437 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4438 return QVariant::fromValue( geom.boundingBox().xMinimum() );
4439}
4440
4441static QVariant fcnXMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4442{
4443 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4444 return QVariant::fromValue( geom.boundingBox().xMaximum() );
4445}
4446
4447static QVariant fcnYMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4448{
4449 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4450 return QVariant::fromValue( geom.boundingBox().yMinimum() );
4451}
4452
4453static QVariant fcnYMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4454{
4455 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4456 return QVariant::fromValue( geom.boundingBox().yMaximum() );
4457}
4458
4459static QVariant fcnZMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4460{
4461 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4462
4463 if ( geom.isNull() || geom.isEmpty( ) )
4464 return QVariant();
4465
4466 if ( !geom.constGet()->is3D() )
4467 return QVariant();
4468
4469 double max = std::numeric_limits< double >::lowest();
4470
4471 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4472 {
4473 double z = ( *it ).z();
4474
4475 if ( max < z )
4476 max = z;
4477 }
4478
4479 if ( max == std::numeric_limits< double >::lowest() )
4480 return QVariant( QVariant::Double );
4481
4482 return QVariant( max );
4483}
4484
4485static QVariant fcnZMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4486{
4487 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4488
4489 if ( geom.isNull() || geom.isEmpty() )
4490 return QVariant();
4491
4492 if ( !geom.constGet()->is3D() )
4493 return QVariant();
4494
4495 double min = std::numeric_limits< double >::max();
4496
4497 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4498 {
4499 double z = ( *it ).z();
4500
4501 if ( z < min )
4502 min = z;
4503 }
4504
4505 if ( min == std::numeric_limits< double >::max() )
4506 return QVariant( QVariant::Double );
4507
4508 return QVariant( min );
4509}
4510
4511static QVariant fcnMMin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4512{
4513 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4514
4515 if ( geom.isNull() || geom.isEmpty() )
4516 return QVariant();
4517
4518 if ( !geom.constGet()->isMeasure() )
4519 return QVariant();
4520
4521 double min = std::numeric_limits< double >::max();
4522
4523 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4524 {
4525 double m = ( *it ).m();
4526
4527 if ( m < min )
4528 min = m;
4529 }
4530
4531 if ( min == std::numeric_limits< double >::max() )
4532 return QVariant( QVariant::Double );
4533
4534 return QVariant( min );
4535}
4536
4537static QVariant fcnMMax( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4538{
4539 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4540
4541 if ( geom.isNull() || geom.isEmpty() )
4542 return QVariant();
4543
4544 if ( !geom.constGet()->isMeasure() )
4545 return QVariant();
4546
4547 double max = std::numeric_limits< double >::lowest();
4548
4549 for ( auto it = geom.vertices_begin(); it != geom.vertices_end(); ++it )
4550 {
4551 double m = ( *it ).m();
4552
4553 if ( max < m )
4554 max = m;
4555 }
4556
4557 if ( max == std::numeric_limits< double >::lowest() )
4558 return QVariant( QVariant::Double );
4559
4560 return QVariant( max );
4561}
4562
4563static QVariant fcnSinuosity( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4564{
4565 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4566 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom.constGet() );
4567 if ( !curve )
4568 {
4569 parent->setEvalErrorString( QObject::tr( "Function `sinuosity` requires a line geometry." ) );
4570 return QVariant();
4571 }
4572
4573 return QVariant( curve->sinuosity() );
4574}
4575
4576static QVariant fcnStraightDistance2d( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4577{
4578 const QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4579 const QgsCurve *curve = geom.constGet() ? qgsgeometry_cast< const QgsCurve * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4580 if ( !curve )
4581 {
4582 parent->setEvalErrorString( QObject::tr( "Function `straight_distance_2d` requires a line geometry or a multi line geometry with a single part." ) );
4583 return QVariant();
4584 }
4585
4586 return QVariant( curve->straightDistance2d() );
4587}
4588
4589static QVariant fcnRoundness( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4590{
4591 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4592 const QgsCurvePolygon *poly = geom.constGet() ? qgsgeometry_cast< const QgsCurvePolygon * >( geom.constGet()->simplifiedTypeRef() ) : nullptr;
4593
4594 if ( !poly )
4595 {
4596 parent->setEvalErrorString( QObject::tr( "Function `roundness` requires a polygon geometry or a multi polygon geometry with a single part." ) );
4597 return QVariant();
4598 }
4599
4600 return QVariant( poly->roundness() );
4601}
4602
4603
4604
4605static QVariant fcnFlipCoordinates( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4606{
4607 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4608 if ( geom.isNull() )
4609 return QVariant();
4610
4611 std::unique_ptr< QgsAbstractGeometry > flipped( geom.constGet()->clone() );
4612 flipped->swapXy();
4613 return QVariant::fromValue( QgsGeometry( std::move( flipped ) ) );
4614}
4615
4616static QVariant fcnIsClosed( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4617{
4618 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4619 if ( fGeom.isNull() )
4620 return QVariant();
4621
4622 const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( fGeom.constGet() );
4623 if ( !curve && fGeom.isMultipart() )
4624 {
4625 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4626 {
4627 if ( collection->numGeometries() == 1 )
4628 {
4629 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
4630 }
4631 }
4632 }
4633
4634 if ( !curve )
4635 return QVariant();
4636
4637 return QVariant::fromValue( curve->isClosed() );
4638}
4639
4640static QVariant fcnCloseLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4641{
4642 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4643
4644 if ( geom.isNull() )
4645 return QVariant();
4646
4647 QVariant result;
4648 if ( !geom.isMultipart() )
4649 {
4650 const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( geom.constGet() );
4651
4652 if ( !line )
4653 return QVariant();
4654
4655 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4656 closedLine->close();
4657
4658 result = QVariant::fromValue( QgsGeometry( std::move( closedLine ) ) );
4659 }
4660 else
4661 {
4662 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( geom.constGet() );
4663
4664 std::unique_ptr< QgsGeometryCollection > closed( collection->createEmptyWithSameType() );
4665
4666 for ( int i = 0; i < collection->numGeometries(); ++i )
4667 {
4668 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString * >( collection->geometryN( i ) ) )
4669 {
4670 std::unique_ptr< QgsLineString > closedLine( line->clone() );
4671 closedLine->close();
4672
4673 closed->addGeometry( closedLine.release() );
4674 }
4675 }
4676 result = QVariant::fromValue( QgsGeometry( std::move( closed ) ) );
4677 }
4678
4679 return result;
4680}
4681
4682static QVariant fcnIsEmpty( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4683{
4684 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4685 if ( fGeom.isNull() )
4686 return QVariant();
4687
4688 return QVariant::fromValue( fGeom.isEmpty() );
4689}
4690
4691static QVariant fcnIsEmptyOrNull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4692{
4693 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
4694 return QVariant::fromValue( true );
4695
4696 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4697 return QVariant::fromValue( fGeom.isNull() || fGeom.isEmpty() );
4698}
4699
4700static QVariant fcnRelate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4701{
4702 if ( values.length() < 2 || values.length() > 3 )
4703 return QVariant();
4704
4705 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4706 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4707
4708 if ( fGeom.isNull() || sGeom.isNull() )
4709 return QVariant();
4710
4711 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( fGeom.constGet() ) );
4712
4713 if ( values.length() == 2 )
4714 {
4715 //two geometry arguments, return relation
4716 QString result = engine->relate( sGeom.constGet() );
4717 return QVariant::fromValue( result );
4718 }
4719 else
4720 {
4721 //three arguments, test pattern
4722 QString pattern = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
4723 bool result = engine->relatePattern( sGeom.constGet(), pattern );
4724 return QVariant::fromValue( result );
4725 }
4726}
4727
4728static QVariant fcnBbox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4729{
4730 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4731 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4732 return fGeom.intersects( sGeom.boundingBox() ) ? TVL_True : TVL_False;
4733}
4734static QVariant fcnDisjoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4735{
4736 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4737 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4738 return fGeom.disjoint( sGeom ) ? TVL_True : TVL_False;
4739}
4740static QVariant fcnIntersects( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4741{
4742 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4743 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4744 return fGeom.intersects( sGeom ) ? TVL_True : TVL_False;
4745}
4746static QVariant fcnTouches( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4747{
4748 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4749 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4750 return fGeom.touches( sGeom ) ? TVL_True : TVL_False;
4751}
4752static QVariant fcnCrosses( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4753{
4754 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4755 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4756 return fGeom.crosses( sGeom ) ? TVL_True : TVL_False;
4757}
4758static QVariant fcnContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4759{
4760 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4761 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4762 return fGeom.contains( sGeom ) ? TVL_True : TVL_False;
4763}
4764static QVariant fcnOverlaps( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4765{
4766 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4767 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4768 return fGeom.overlaps( sGeom ) ? TVL_True : TVL_False;
4769}
4770static QVariant fcnWithin( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4771{
4772 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4773 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
4774 return fGeom.within( sGeom ) ? TVL_True : TVL_False;
4775}
4776
4777static QVariant fcnBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4778{
4779 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4780 const double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4781 const int seg = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4782 const QString endCapString = QgsExpressionUtils::getStringValue( values.at( 3 ), parent ).trimmed();
4783 const QString joinString = QgsExpressionUtils::getStringValue( values.at( 4 ), parent ).trimmed();
4784 const double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
4785
4786 Qgis::EndCapStyle capStyle = Qgis::EndCapStyle::Round;
4787 if ( endCapString.compare( QLatin1String( "flat" ), Qt::CaseInsensitive ) == 0 )
4788 capStyle = Qgis::EndCapStyle::Flat;
4789 else if ( endCapString.compare( QLatin1String( "square" ), Qt::CaseInsensitive ) == 0 )
4790 capStyle = Qgis::EndCapStyle::Square;
4791
4792 Qgis::JoinStyle joinStyle = Qgis::JoinStyle::Round;
4793 if ( joinString.compare( QLatin1String( "miter" ), Qt::CaseInsensitive ) == 0 )
4794 joinStyle = Qgis::JoinStyle::Miter;
4795 else if ( joinString.compare( QLatin1String( "bevel" ), Qt::CaseInsensitive ) == 0 )
4796 joinStyle = Qgis::JoinStyle::Bevel;
4797
4798 QgsGeometry geom = fGeom.buffer( dist, seg, capStyle, joinStyle, miterLimit );
4799 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4800 return result;
4801}
4802
4803static QVariant fcnForceRHR( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4804{
4805 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4806 const QgsGeometry reoriented = fGeom.forceRHR();
4807 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4808}
4809
4810static QVariant fcnForcePolygonCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4811{
4812 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4813 const QgsGeometry reoriented = fGeom.forcePolygonClockwise();
4814 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4815}
4816
4817static QVariant fcnForcePolygonCCW( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4818{
4819 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4820 const QgsGeometry reoriented = fGeom.forcePolygonCounterClockwise();
4821 return !reoriented.isNull() ? QVariant::fromValue( reoriented ) : QVariant();
4822}
4823
4824static QVariant fcnWedgeBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4825{
4826 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4827 const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( fGeom.constGet() );
4828 if ( !pt && fGeom.isMultipart() )
4829 {
4830 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
4831 {
4832 if ( collection->numGeometries() == 1 )
4833 {
4834 pt = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
4835 }
4836 }
4837 }
4838
4839 if ( !pt )
4840 {
4841 parent->setEvalErrorString( QObject::tr( "Function `wedge_buffer` requires a point value for the center." ) );
4842 return QVariant();
4843 }
4844
4845 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4846 double width = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4847 double outerRadius = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4848 double innerRadius = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
4849
4850 QgsGeometry geom = QgsGeometry::createWedgeBuffer( *pt, azimuth, width, outerRadius, innerRadius );
4851 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4852 return result;
4853}
4854
4855static QVariant fcnTaperedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4856{
4857 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4858 if ( fGeom.type() != Qgis::GeometryType::Line )
4859 {
4860 parent->setEvalErrorString( QObject::tr( "Function `tapered_buffer` requires a line geometry." ) );
4861 return QVariant();
4862 }
4863
4864 double startWidth = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4865 double endWidth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4866 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) );
4867
4868 QgsGeometry geom = fGeom.taperedBuffer( startWidth, endWidth, segments );
4869 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4870 return result;
4871}
4872
4873static QVariant fcnBufferByM( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4874{
4875 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4876 if ( fGeom.type() != Qgis::GeometryType::Line )
4877 {
4878 parent->setEvalErrorString( QObject::tr( "Function `buffer_by_m` requires a line geometry." ) );
4879 return QVariant();
4880 }
4881
4882 int segments = static_cast< int >( QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) );
4883
4884 QgsGeometry geom = fGeom.variableWidthBufferByM( segments );
4885 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4886 return result;
4887}
4888
4889static QVariant fcnOffsetCurve( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4890{
4891 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4892 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4893 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4894 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4895 if ( joinInt < 1 || joinInt > 3 )
4896 return QVariant();
4897 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
4898
4899 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4900
4901 QgsGeometry geom = fGeom.offsetCurve( dist, segments, join, miterLimit );
4902 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4903 return result;
4904}
4905
4906static QVariant fcnSingleSidedBuffer( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4907{
4908 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4909 double dist = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4910 int segments = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
4911
4912 const int joinInt = QgsExpressionUtils::getIntValue( values.at( 3 ), parent );
4913 if ( joinInt < 1 || joinInt > 3 )
4914 return QVariant();
4915 const Qgis::JoinStyle join = static_cast< Qgis::JoinStyle >( joinInt );
4916
4917 double miterLimit = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
4918
4919 QgsGeometry geom = fGeom.singleSidedBuffer( dist, segments, Qgis::BufferSide::Left, join, miterLimit );
4920 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4921 return result;
4922}
4923
4924static QVariant fcnExtend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4925{
4926 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4927 double distStart = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4928 double distEnd = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4929
4930 QgsGeometry geom = fGeom.extendLine( distStart, distEnd );
4931 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
4932 return result;
4933}
4934
4935static QVariant fcnTranslate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4936{
4937 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4938 double dx = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4939 double dy = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4940 fGeom.translate( dx, dy );
4941 return QVariant::fromValue( fGeom );
4942}
4943
4944static QVariant fcnRotate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4945{
4946 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4947 const double rotation = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4948 const QgsGeometry center = values.at( 2 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 2 ), parent )
4949 : QgsGeometry();
4950 const bool perPart = values.value( 3 ).toBool();
4951
4952 if ( center.isNull() && perPart && fGeom.isMultipart() )
4953 {
4954 // no explicit center, rotating per part
4955 // (note that we only do this branch for multipart geometries -- for singlepart geometries
4956 // the result is equivalent to setting perPart as false anyway)
4957 std::unique_ptr< QgsGeometryCollection > collection( qgsgeometry_cast< QgsGeometryCollection * >( fGeom.constGet()->clone() ) );
4958 for ( auto it = collection->parts_begin(); it != collection->parts_end(); ++it )
4959 {
4960 const QgsPointXY partCenter = ( *it )->boundingBox().center();
4961 QTransform t = QTransform::fromTranslate( partCenter.x(), partCenter.y() );
4962 t.rotate( -rotation );
4963 t.translate( -partCenter.x(), -partCenter.y() );
4964 ( *it )->transform( t );
4965 }
4966 return QVariant::fromValue( QgsGeometry( std::move( collection ) ) );
4967 }
4968 else
4969 {
4970 QgsPointXY pt;
4971 if ( center.isEmpty() )
4972 {
4973 // if center wasn't specified, use bounding box centroid
4974 pt = fGeom.boundingBox().center();
4975 }
4977 {
4978 parent->setEvalErrorString( QObject::tr( "Function 'rotate' requires a point value for the center" ) );
4979 return QVariant();
4980 }
4981 else
4982 {
4983 pt = QgsPointXY( *qgsgeometry_cast< const QgsPoint * >( center.constGet()->simplifiedTypeRef() ) );
4984 }
4985
4986 fGeom.rotate( rotation, pt );
4987 return QVariant::fromValue( fGeom );
4988 }
4989}
4990
4991static QVariant fcnScale( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
4992{
4993 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
4994 const double xScale = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
4995 const double yScale = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
4996 const QgsGeometry center = values.at( 3 ).isValid() ? QgsExpressionUtils::getGeometry( values.at( 3 ), parent )
4997 : QgsGeometry();
4998
4999 QgsPointXY pt;
5000 if ( center.isNull() )
5001 {
5002 // if center wasn't specified, use bounding box centroid
5003 pt = fGeom.boundingBox().center();
5004 }
5006 {
5007 parent->setEvalErrorString( QObject::tr( "Function 'scale' requires a point value for the center" ) );
5008 return QVariant();
5009 }
5010 else
5011 {
5012 pt = center.asPoint();
5013 }
5014
5015 QTransform t = QTransform::fromTranslate( pt.x(), pt.y() );
5016 t.scale( xScale, yScale );
5017 t.translate( -pt.x(), -pt.y() );
5018 fGeom.transform( t );
5019 return QVariant::fromValue( fGeom );
5020}
5021
5022static QVariant fcnAffineTransform( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5023{
5024 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5025 if ( fGeom.isNull() )
5026 {
5027 return QVariant();
5028 }
5029
5030 const double deltaX = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5031 const double deltaY = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5032
5033 const double rotationZ = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5034
5035 const double scaleX = QgsExpressionUtils::getDoubleValue( values.at( 4 ), parent );
5036 const double scaleY = QgsExpressionUtils::getDoubleValue( values.at( 5 ), parent );
5037
5038 const double deltaZ = QgsExpressionUtils::getDoubleValue( values.at( 6 ), parent );
5039 const double deltaM = QgsExpressionUtils::getDoubleValue( values.at( 7 ), parent );
5040 const double scaleZ = QgsExpressionUtils::getDoubleValue( values.at( 8 ), parent );
5041 const double scaleM = QgsExpressionUtils::getDoubleValue( values.at( 9 ), parent );
5042
5043 if ( deltaZ != 0.0 && !fGeom.constGet()->is3D() )
5044 {
5045 fGeom.get()->addZValue( 0 );
5046 }
5047 if ( deltaM != 0.0 && !fGeom.constGet()->isMeasure() )
5048 {
5049 fGeom.get()->addMValue( 0 );
5050 }
5051
5052 QTransform transform;
5053 transform.translate( deltaX, deltaY );
5054 transform.rotate( rotationZ );
5055 transform.scale( scaleX, scaleY );
5056 fGeom.transform( transform, deltaZ, scaleZ, deltaM, scaleM );
5057
5058 return QVariant::fromValue( fGeom );
5059}
5060
5061
5062static QVariant fcnCentroid( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5063{
5064 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5065 QgsGeometry geom = fGeom.centroid();
5066 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5067 return result;
5068}
5069static QVariant fcnPointOnSurface( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5070{
5071 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5072 QgsGeometry geom = fGeom.pointOnSurface();
5073 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5074 return result;
5075}
5076
5077static QVariant fcnPoleOfInaccessibility( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5078{
5079 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5080 double tolerance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5081 QgsGeometry geom = fGeom.poleOfInaccessibility( tolerance );
5082 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5083 return result;
5084}
5085
5086static QVariant fcnConvexHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5087{
5088 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5089 QgsGeometry geom = fGeom.convexHull();
5090 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5091 return result;
5092}
5093
5094#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
5095static QVariant fcnConcaveHull( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5096{
5097 try
5098 {
5099 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5100 const double targetPercent = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5101 const bool allowHoles = values.value( 2 ).toBool();
5102 QgsGeometry geom = fGeom.concaveHull( targetPercent, allowHoles );
5103 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5104 return result;
5105 }
5106 catch ( QgsCsException &cse )
5107 {
5108 QgsMessageLog::logMessage( QObject::tr( "Error caught in concave_hull() function: %1" ).arg( cse.what() ) );
5109 return QVariant();
5110 }
5111}
5112#endif
5113
5114static QVariant fcnMinimalCircle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5115{
5116 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5117 int segments = 36;
5118 if ( values.length() == 2 )
5119 segments = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5120 if ( segments < 0 )
5121 {
5122 parent->setEvalErrorString( QObject::tr( "Parameter can not be negative." ) );
5123 return QVariant();
5124 }
5125
5126 QgsGeometry geom = fGeom.minimalEnclosingCircle( static_cast<unsigned int>( segments ) );
5127 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5128 return result;
5129}
5130
5131static QVariant fcnOrientedBBox( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5132{
5133 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5135 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5136 return result;
5137}
5138
5139static QVariant fcnMainAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5140{
5141 const QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5142
5143 // we use the angle of the oriented minimum bounding box to calculate the polygon main angle.
5144 // While ArcGIS uses a different approach ("the angle of longest collection of segments that have similar orientation"), this
5145 // yields similar results to OMBB approach under the same constraints ("this tool is meant for primarily orthogonal polygons rather than organically shaped ones.")
5146
5147 double area, angle, width, height;
5148 const QgsGeometry geom = fGeom.orientedMinimumBoundingBox( area, angle, width, height );
5149
5150 if ( geom.isNull() )
5151 {
5152 parent->setEvalErrorString( QObject::tr( "Error calculating polygon main angle: %1" ).arg( geom.lastError() ) );
5153 return QVariant();
5154 }
5155 return angle;
5156}
5157
5158static QVariant fcnDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5159{
5160 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5161 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5162 QgsGeometry geom = fGeom.difference( sGeom );
5163 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5164 return result;
5165}
5166
5167static QVariant fcnReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5168{
5169 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5170 if ( fGeom.isNull() )
5171 return QVariant();
5172
5173 QVariant result;
5174 if ( !fGeom.isMultipart() )
5175 {
5176 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( fGeom.constGet() );
5177 if ( !curve )
5178 return QVariant();
5179
5180 QgsCurve *reversed = curve->reversed();
5181 result = reversed ? QVariant::fromValue( QgsGeometry( reversed ) ) : QVariant();
5182 }
5183 else
5184 {
5185 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection *>( fGeom.constGet() );
5186 std::unique_ptr< QgsGeometryCollection > reversed( collection->createEmptyWithSameType() );
5187 for ( int i = 0; i < collection->numGeometries(); ++i )
5188 {
5189 if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve * >( collection->geometryN( i ) ) )
5190 {
5191 reversed->addGeometry( curve->reversed() );
5192 }
5193 else
5194 {
5195 reversed->addGeometry( collection->geometryN( i )->clone() );
5196 }
5197 }
5198 result = reversed ? QVariant::fromValue( QgsGeometry( std::move( reversed ) ) ) : QVariant();
5199 }
5200 return result;
5201}
5202
5203static QVariant fcnExteriorRing( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5204{
5205 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5206 if ( fGeom.isNull() )
5207 return QVariant();
5208
5209 const QgsCurvePolygon *curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( fGeom.constGet() );
5210 if ( !curvePolygon && fGeom.isMultipart() )
5211 {
5212 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom.constGet() ) )
5213 {
5214 if ( collection->numGeometries() == 1 )
5215 {
5216 curvePolygon = qgsgeometry_cast< const QgsCurvePolygon * >( collection->geometryN( 0 ) );
5217 }
5218 }
5219 }
5220
5221 if ( !curvePolygon || !curvePolygon->exteriorRing() )
5222 return QVariant();
5223
5224 QgsCurve *exterior = static_cast< QgsCurve * >( curvePolygon->exteriorRing()->clone() );
5225 QVariant result = exterior ? QVariant::fromValue( QgsGeometry( exterior ) ) : QVariant();
5226 return result;
5227}
5228
5229static QVariant fcnDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5230{
5231 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5232 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5233 return QVariant( fGeom.distance( sGeom ) );
5234}
5235
5236static QVariant fcnHausdorffDistance( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5237{
5238 QgsGeometry g1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5239 QgsGeometry g2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5240
5241 double res = -1;
5242 if ( values.length() == 3 && values.at( 2 ).isValid() )
5243 {
5244 double densify = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5245 densify = std::clamp( densify, 0.0, 1.0 );
5246 res = g1.hausdorffDistanceDensify( g2, densify );
5247 }
5248 else
5249 {
5250 res = g1.hausdorffDistance( g2 );
5251 }
5252
5253 return res > -1 ? QVariant( res ) : QVariant();
5254}
5255
5256static QVariant fcnIntersection( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5257{
5258 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5259 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5260 QgsGeometry geom = fGeom.intersection( sGeom );
5261 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5262 return result;
5263}
5264static QVariant fcnSymDifference( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5265{
5266 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5267 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5268 QgsGeometry geom = fGeom.symDifference( sGeom );
5269 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5270 return result;
5271}
5272static QVariant fcnCombine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5273{
5274 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5275 QgsGeometry sGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5276 QgsGeometry geom = fGeom.combine( sGeom );
5277 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5278 return result;
5279}
5280
5281static QVariant fcnGeomToWKT( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5282{
5283 if ( values.length() < 1 || values.length() > 2 )
5284 return QVariant();
5285
5286 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5287 int prec = 8;
5288 if ( values.length() == 2 )
5289 prec = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5290 QString wkt = fGeom.asWkt( prec );
5291 return QVariant( wkt );
5292}
5293
5294static QVariant fcnGeomToWKB( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5295{
5296 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5297 return fGeom.isNull() ? QVariant() : QVariant( fGeom.asWkb() );
5298}
5299
5300static QVariant fcnAzimuth( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5301{
5302 if ( values.length() != 2 )
5303 {
5304 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires exactly two parameters. %n given.", nullptr, values.length() ) );
5305 return QVariant();
5306 }
5307
5308 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5309 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5310
5311 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5312 if ( !pt1 && fGeom1.isMultipart() )
5313 {
5314 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5315 {
5316 if ( collection->numGeometries() == 1 )
5317 {
5318 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5319 }
5320 }
5321 }
5322
5323 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5324 if ( !pt2 && fGeom2.isMultipart() )
5325 {
5326 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5327 {
5328 if ( collection->numGeometries() == 1 )
5329 {
5330 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5331 }
5332 }
5333 }
5334
5335 if ( !pt1 || !pt2 )
5336 {
5337 parent->setEvalErrorString( QObject::tr( "Function `azimuth` requires two points as arguments." ) );
5338 return QVariant();
5339 }
5340
5341 // Code from PostGIS
5342 if ( qgsDoubleNear( pt1->x(), pt2->x() ) )
5343 {
5344 if ( pt1->y() < pt2->y() )
5345 return 0.0;
5346 else if ( pt1->y() > pt2->y() )
5347 return M_PI;
5348 else
5349 return 0;
5350 }
5351
5352 if ( qgsDoubleNear( pt1->y(), pt2->y() ) )
5353 {
5354 if ( pt1->x() < pt2->x() )
5355 return M_PI_2;
5356 else if ( pt1->x() > pt2->x() )
5357 return M_PI + ( M_PI_2 );
5358 else
5359 return 0;
5360 }
5361
5362 if ( pt1->x() < pt2->x() )
5363 {
5364 if ( pt1->y() < pt2->y() )
5365 {
5366 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) );
5367 }
5368 else /* ( pt1->y() > pt2->y() ) - equality case handled above */
5369 {
5370 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5371 + ( M_PI_2 );
5372 }
5373 }
5374
5375 else /* ( pt1->x() > pt2->x() ) - equality case handled above */
5376 {
5377 if ( pt1->y() > pt2->y() )
5378 {
5379 return std::atan( std::fabs( pt1->x() - pt2->x() ) / std::fabs( pt1->y() - pt2->y() ) )
5380 + M_PI;
5381 }
5382 else /* ( pt1->y() < pt2->y() ) - equality case handled above */
5383 {
5384 return std::atan( std::fabs( pt1->y() - pt2->y() ) / std::fabs( pt1->x() - pt2->x() ) )
5385 + ( M_PI + ( M_PI_2 ) );
5386 }
5387 }
5388}
5389
5390static QVariant fcnProject( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5391{
5392 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5393
5395 {
5396 parent->setEvalErrorString( QStringLiteral( "'project' requires a point geometry" ) );
5397 return QVariant();
5398 }
5399
5400 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5401 double azimuth = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5402 double inclination = QgsExpressionUtils::getDoubleValue( values.at( 3 ), parent );
5403
5404 const QgsPoint *p = static_cast<const QgsPoint *>( geom.constGet()->simplifiedTypeRef( ) );
5405 QgsPoint newPoint = p->project( distance, 180.0 * azimuth / M_PI, 180.0 * inclination / M_PI );
5406
5407 return QVariant::fromValue( QgsGeometry( new QgsPoint( newPoint ) ) );
5408}
5409
5410static QVariant fcnInclination( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5411{
5412 QgsGeometry fGeom1 = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5413 QgsGeometry fGeom2 = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5414
5415 const QgsPoint *pt1 = qgsgeometry_cast<const QgsPoint *>( fGeom1.constGet() );
5416 if ( !pt1 && fGeom1.isMultipart() )
5417 {
5418 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom1.constGet() ) )
5419 {
5420 if ( collection->numGeometries() == 1 )
5421 {
5422 pt1 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5423 }
5424 }
5425 }
5426 const QgsPoint *pt2 = qgsgeometry_cast<const QgsPoint *>( fGeom2.constGet() );
5427 if ( !pt2 && fGeom2.isMultipart() )
5428 {
5429 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( fGeom2.constGet() ) )
5430 {
5431 if ( collection->numGeometries() == 1 )
5432 {
5433 pt2 = qgsgeometry_cast< const QgsPoint * >( collection->geometryN( 0 ) );
5434 }
5435 }
5436 }
5437
5438 if ( ( fGeom1.type() != Qgis::GeometryType::Point ) || ( fGeom2.type() != Qgis::GeometryType::Point ) ||
5439 !pt1 || !pt2 )
5440 {
5441 parent->setEvalErrorString( QStringLiteral( "Function 'inclination' requires two points as arguments." ) );
5442 return QVariant();
5443 }
5444
5445 return pt1->inclination( *pt2 );
5446
5447}
5448
5449static QVariant fcnExtrude( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5450{
5451 if ( values.length() != 3 )
5452 return QVariant();
5453
5454 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5455 double x = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5456 double y = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5457
5458 QgsGeometry geom = fGeom.extrude( x, y );
5459
5460 QVariant result = geom.constGet() ? QVariant::fromValue( geom ) : QVariant();
5461 return result;
5462}
5463
5464static QVariant fcnOrderParts( const QVariantList &values, const QgsExpressionContext *ctx, QgsExpression *parent, const QgsExpressionNodeFunction * )
5465{
5466 if ( values.length() < 2 )
5467 return QVariant();
5468
5469 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5470
5471 if ( !fGeom.isMultipart() )
5472 return values.at( 0 );
5473
5474 QString expString = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5475 QVariant cachedExpression;
5476 if ( ctx )
5477 cachedExpression = ctx->cachedValue( expString );
5478 QgsExpression expression;
5479
5480 if ( cachedExpression.isValid() )
5481 {
5482 expression = cachedExpression.value<QgsExpression>();
5483 }
5484 else
5485 expression = QgsExpression( expString );
5486
5487 bool asc = values.value( 2 ).toBool();
5488
5489 QgsExpressionContext *unconstedContext = nullptr;
5490 QgsFeature f;
5491 if ( ctx )
5492 {
5493 // ExpressionSorter wants a modifiable expression context, but it will return it in the same shape after
5494 // so no reason to worry
5495 unconstedContext = const_cast<QgsExpressionContext *>( ctx );
5496 f = ctx->feature();
5497 }
5498 else
5499 {
5500 // If there's no context provided, create a fake one
5501 unconstedContext = new QgsExpressionContext();
5502 }
5503
5504 const QgsGeometryCollection *collection = qgsgeometry_cast<const QgsGeometryCollection *>( fGeom.constGet() );
5505 Q_ASSERT( collection ); // Should have failed the multipart check above
5506
5508 orderBy.append( QgsFeatureRequest::OrderByClause( expression, asc ) );
5509 QgsExpressionSorter sorter( orderBy );
5510
5511 QList<QgsFeature> partFeatures;
5512 partFeatures.reserve( collection->partCount() );
5513 for ( int i = 0; i < collection->partCount(); ++i )
5514 {
5515 f.setGeometry( QgsGeometry( collection->geometryN( i )->clone() ) );
5516 partFeatures << f;
5517 }
5518
5519 sorter.sortFeatures( partFeatures, unconstedContext );
5520
5521 QgsGeometryCollection *orderedGeom = qgsgeometry_cast<QgsGeometryCollection *>( fGeom.constGet()->clone() );
5522
5523 Q_ASSERT( orderedGeom );
5524
5525 while ( orderedGeom->partCount() )
5526 orderedGeom->removeGeometry( 0 );
5527
5528 for ( const QgsFeature &feature : std::as_const( partFeatures ) )
5529 {
5530 orderedGeom->addGeometry( feature.geometry().constGet()->clone() );
5531 }
5532
5533 QVariant result = QVariant::fromValue( QgsGeometry( orderedGeom ) );
5534
5535 if ( !ctx )
5536 delete unconstedContext;
5537
5538 return result;
5539}
5540
5541static QVariant fcnClosestPoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5542{
5543 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5544 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5545
5546 QgsGeometry geom = fromGeom.nearestPoint( toGeom );
5547
5548 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5549 return result;
5550}
5551
5552static QVariant fcnShortestLine( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5553{
5554 QgsGeometry fromGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5555 QgsGeometry toGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5556
5557 QgsGeometry geom = fromGeom.shortestLine( toGeom );
5558
5559 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5560 return result;
5561}
5562
5563static QVariant fcnLineInterpolatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5564{
5565 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5566 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5567
5568 QgsGeometry geom = lineGeom.interpolate( distance );
5569
5570 QVariant result = !geom.isNull() ? QVariant::fromValue( geom ) : QVariant();
5571 return result;
5572}
5573
5574static QVariant fcnLineSubset( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5575{
5576 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5577 if ( lineGeom.type() != Qgis::GeometryType::Line )
5578 {
5579 parent->setEvalErrorString( QObject::tr( "line_substring requires a curve geometry input" ) );
5580 return QVariant();
5581 }
5582
5583 const QgsCurve *curve = nullptr;
5584 if ( !lineGeom.isMultipart() )
5585 curve = qgsgeometry_cast< const QgsCurve * >( lineGeom.constGet() );
5586 else
5587 {
5588 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( lineGeom.constGet() ) )
5589 {
5590 if ( collection->numGeometries() > 0 )
5591 {
5592 curve = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( 0 ) );
5593 }
5594 }
5595 }
5596 if ( !curve )
5597 return QVariant();
5598
5599 double startDistance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5600 double endDistance = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5601
5602 std::unique_ptr< QgsCurve > substring( curve->curveSubstring( startDistance, endDistance ) );
5603 QgsGeometry result( std::move( substring ) );
5604 return !result.isNull() ? QVariant::fromValue( result ) : QVariant();
5605}
5606
5607static QVariant fcnLineInterpolateAngle( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5608{
5609 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5610 double distance = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5611
5612 return lineGeom.interpolateAngle( distance ) * 180.0 / M_PI;
5613}
5614
5615static QVariant fcnAngleAtVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5616{
5617 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5618 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5619 if ( vertex < 0 )
5620 {
5621 //negative idx
5622 int count = geom.constGet()->nCoordinates();
5623 vertex = count + vertex;
5624 }
5625
5626 return geom.angleAtVertex( vertex ) * 180.0 / M_PI;
5627}
5628
5629static QVariant fcnDistanceToVertex( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5630{
5631 QgsGeometry geom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5632 int vertex = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5633 if ( vertex < 0 )
5634 {
5635 //negative idx
5636 int count = geom.constGet()->nCoordinates();
5637 vertex = count + vertex;
5638 }
5639
5640 return geom.distanceToVertex( vertex );
5641}
5642
5643static QVariant fcnLineLocatePoint( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5644{
5645 QgsGeometry lineGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
5646 QgsGeometry pointGeom = QgsExpressionUtils::getGeometry( values.at( 1 ), parent );
5647
5648 double distance = lineGeom.lineLocatePoint( pointGeom );
5649
5650 return distance >= 0 ? distance : QVariant();
5651}
5652
5653static QVariant fcnRound( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5654{
5655 if ( values.length() == 2 && values.at( 1 ).toInt() != 0 )
5656 {
5657 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5658 return qgsRound( number, QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
5659 }
5660
5661 if ( values.length() >= 1 )
5662 {
5663 double number = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5664 return QVariant( qlonglong( std::round( number ) ) );
5665 }
5666
5667 return QVariant();
5668}
5669
5670static QVariant fcnPi( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5671{
5672 Q_UNUSED( values )
5673 Q_UNUSED( parent )
5674 return M_PI;
5675}
5676
5677static QVariant fcnFormatNumber( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5678{
5679 const double value = QgsExpressionUtils::getDoubleValue( values.at( 0 ), parent );
5680 const int places = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5681 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5682 if ( places < 0 )
5683 {
5684 parent->setEvalErrorString( QObject::tr( "Number of places must be positive" ) );
5685 return QVariant();
5686 }
5687
5688 const bool omitGroupSeparator = values.value( 3 ).toBool();
5689 const bool trimTrailingZeros = values.value( 4 ).toBool();
5690
5691 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5692 if ( !omitGroupSeparator )
5693 locale.setNumberOptions( locale.numberOptions() & ~QLocale::NumberOption::OmitGroupSeparator );
5694 else
5695 locale.setNumberOptions( locale.numberOptions() | QLocale::NumberOption::OmitGroupSeparator );
5696
5697 QString res = locale.toString( value, 'f', places );
5698
5699 if ( trimTrailingZeros )
5700 {
5701#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
5702 const QChar decimal = locale.decimalPoint();
5703 const QChar zeroDigit = locale.zeroDigit();
5704#else
5705 const QChar decimal = locale.decimalPoint().at( 0 );
5706 const QChar zeroDigit = locale.zeroDigit().at( 0 );
5707#endif
5708
5709 if ( res.contains( decimal ) )
5710 {
5711 int trimPoint = res.length() - 1;
5712
5713 while ( res.at( trimPoint ) == zeroDigit )
5714 trimPoint--;
5715
5716 if ( res.at( trimPoint ) == decimal )
5717 trimPoint--;
5718
5719 res.truncate( trimPoint + 1 );
5720 }
5721 }
5722
5723 return res;
5724}
5725
5726static QVariant fcnFormatDate( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5727{
5728 const QDateTime datetime = QgsExpressionUtils::getDateTimeValue( values.at( 0 ), parent );
5729 const QString format = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5730 const QString language = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
5731
5732 QLocale locale = !language.isEmpty() ? QLocale( language ) : QLocale();
5733 return locale.toString( datetime, format );
5734}
5735
5736static QVariant fcnColorGrayscaleAverage( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
5737{
5738 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5739 int avg = ( color.red() + color.green() + color.blue() ) / 3;
5740 int alpha = color.alpha();
5741
5742 color.setRgb( avg, avg, avg, alpha );
5743
5744 return QgsSymbolLayerUtils::encodeColor( color );
5745}
5746
5747static QVariant fcnColorMixRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5748{
5749 QColor color1 = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5750 QColor color2 = QgsSymbolLayerUtils::decodeColor( values.at( 1 ).toString() );
5751 double ratio = QgsExpressionUtils::getDoubleValue( values.at( 2 ), parent );
5752 if ( ratio > 1 )
5753 {
5754 ratio = 1;
5755 }
5756 else if ( ratio < 0 )
5757 {
5758 ratio = 0;
5759 }
5760
5761 int red = static_cast<int>( color1.red() * ( 1 - ratio ) + color2.red() * ratio );
5762 int green = static_cast<int>( color1.green() * ( 1 - ratio ) + color2.green() * ratio );
5763 int blue = static_cast<int>( color1.blue() * ( 1 - ratio ) + color2.blue() * ratio );
5764 int alpha = static_cast<int>( color1.alpha() * ( 1 - ratio ) + color2.alpha() * ratio );
5765
5766 QColor newColor( red, green, blue, alpha );
5767
5768 return QgsSymbolLayerUtils::encodeColor( newColor );
5769}
5770
5771static QVariant fcnColorRgb( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5772{
5773 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
5774 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5775 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
5776 QColor color = QColor( red, green, blue );
5777 if ( ! color.isValid() )
5778 {
5779 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( red ).arg( green ).arg( blue ) );
5780 color = QColor( 0, 0, 0 );
5781 }
5782
5783 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5784}
5785
5786static QVariant fcnTry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5787{
5788 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
5789 QVariant value = node->eval( parent, context );
5790 if ( parent->hasEvalError() )
5791 {
5792 parent->setEvalErrorString( QString() );
5793 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
5795 value = node->eval( parent, context );
5797 }
5798 return value;
5799}
5800
5801static QVariant fcnIf( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
5802{
5803 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
5805 QVariant value = node->eval( parent, context );
5807 if ( value.toBool() )
5808 {
5809 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
5811 value = node->eval( parent, context );
5813 }
5814 else
5815 {
5816 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
5818 value = node->eval( parent, context );
5820 }
5821 return value;
5822}
5823
5824static QVariant fncColorRgba( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5825{
5826 int red = QgsExpressionUtils::getNativeIntValue( values.at( 0 ), parent );
5827 int green = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
5828 int blue = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
5829 int alpha = QgsExpressionUtils::getNativeIntValue( values.at( 3 ), parent );
5830 QColor color = QColor( red, green, blue, alpha );
5831 if ( ! color.isValid() )
5832 {
5833 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) );
5834 color = QColor( 0, 0, 0 );
5835 }
5836 return QgsSymbolLayerUtils::encodeColor( color );
5837}
5838
5839QVariant fcnRampColor( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5840{
5841 QgsGradientColorRamp expRamp;
5842 const QgsColorRamp *ramp = nullptr;
5843 if ( values.at( 0 ).userType() == QMetaType::type( "QgsGradientColorRamp" ) )
5844 {
5845 expRamp = QgsExpressionUtils::getRamp( values.at( 0 ), parent );
5846 ramp = &expRamp;
5847 }
5848 else
5849 {
5850 QString rampName = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
5851 ramp = QgsStyle::defaultStyle()->colorRampRef( rampName );
5852 if ( ! ramp )
5853 {
5854 parent->setEvalErrorString( QObject::tr( "\"%1\" is not a valid color ramp" ).arg( rampName ) );
5855 return QVariant();
5856 }
5857 }
5858
5859 double value = QgsExpressionUtils::getDoubleValue( values.at( 1 ), parent );
5860 QColor color = ramp->color( value );
5861 return QgsSymbolLayerUtils::encodeColor( color );
5862}
5863
5864static QVariant fcnColorHsl( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5865{
5866 // Hue ranges from 0 - 360
5867 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5868 // Saturation ranges from 0 - 100
5869 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5870 // Lightness ranges from 0 - 100
5871 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5872
5873 QColor color = QColor::fromHslF( hue, saturation, lightness );
5874
5875 if ( ! color.isValid() )
5876 {
5877 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( lightness ) );
5878 color = QColor( 0, 0, 0 );
5879 }
5880
5881 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5882}
5883
5884static QVariant fncColorHsla( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5885{
5886 // Hue ranges from 0 - 360
5887 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5888 // Saturation ranges from 0 - 100
5889 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5890 // Lightness ranges from 0 - 100
5891 double lightness = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5892 // Alpha ranges from 0 - 255
5893 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
5894
5895 QColor color = QColor::fromHslF( hue, saturation, lightness, alpha );
5896 if ( ! color.isValid() )
5897 {
5898 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( lightness ).arg( alpha ) );
5899 color = QColor( 0, 0, 0 );
5900 }
5901 return QgsSymbolLayerUtils::encodeColor( color );
5902}
5903
5904static QVariant fcnColorHsv( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5905{
5906 // Hue ranges from 0 - 360
5907 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5908 // Saturation ranges from 0 - 100
5909 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5910 // Value ranges from 0 - 100
5911 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5912
5913 QColor color = QColor::fromHsvF( hue, saturation, value );
5914
5915 if ( ! color.isValid() )
5916 {
5917 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3' to color" ).arg( hue ).arg( saturation ).arg( value ) );
5918 color = QColor( 0, 0, 0 );
5919 }
5920
5921 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5922}
5923
5924static QVariant fncColorHsva( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5925{
5926 // Hue ranges from 0 - 360
5927 double hue = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 360.0;
5928 // Saturation ranges from 0 - 100
5929 double saturation = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5930 // Value ranges from 0 - 100
5931 double value = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5932 // Alpha ranges from 0 - 255
5933 double alpha = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 255.0;
5934
5935 QColor color = QColor::fromHsvF( hue, saturation, value, alpha );
5936 if ( ! color.isValid() )
5937 {
5938 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( hue ).arg( saturation ).arg( value ).arg( alpha ) );
5939 color = QColor( 0, 0, 0 );
5940 }
5941 return QgsSymbolLayerUtils::encodeColor( color );
5942}
5943
5944static QVariant fcnColorCmyk( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5945{
5946 // Cyan ranges from 0 - 100
5947 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
5948 // Magenta ranges from 0 - 100
5949 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5950 // Yellow ranges from 0 - 100
5951 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5952 // Black ranges from 0 - 100
5953 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
5954
5955 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black );
5956
5957 if ( ! color.isValid() )
5958 {
5959 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ) );
5960 color = QColor( 0, 0, 0 );
5961 }
5962
5963 return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() );
5964}
5965
5966static QVariant fncColorCmyka( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5967{
5968 // Cyan ranges from 0 - 100
5969 double cyan = QgsExpressionUtils::getIntValue( values.at( 0 ), parent ) / 100.0;
5970 // Magenta ranges from 0 - 100
5971 double magenta = QgsExpressionUtils::getIntValue( values.at( 1 ), parent ) / 100.0;
5972 // Yellow ranges from 0 - 100
5973 double yellow = QgsExpressionUtils::getIntValue( values.at( 2 ), parent ) / 100.0;
5974 // Black ranges from 0 - 100
5975 double black = QgsExpressionUtils::getIntValue( values.at( 3 ), parent ) / 100.0;
5976 // Alpha ranges from 0 - 255
5977 double alpha = QgsExpressionUtils::getIntValue( values.at( 4 ), parent ) / 255.0;
5978
5979 QColor color = QColor::fromCmykF( cyan, magenta, yellow, black, alpha );
5980 if ( ! color.isValid() )
5981 {
5982 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1:%2:%3:%4:%5' to color" ).arg( cyan ).arg( magenta ).arg( yellow ).arg( black ).arg( alpha ) );
5983 color = QColor( 0, 0, 0 );
5984 }
5985 return QgsSymbolLayerUtils::encodeColor( color );
5986}
5987
5988static QVariant fncColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
5989{
5990 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
5991 if ( ! color.isValid() )
5992 {
5993 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
5994 return QVariant();
5995 }
5996
5997 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
5998 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
5999 return color.red();
6000 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6001 return color.green();
6002 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6003 return color.blue();
6004 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6005 return color.alpha();
6006 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6007 return static_cast< double >( color.hsvHueF() * 360 );
6008 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6009 return static_cast< double >( color.hsvSaturationF() * 100 );
6010 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6011 return static_cast< double >( color.valueF() * 100 );
6012 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6013 return static_cast< double >( color.hslHueF() * 360 );
6014 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6015 return static_cast< double >( color.hslSaturationF() * 100 );
6016 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6017 return static_cast< double >( color.lightnessF() * 100 );
6018 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6019 return static_cast< double >( color.cyanF() * 100 );
6020 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6021 return static_cast< double >( color.magentaF() * 100 );
6022 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6023 return static_cast< double >( color.yellowF() * 100 );
6024 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6025 return static_cast< double >( color.blackF() * 100 );
6026
6027 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6028 return QVariant();
6029}
6030
6031static QVariant fcnCreateRamp( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6032{
6033 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
6034 if ( map.empty() )
6035 {
6036 parent->setEvalErrorString( QObject::tr( "A minimum of two colors is required to create a ramp" ) );
6037 return QVariant();
6038 }
6039
6040 QList< QColor > colors;
6042 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
6043 {
6044 colors << QgsSymbolLayerUtils::decodeColor( it.value().toString() );
6045 if ( !colors.last().isValid() )
6046 {
6047 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( it.value().toString() ) );
6048 return QVariant();
6049 }
6050
6051 double step = it.key().toDouble();
6052 if ( it == map.constBegin() )
6053 {
6054 if ( step != 0.0 )
6055 stops << QgsGradientStop( step, colors.last() );
6056 }
6057 else if ( it == map.constEnd() )
6058 {
6059 if ( step != 1.0 )
6060 stops << QgsGradientStop( step, colors.last() );
6061 }
6062 else
6063 {
6064 stops << QgsGradientStop( step, colors.last() );
6065 }
6066 }
6067 bool discrete = values.at( 1 ).toBool();
6068
6069 if ( colors.empty() )
6070 return QVariant();
6071
6072 return QVariant::fromValue( QgsGradientColorRamp( colors.first(), colors.last(), discrete, stops ) );
6073}
6074
6075static QVariant fncSetColorPart( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6076{
6077 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6078 if ( ! color.isValid() )
6079 {
6080 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6081 return QVariant();
6082 }
6083
6084 QString part = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6085 int value = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
6086 if ( part.compare( QLatin1String( "red" ), Qt::CaseInsensitive ) == 0 )
6087 color.setRed( value );
6088 else if ( part.compare( QLatin1String( "green" ), Qt::CaseInsensitive ) == 0 )
6089 color.setGreen( value );
6090 else if ( part.compare( QLatin1String( "blue" ), Qt::CaseInsensitive ) == 0 )
6091 color.setBlue( value );
6092 else if ( part.compare( QLatin1String( "alpha" ), Qt::CaseInsensitive ) == 0 )
6093 color.setAlpha( value );
6094 else if ( part.compare( QLatin1String( "hue" ), Qt::CaseInsensitive ) == 0 )
6095 color.setHsv( value, color.hsvSaturation(), color.value(), color.alpha() );
6096 else if ( part.compare( QLatin1String( "saturation" ), Qt::CaseInsensitive ) == 0 )
6097 color.setHsvF( color.hsvHueF(), value / 100.0, color.valueF(), color.alphaF() );
6098 else if ( part.compare( QLatin1String( "value" ), Qt::CaseInsensitive ) == 0 )
6099 color.setHsvF( color.hsvHueF(), color.hsvSaturationF(), value / 100.0, color.alphaF() );
6100 else if ( part.compare( QLatin1String( "hsl_hue" ), Qt::CaseInsensitive ) == 0 )
6101 color.setHsl( value, color.hslSaturation(), color.lightness(), color.alpha() );
6102 else if ( part.compare( QLatin1String( "hsl_saturation" ), Qt::CaseInsensitive ) == 0 )
6103 color.setHslF( color.hslHueF(), value / 100.0, color.lightnessF(), color.alphaF() );
6104 else if ( part.compare( QLatin1String( "lightness" ), Qt::CaseInsensitive ) == 0 )
6105 color.setHslF( color.hslHueF(), color.hslSaturationF(), value / 100.0, color.alphaF() );
6106 else if ( part.compare( QLatin1String( "cyan" ), Qt::CaseInsensitive ) == 0 )
6107 color.setCmykF( value / 100.0, color.magentaF(), color.yellowF(), color.blackF(), color.alphaF() );
6108 else if ( part.compare( QLatin1String( "magenta" ), Qt::CaseInsensitive ) == 0 )
6109 color.setCmykF( color.cyanF(), value / 100.0, color.yellowF(), color.blackF(), color.alphaF() );
6110 else if ( part.compare( QLatin1String( "yellow" ), Qt::CaseInsensitive ) == 0 )
6111 color.setCmykF( color.cyanF(), color.magentaF(), value / 100.0, color.blackF(), color.alphaF() );
6112 else if ( part.compare( QLatin1String( "black" ), Qt::CaseInsensitive ) == 0 )
6113 color.setCmykF( color.cyanF(), color.magentaF(), color.yellowF(), value / 100.0, color.alphaF() );
6114 else
6115 {
6116 parent->setEvalErrorString( QObject::tr( "Unknown color component '%1'" ).arg( part ) );
6117 return QVariant();
6118 }
6119 return QgsSymbolLayerUtils::encodeColor( color );
6120}
6121
6122static QVariant fncDarker( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6123{
6124 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6125 if ( ! color.isValid() )
6126 {
6127 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6128 return QVariant();
6129 }
6130
6131 color = color.darker( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6132
6133 return QgsSymbolLayerUtils::encodeColor( color );
6134}
6135
6136static QVariant fncLighter( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6137{
6138 QColor color = QgsSymbolLayerUtils::decodeColor( values.at( 0 ).toString() );
6139 if ( ! color.isValid() )
6140 {
6141 parent->setEvalErrorString( QObject::tr( "Cannot convert '%1' to color" ).arg( values.at( 0 ).toString() ) );
6142 return QVariant();
6143 }
6144
6145 color = color.lighter( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ) );
6146
6147 return QgsSymbolLayerUtils::encodeColor( color );
6148}
6149
6150static QVariant fcnGetGeometry( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6151{
6152 QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6153 QgsGeometry geom = feat.geometry();
6154 if ( !geom.isNull() )
6155 return QVariant::fromValue( geom );
6156 return QVariant();
6157}
6158
6159static QVariant fcnGetFeatureId( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6160{
6161 const QgsFeature feat = QgsExpressionUtils::getFeature( values.at( 0 ), parent );
6162 if ( !feat.isValid() )
6163 return QVariant();
6164 return feat.id();
6165}
6166
6167static QVariant fcnTransformGeometry( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6168{
6169 QgsGeometry fGeom = QgsExpressionUtils::getGeometry( values.at( 0 ), parent );
6170 QString sAuthId = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6171 QString dAuthId = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
6172
6174 if ( ! s.isValid() )
6175 return QVariant::fromValue( fGeom );
6177 if ( ! d.isValid() )
6178 return QVariant::fromValue( fGeom );
6179
6181 if ( context )
6182 tContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
6183 QgsCoordinateTransform t( s, d, tContext );
6184 try
6185 {
6187 return QVariant::fromValue( fGeom );
6188 }
6189 catch ( QgsCsException &cse )
6190 {
6191 QgsMessageLog::logMessage( QObject::tr( "Transform error caught in transform() function: %1" ).arg( cse.what() ) );
6192 return QVariant();
6193 }
6194 return QVariant();
6195}
6196
6197
6198static QVariant fcnGetFeatureById( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6199{
6200 bool foundLayer = false;
6201 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6202
6203 //no layer found
6204 if ( !featureSource || !foundLayer )
6205 {
6206 return QVariant();
6207 }
6208
6209 const QgsFeatureId fid = QgsExpressionUtils::getIntValue( values.at( 1 ), parent );
6210
6212 req.setFilterFid( fid );
6213 req.setTimeout( 10000 );
6214 req.setRequestMayBeNested( true );
6215 if ( context )
6216 req.setFeedback( context->feedback() );
6217 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6218
6219 QgsFeature fet;
6220 QVariant result;
6221 if ( fIt.nextFeature( fet ) )
6222 result = QVariant::fromValue( fet );
6223
6224 return result;
6225}
6226
6227static QVariant fcnGetFeature( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6228{
6229 //arguments: 1. layer id / name, 2. key attribute, 3. eq value
6230 bool foundLayer = false;
6231 std::unique_ptr<QgsVectorLayerFeatureSource> featureSource = QgsExpressionUtils::getFeatureSource( values.at( 0 ), context, parent, foundLayer );
6232
6233 //no layer found
6234 if ( !featureSource || !foundLayer )
6235 {
6236 return QVariant();
6237 }
6239 QString cacheValueKey;
6240 if ( values.at( 1 ).type() == QVariant::Map )
6241 {
6242 QVariantMap attributeMap = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
6243
6244 QMap <QString, QVariant>::const_iterator i = attributeMap.constBegin();
6245 QString filterString;
6246 for ( ; i != attributeMap.constEnd(); ++i )
6247 {
6248 if ( !filterString.isEmpty() )
6249 {
6250 filterString.append( " AND " );
6251 }
6252 filterString.append( QgsExpression::createFieldEqualityExpression( i.key(), i.value() ) );
6253 }
6254 cacheValueKey = QStringLiteral( "getfeature:%1:%2" ).arg( featureSource->id(), filterString );
6255 if ( context && context->hasCachedValue( cacheValueKey ) )
6256 {
6257 return context->cachedValue( cacheValueKey );
6258 }
6259 req.setFilterExpression( filterString );
6260 }
6261 else
6262 {
6263 QString attribute = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6264 int attributeId = featureSource->fields().lookupField( attribute );
6265 if ( attributeId == -1 )
6266 {
6267 return QVariant();
6268 }
6269
6270 const QVariant &attVal = values.at( 2 );
6271
6272 cacheValueKey = QStringLiteral( "getfeature:%1:%2:%3" ).arg( featureSource->id(), QString::number( attributeId ), attVal.toString() );
6273 if ( context && context->hasCachedValue( cacheValueKey ) )
6274 {
6275 return context->cachedValue( cacheValueKey );
6276 }
6277
6279 }
6280 req.setLimit( 1 );
6281 req.setTimeout( 10000 );
6282 req.setRequestMayBeNested( true );
6283 if ( context )
6284 req.setFeedback( context->feedback() );
6285 if ( !parent->needsGeometry() )
6286 {
6288 }
6289 QgsFeatureIterator fIt = featureSource->getFeatures( req );
6290
6291 QgsFeature fet;
6292 QVariant res;
6293 if ( fIt.nextFeature( fet ) )
6294 {
6295 res = QVariant::fromValue( fet );
6296 }
6297
6298 if ( context )
6299 context->setCachedValue( cacheValueKey, res );
6300 return res;
6301}
6302
6303static QVariant fcnRepresentValue( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6304{
6305 QVariant result;
6306 QString fieldName;
6307
6308 if ( context )
6309 {
6310 if ( !values.isEmpty() )
6311 {
6312 QgsExpressionNodeColumnRef *col = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
6313 if ( col && ( values.size() == 1 || !values.at( 1 ).isValid() ) )
6314 fieldName = col->name();
6315 else if ( values.size() == 2 )
6316 fieldName = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6317 }
6318
6319 QVariant value = values.at( 0 );
6320
6321 const QgsFields fields = context->fields();
6322 int fieldIndex = fields.lookupField( fieldName );
6323
6324 if ( fieldIndex == -1 )
6325 {
6326 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: Field not found %2" ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6327 }
6328 else
6329 {
6330 // TODO this function is NOT thread safe
6332 QgsVectorLayer *layer = QgsExpressionUtils::getVectorLayer( context->variable( QStringLiteral( "layer" ) ), context, parent );
6334
6335 const QString cacheValueKey = QStringLiteral( "repvalfcnval:%1:%2:%3" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName, value.toString() );
6336 if ( context->hasCachedValue( cacheValueKey ) )
6337 {
6338 return context->cachedValue( cacheValueKey );
6339 }
6340
6341 const QgsEditorWidgetSetup setup = fields.at( fieldIndex ).editorWidgetSetup();
6343
6344 const QString cacheKey = QStringLiteral( "repvalfcn:%1:%2" ).arg( layer ? layer->id() : QStringLiteral( "[None]" ), fieldName );
6345
6346 QVariant cache;
6347 if ( !context->hasCachedValue( cacheKey ) )
6348 {
6349 cache = formatter->createCache( layer, fieldIndex, setup.config() );
6350 context->setCachedValue( cacheKey, cache );
6351 }
6352 else
6353 cache = context->cachedValue( cacheKey );
6354
6355 result = formatter->representValue( layer, fieldIndex, setup.config(), cache, value );
6356
6357 context->setCachedValue( cacheValueKey, result );
6358 }
6359 }
6360 else
6361 {
6362 parent->setEvalErrorString( QCoreApplication::translate( "expression", "%1: function cannot be evaluated without a context." ).arg( QStringLiteral( "represent_value" ), fieldName ) );
6363 }
6364
6365 return result;
6366}
6367
6368static QVariant fcnMimeType( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6369{
6370 const QVariant data = values.at( 0 );
6371 const QMimeDatabase db;
6372 return db.mimeTypeForData( data.toByteArray() ).name();
6373}
6374
6375static QVariant fcnGetLayerProperty( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6376{
6377 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
6378
6379 bool foundLayer = false;
6380 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [layerProperty]( QgsMapLayer * layer )-> QVariant
6381 {
6382 if ( !layer )
6383 return QVariant();
6384
6385 // here, we always prefer the layer metadata values over the older server-specific published values
6386 if ( QString::compare( layerProperty, QStringLiteral( "name" ), Qt::CaseInsensitive ) == 0 )
6387 return layer->name();
6388 else if ( QString::compare( layerProperty, QStringLiteral( "id" ), Qt::CaseInsensitive ) == 0 )
6389 return layer->id();
6390 else if ( QString::compare( layerProperty, QStringLiteral( "title" ), Qt::CaseInsensitive ) == 0 )
6391 return !layer->metadata().title().isEmpty() ? layer->metadata().title() : layer->title();
6392 else if ( QString::compare( layerProperty, QStringLiteral( "abstract" ), Qt::CaseInsensitive ) == 0 )
6393 return !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->abstract();
6394 else if ( QString::compare( layerProperty, QStringLiteral( "keywords" ), Qt::CaseInsensitive ) == 0 )
6395 {
6396 QStringList keywords;
6397 const QgsAbstractMetadataBase::KeywordMap keywordMap = layer->metadata().keywords();
6398 for ( auto it = keywordMap.constBegin(); it != keywordMap.constEnd(); ++it )
6399 {
6400 keywords.append( it.value() );
6401 }
6402 if ( !keywords.isEmpty() )
6403 return keywords;
6404 return layer->keywordList();
6405 }
6406 else if ( QString::compare( layerProperty, QStringLiteral( "data_url" ), Qt::CaseInsensitive ) == 0 )
6407 return layer->dataUrl();
6408 else if ( QString::compare( layerProperty, QStringLiteral( "attribution" ), Qt::CaseInsensitive ) == 0 )
6409 {
6410 return !layer->metadata().rights().isEmpty() ? QVariant( layer->metadata().rights() ) : QVariant( layer->attribution() );
6411 }
6412 else if ( QString::compare( layerProperty, QStringLiteral( "attribution_url" ), Qt::CaseInsensitive ) == 0 )
6413 return layer->attributionUrl();
6414 else if ( QString::compare( layerProperty, QStringLiteral( "source" ), Qt::CaseInsensitive ) == 0 )
6415 return layer->publicSource();
6416 else if ( QString::compare( layerProperty, QStringLiteral( "min_scale" ), Qt::CaseInsensitive ) == 0 )
6417 return layer->minimumScale();
6418 else if ( QString::compare( layerProperty, QStringLiteral( "max_scale" ), Qt::CaseInsensitive ) == 0 )
6419 return layer->maximumScale();
6420 else if ( QString::compare( layerProperty, QStringLiteral( "is_editable" ), Qt::CaseInsensitive ) == 0 )
6421 return layer->isEditable();
6422 else if ( QString::compare( layerProperty, QStringLiteral( "crs" ), Qt::CaseInsensitive ) == 0 )
6423 return layer->crs().authid();
6424 else if ( QString::compare( layerProperty, QStringLiteral( "crs_definition" ), Qt::CaseInsensitive ) == 0 )
6425 return layer->crs().toProj();
6426 else if ( QString::compare( layerProperty, QStringLiteral( "crs_description" ), Qt::CaseInsensitive ) == 0 )
6427 return layer->crs().description();
6428 else if ( QString::compare( layerProperty, QStringLiteral( "extent" ), Qt::CaseInsensitive ) == 0 )
6429 {
6430 QgsGeometry extentGeom = QgsGeometry::fromRect( layer->extent() );
6431 QVariant result = QVariant::fromValue( extentGeom );
6432 return result;
6433 }
6434 else if ( QString::compare( layerProperty, QStringLiteral( "distance_units" ), Qt::CaseInsensitive ) == 0 )
6435 return QgsUnitTypes::encodeUnit( layer->crs().mapUnits() );
6436 else if ( QString::compare( layerProperty, QStringLiteral( "path" ), Qt::CaseInsensitive ) == 0 )
6437 {
6438 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->source() );
6439 return decodedUri.value( QStringLiteral( "path" ) );
6440 }
6441 else if ( QString::compare( layerProperty, QStringLiteral( "type" ), Qt::CaseInsensitive ) == 0 )
6442 {
6443 switch ( layer->type() )
6444 {
6445 case Qgis::LayerType::Vector:
6446 return QCoreApplication::translate( "expressions", "Vector" );
6447 case Qgis::LayerType::Raster:
6448 return QCoreApplication::translate( "expressions", "Raster" );
6449 case Qgis::LayerType::Mesh:
6450 return QCoreApplication::translate( "expressions", "Mesh" );
6451 case Qgis::LayerType::VectorTile:
6452 return QCoreApplication::translate( "expressions", "Vector Tile" );
6453 case Qgis::LayerType::Plugin:
6454 return QCoreApplication::translate( "expressions", "Plugin" );
6455 case Qgis::LayerType::Annotation:
6456 return QCoreApplication::translate( "expressions", "Annotation" );
6457 case Qgis::LayerType::PointCloud:
6458 return QCoreApplication::translate( "expressions", "Point Cloud" );
6459 case Qgis::LayerType::Group:
6460 return QCoreApplication::translate( "expressions", "Group" );
6461 }
6462 }
6463 else
6464 {
6465 //vector layer methods
6466 QgsVectorLayer *vLayer = qobject_cast< QgsVectorLayer * >( layer );
6467 if ( vLayer )
6468 {
6469 if ( QString::compare( layerProperty, QStringLiteral( "storage_type" ), Qt::CaseInsensitive ) == 0 )
6470 return vLayer->storageType();
6471 else if ( QString::compare( layerProperty, QStringLiteral( "geometry_type" ), Qt::CaseInsensitive ) == 0 )
6473 else if ( QString::compare( layerProperty, QStringLiteral( "feature_count" ), Qt::CaseInsensitive ) == 0 )
6474 return QVariant::fromValue( vLayer->featureCount() );
6475 }
6476 }
6477
6478 return QVariant();
6479 }, foundLayer );
6480
6481 if ( !foundLayer )
6482 return QVariant();
6483 else
6484 return res;
6485}
6486
6487static QVariant fcnDecodeUri( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6488{
6489 const QString uriPart = values.at( 1 ).toString();
6490
6491 bool foundLayer = false;
6492
6493 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, uriPart]( QgsMapLayer * layer )-> QVariant
6494 {
6495 if ( !layer->dataProvider() )
6496 {
6497 parent->setEvalErrorString( QObject::tr( "Layer %1 has invalid data provider" ).arg( layer->name() ) );
6498 return QVariant();
6499 }
6500
6501 const QVariantMap decodedUri = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
6502
6503 if ( !uriPart.isNull() )
6504 {
6505 return decodedUri.value( uriPart );
6506 }
6507 else
6508 {
6509 return decodedUri;
6510 }
6511 }, foundLayer );
6512
6513 if ( !foundLayer )
6514 {
6515 parent->setEvalErrorString( QObject::tr( "Function `decode_uri` requires a valid layer." ) );
6516 return QVariant();
6517 }
6518 else
6519 {
6520 return res;
6521 }
6522}
6523
6524static QVariant fcnGetRasterBandStat( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
6525{
6526 const int band = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6527 const QString layerProperty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
6528
6529 bool foundLayer = false;
6530 const QVariant res = QgsExpressionUtils::runMapLayerFunctionThreadSafe( values.at( 0 ), context, parent, [parent, band, layerProperty]( QgsMapLayer * layer )-> QVariant
6531 {
6532 QgsRasterLayer *rl = qobject_cast< QgsRasterLayer * >( layer );
6533 if ( !rl )
6534 return QVariant();
6535
6536 if ( band < 1 || band > rl->bandCount() )
6537 {
6538 parent->setEvalErrorString( QObject::tr( "Invalid band number %1 for layer" ).arg( band ) );
6539 return QVariant();
6540 }
6541
6542 int stat = 0;
6543
6544 if ( QString::compare( layerProperty, QStringLiteral( "avg" ), Qt::CaseInsensitive ) == 0 )
6546 else if ( QString::compare( layerProperty, QStringLiteral( "stdev" ), Qt::CaseInsensitive ) == 0 )
6548 else if ( QString::compare( layerProperty, QStringLiteral( "min" ), Qt::CaseInsensitive ) == 0 )
6550 else if ( QString::compare( layerProperty, QStringLiteral( "max" ), Qt::CaseInsensitive ) == 0 )
6552 else if ( QString::compare( layerProperty, QStringLiteral( "range" ), Qt::CaseInsensitive ) == 0 )
6554 else if ( QString::compare( layerProperty, QStringLiteral( "sum" ), Qt::CaseInsensitive ) == 0 )
6556 else
6557 {
6558 parent->setEvalErrorString( QObject::tr( "Invalid raster statistic: '%1'" ).arg( layerProperty ) );
6559 return QVariant();
6560 }
6561
6562 QgsRasterBandStats stats = rl->dataProvider()->bandStatistics( band, stat );
6563 switch ( stat )
6564 {
6566 return stats.mean;
6568 return stats.stdDev;
6570 return stats.minimumValue;
6572 return stats.maximumValue;
6574 return stats.range;
6576 return stats.sum;
6577 }
6578 return QVariant();
6579 }, foundLayer );
6580
6581 if ( !foundLayer )
6582 {
6583#if 0 // for consistency with other functions we should raise an error here, but for compatibility with old projects we don't
6584 parent->setEvalErrorString( QObject::tr( "Function `raster_statistic` requires a valid raster layer." ) );
6585#endif
6586 return QVariant();
6587 }
6588 else
6589 {
6590 return res;
6591 }
6592}
6593
6594static QVariant fcnArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
6595{
6596 return values;
6597}
6598
6599static QVariant fcnArraySort( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6600{
6601 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6602 bool ascending = values.value( 1 ).toBool();
6603 std::sort( list.begin(), list.end(), [ascending]( QVariant a, QVariant b ) -> bool { return ( !ascending ? qgsVariantLessThan( b, a ) : qgsVariantLessThan( a, b ) ); } );
6604 return list;
6605}
6606
6607static QVariant fcnArrayLength( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6608{
6609 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).length();
6610}
6611
6612static QVariant fcnArrayContains( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6613{
6614 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).contains( values.at( 1 ) ) );
6615}
6616
6617static QVariant fcnArrayCount( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6618{
6619 return QVariant( QgsExpressionUtils::getListValue( values.at( 0 ), parent ).count( values.at( 1 ) ) );
6620}
6621
6622static QVariant fcnArrayAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6623{
6624 QVariantList listA = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6625 QVariantList listB = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
6626 int match = 0;
6627 for ( const auto &item : listB )
6628 {
6629 if ( listA.contains( item ) )
6630 match++;
6631 }
6632
6633 return QVariant( match == listB.count() );
6634}
6635
6636static QVariant fcnArrayFind( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6637{
6638 return QgsExpressionUtils::getListValue( values.at( 0 ), parent ).indexOf( values.at( 1 ) );
6639}
6640
6641static QVariant fcnArrayGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6642{
6643 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6644 const int pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6645 if ( pos < list.length() && pos >= 0 ) return list.at( pos );
6646 else if ( pos < 0 && ( list.length() + pos ) >= 0 )
6647 return list.at( list.length() + pos );
6648 return QVariant();
6649}
6650
6651static QVariant fcnArrayFirst( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6652{
6653 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6654 return list.value( 0 );
6655}
6656
6657static QVariant fcnArrayLast( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6658{
6659 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6660 return list.value( list.size() - 1 );
6661}
6662
6663static QVariant fcnArrayMinimum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6664{
6665 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6666 return list.isEmpty() ? QVariant() : *std::min_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6667}
6668
6669static QVariant fcnArrayMaximum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6670{
6671 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6672 return list.isEmpty() ? QVariant() : *std::max_element( list.constBegin(), list.constEnd(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6673}
6674
6675static QVariant fcnArrayMean( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6676{
6677 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6678 int i = 0;
6679 double total = 0.0;
6680 for ( const QVariant &item : list )
6681 {
6682 switch ( item.userType() )
6683 {
6684 case QMetaType::Int:
6685 case QMetaType::UInt:
6686 case QMetaType::LongLong:
6687 case QMetaType::ULongLong:
6688 case QMetaType::Float:
6689 case QMetaType::Double:
6690 total += item.toDouble();
6691 ++i;
6692 break;
6693 }
6694 }
6695 return i == 0 ? QVariant() : total / i;
6696}
6697
6698static QVariant fcnArrayMedian( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6699{
6700 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6701 QVariantList numbers;
6702 for ( const auto &item : list )
6703 {
6704 switch ( item.userType() )
6705 {
6706 case QMetaType::Int:
6707 case QMetaType::UInt:
6708 case QMetaType::LongLong:
6709 case QMetaType::ULongLong:
6710 case QMetaType::Float:
6711 case QMetaType::Double:
6712 numbers.append( item );
6713 break;
6714 }
6715 }
6716 std::sort( numbers.begin(), numbers.end(), []( QVariant a, QVariant b ) -> bool { return ( qgsVariantLessThan( a, b ) ); } );
6717 const int count = numbers.count();
6718 if ( count == 0 )
6719 {
6720 return QVariant();
6721 }
6722 else if ( count % 2 )
6723 {
6724 return numbers.at( count / 2 );
6725 }
6726 else
6727 {
6728 return ( numbers.at( count / 2 - 1 ).toDouble() + numbers.at( count / 2 ).toDouble() ) / 2;
6729 }
6730}
6731
6732static QVariant fcnArraySum( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6733{
6734 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6735 int i = 0;
6736 double total = 0.0;
6737 for ( const QVariant &item : list )
6738 {
6739 switch ( item.userType() )
6740 {
6741 case QMetaType::Int:
6742 case QMetaType::UInt:
6743 case QMetaType::LongLong:
6744 case QMetaType::ULongLong:
6745 case QMetaType::Float:
6746 case QMetaType::Double:
6747 total += item.toDouble();
6748 ++i;
6749 break;
6750 }
6751 }
6752 return i == 0 ? QVariant() : total;
6753}
6754
6755static QVariant convertToSameType( const QVariant &value, QVariant::Type type )
6756{
6757 QVariant result = value;
6758 result.convert( static_cast<int>( type ) );
6759 return result;
6760}
6761
6762static QVariant fcnArrayMajority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6763{
6764 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6765 QHash< QVariant, int > hash;
6766 for ( const auto &item : list )
6767 {
6768 ++hash[item];
6769 }
6770 const QList< int > occurrences = hash.values();
6771 if ( occurrences.empty() )
6772 return QVariantList();
6773
6774 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
6775
6776 const QString option = values.at( 1 ).toString();
6777 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
6778 {
6779 return convertToSameType( hash.keys( maxValue ), values.at( 0 ).type() );
6780 }
6781 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
6782 {
6783 if ( hash.isEmpty() )
6784 return QVariant();
6785
6786 return QVariant( hash.key( maxValue ) );
6787 }
6788 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
6789 {
6790 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( maxValue ), values.at( 0 ).type() ), context, parent, node );
6791 }
6792 else if ( option.compare( QLatin1String( "real_majority" ), Qt::CaseInsensitive ) == 0 )
6793 {
6794 if ( maxValue * 2 <= list.size() )
6795 return QVariant();
6796
6797 return QVariant( hash.key( maxValue ) );
6798 }
6799 else
6800 {
6801 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
6802 return QVariant();
6803 }
6804}
6805
6806static QVariant fcnArrayMinority( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
6807{
6808 const QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6809 QHash< QVariant, int > hash;
6810 for ( const auto &item : list )
6811 {
6812 ++hash[item];
6813 }
6814 const QList< int > occurrences = hash.values();
6815 if ( occurrences.empty() )
6816 return QVariantList();
6817
6818 const int minValue = *std::min_element( occurrences.constBegin(), occurrences.constEnd() );
6819
6820 const QString option = values.at( 1 ).toString();
6821 if ( option.compare( QLatin1String( "all" ), Qt::CaseInsensitive ) == 0 )
6822 {
6823 return convertToSameType( hash.keys( minValue ), values.at( 0 ).type() );
6824 }
6825 else if ( option.compare( QLatin1String( "any" ), Qt::CaseInsensitive ) == 0 )
6826 {
6827 if ( hash.isEmpty() )
6828 return QVariant();
6829
6830 return QVariant( hash.key( minValue ) );
6831 }
6832 else if ( option.compare( QLatin1String( "median" ), Qt::CaseInsensitive ) == 0 )
6833 {
6834 return fcnArrayMedian( QVariantList() << convertToSameType( hash.keys( minValue ), values.at( 0 ).type() ), context, parent, node );
6835 }
6836 else if ( option.compare( QLatin1String( "real_minority" ), Qt::CaseInsensitive ) == 0 )
6837 {
6838 if ( hash.isEmpty() )
6839 return QVariant();
6840
6841 // Remove the majority, all others are minority
6842 const int maxValue = *std::max_element( occurrences.constBegin(), occurrences.constEnd() );
6843 if ( maxValue * 2 > list.size() )
6844 hash.remove( hash.key( maxValue ) );
6845
6846 return convertToSameType( hash.keys(), values.at( 0 ).type() );
6847 }
6848 else
6849 {
6850 parent->setEvalErrorString( QObject::tr( "No such option '%1'" ).arg( option ) );
6851 return QVariant();
6852 }
6853}
6854
6855static QVariant fcnArrayAppend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6856{
6857 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6858 list.append( values.at( 1 ) );
6859 return convertToSameType( list, values.at( 0 ).type() );
6860}
6861
6862static QVariant fcnArrayPrepend( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6863{
6864 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6865 list.prepend( values.at( 1 ) );
6866 return convertToSameType( list, values.at( 0 ).type() );
6867}
6868
6869static QVariant fcnArrayInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6870{
6871 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6872 list.insert( QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent ), values.at( 2 ) );
6873 return convertToSameType( list, values.at( 0 ).type() );
6874}
6875
6876static QVariant fcnArrayRemoveAt( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6877{
6878 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6879 int position = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
6880 if ( position < 0 )
6881 position = position + list.length();
6882 if ( position >= 0 && position < list.length() )
6883 list.removeAt( position );
6884 return convertToSameType( list, values.at( 0 ).type() );
6885}
6886
6887static QVariant fcnArrayRemoveAll( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6888{
6889 if ( QgsVariantUtils::isNull( values.at( 0 ) ) )
6890 return QVariant();
6891
6892 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6893
6894 const QVariant toRemove = values.at( 1 );
6895 if ( QgsVariantUtils::isNull( toRemove ) )
6896 {
6897 list.erase( std::remove_if( list.begin(), list.end(), []( const QVariant & element )
6898 {
6899 return QgsVariantUtils::isNull( element );
6900 } ), list.end() );
6901 }
6902 else
6903 {
6904 list.removeAll( toRemove );
6905 }
6906 return convertToSameType( list, values.at( 0 ).type() );
6907}
6908
6909static QVariant fcnArrayReplace( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6910{
6911 if ( values.count() == 2 && values.at( 1 ).type() == QVariant::Map )
6912 {
6913 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 1 ), parent );
6914
6915 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6916 for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
6917 {
6918 int index = list.indexOf( it.key() );
6919 while ( index >= 0 )
6920 {
6921 list.replace( index, it.value() );
6922 index = list.indexOf( it.key() );
6923 }
6924 }
6925
6926 return convertToSameType( list, values.at( 0 ).type() );
6927 }
6928 else if ( values.count() == 3 )
6929 {
6930 QVariantList before;
6931 QVariantList after;
6932 bool isSingleReplacement = false;
6933
6934 if ( !QgsExpressionUtils::isList( values.at( 1 ) ) && values.at( 2 ).type() != QVariant::StringList )
6935 {
6936 before = QVariantList() << values.at( 1 );
6937 }
6938 else
6939 {
6940 before = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
6941 }
6942
6943 if ( !QgsExpressionUtils::isList( values.at( 2 ) ) )
6944 {
6945 after = QVariantList() << values.at( 2 );
6946 isSingleReplacement = true;
6947 }
6948 else
6949 {
6950 after = QgsExpressionUtils::getListValue( values.at( 2 ), parent );
6951 }
6952
6953 if ( !isSingleReplacement && before.length() != after.length() )
6954 {
6955 parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) );
6956 return QVariant();
6957 }
6958
6959 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6960 for ( int i = 0; i < before.length(); i++ )
6961 {
6962 int index = list.indexOf( before.at( i ) );
6963 while ( index >= 0 )
6964 {
6965 list.replace( index, after.at( isSingleReplacement ? 0 : i ) );
6966 index = list.indexOf( before.at( i ) );
6967 }
6968 }
6969
6970 return convertToSameType( list, values.at( 0 ).type() );
6971 }
6972 else
6973 {
6974 parent->setEvalErrorString( QObject::tr( "Function array_replace requires 2 or 3 arguments" ) );
6975 return QVariant();
6976 }
6977}
6978
6979static QVariant fcnArrayPrioritize( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6980{
6981 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
6982 QVariantList list_new;
6983
6984 for ( const QVariant &cur : QgsExpressionUtils::getListValue( values.at( 1 ), parent ) )
6985 {
6986 while ( list.removeOne( cur ) )
6987 {
6988 list_new.append( cur );
6989 }
6990 }
6991
6992 list_new.append( list );
6993
6994 return convertToSameType( list_new, values.at( 0 ).type() );
6995}
6996
6997static QVariant fcnArrayCat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
6998{
6999 QVariantList list;
7000 for ( const QVariant &cur : values )
7001 {
7002 list += QgsExpressionUtils::getListValue( cur, parent );
7003 }
7004 return convertToSameType( list, values.at( 0 ).type() );
7005}
7006
7007static QVariant fcnArraySlice( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7008{
7009 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7010 int start_pos = QgsExpressionUtils::getNativeIntValue( values.at( 1 ), parent );
7011 const int end_pos = QgsExpressionUtils::getNativeIntValue( values.at( 2 ), parent );
7012 int slice_length = 0;
7013 // negative positions means positions taken relative to the end of the array
7014 if ( start_pos < 0 )
7015 {
7016 start_pos = list.length() + start_pos;
7017 }
7018 if ( end_pos >= 0 )
7019 {
7020 slice_length = end_pos - start_pos + 1;
7021 }
7022 else
7023 {
7024 slice_length = list.length() + end_pos - start_pos + 1;
7025 }
7026 //avoid negative lengths in QList.mid function
7027 if ( slice_length < 0 )
7028 {
7029 slice_length = 0;
7030 }
7031 list = list.mid( start_pos, slice_length );
7032 return list;
7033}
7034
7035static QVariant fcnArrayReverse( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7036{
7037 QVariantList list = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7038 std::reverse( list.begin(), list.end() );
7039 return list;
7040}
7041
7042static QVariant fcnArrayIntersect( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7043{
7044 const QVariantList array1 = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7045 const QVariantList array2 = QgsExpressionUtils::getListValue( values.at( 1 ), parent );
7046 for ( const QVariant &cur : array2 )
7047 {
7048 if ( array1.contains( cur ) )
7049 return QVariant( true );
7050 }
7051 return QVariant( false );
7052}
7053
7054static QVariant fcnArrayDistinct( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7055{
7056 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7057
7058 QVariantList distinct;
7059
7060 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7061 {
7062 if ( !distinct.contains( *it ) )
7063 {
7064 distinct += ( *it );
7065 }
7066 }
7067
7068 return distinct;
7069}
7070
7071static QVariant fcnArrayToString( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7072{
7073 QVariantList array = QgsExpressionUtils::getListValue( values.at( 0 ), parent );
7074 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7075 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7076
7077 QString str;
7078
7079 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
7080 {
7081 str += ( !( *it ).toString().isEmpty() ) ? ( *it ).toString() : empty;
7082 if ( it != ( array.constEnd() - 1 ) )
7083 {
7084 str += delimiter;
7085 }
7086 }
7087
7088 return QVariant( str );
7089}
7090
7091static QVariant fcnStringToArray( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7092{
7093 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7094 QString delimiter = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7095 QString empty = QgsExpressionUtils::getStringValue( values.at( 2 ), parent );
7096
7097 QStringList list = str.split( delimiter );
7098 QVariantList array;
7099
7100 for ( QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it )
7101 {
7102 array += ( !( *it ).isEmpty() ) ? *it : empty;
7103 }
7104
7105 return array;
7106}
7107
7108static QVariant fcnLoadJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7109{
7110 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7111 QJsonDocument document = QJsonDocument::fromJson( str.toUtf8() );
7112 if ( document.isNull() )
7113 return QVariant();
7114
7115 return document.toVariant();
7116}
7117
7118static QVariant fcnWriteJson( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7119{
7120 Q_UNUSED( parent )
7121 QJsonDocument document = QJsonDocument::fromVariant( values.at( 0 ) );
7122 return QString( document.toJson( QJsonDocument::Compact ) );
7123}
7124
7125static QVariant fcnHstoreToMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7126{
7127 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7128 if ( str.isEmpty() )
7129 return QVariantMap();
7130 str = str.trimmed();
7131
7132 return QgsHstoreUtils::parse( str );
7133}
7134
7135static QVariant fcnMapToHstore( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7136{
7137 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7138 return QgsHstoreUtils::build( map );
7139}
7140
7141static QVariant fcnMap( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7142{
7143 QVariantMap result;
7144 for ( int i = 0; i + 1 < values.length(); i += 2 )
7145 {
7146 result.insert( QgsExpressionUtils::getStringValue( values.at( i ), parent ), values.at( i + 1 ) );
7147 }
7148 return result;
7149}
7150
7151static QVariant fcnMapPrefixKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7152{
7153 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7154 const QString prefix = QgsExpressionUtils::getStringValue( values.at( 1 ), parent );
7155 QVariantMap resultMap;
7156
7157 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7158 {
7159 resultMap.insert( QString( it.key() ).prepend( prefix ), it.value() );
7160 }
7161
7162 return resultMap;
7163}
7164
7165static QVariant fcnMapGet( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7166{
7167 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).value( values.at( 1 ).toString() );
7168}
7169
7170static QVariant fcnMapExist( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7171{
7172 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).contains( values.at( 1 ).toString() );
7173}
7174
7175static QVariant fcnMapDelete( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7176{
7177 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7178 map.remove( values.at( 1 ).toString() );
7179 return map;
7180}
7181
7182static QVariant fcnMapInsert( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7183{
7184 QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7185 map.insert( values.at( 1 ).toString(), values.at( 2 ) );
7186 return map;
7187}
7188
7189static QVariant fcnMapConcat( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7190{
7191 QVariantMap result;
7192 for ( const QVariant &cur : values )
7193 {
7194 const QVariantMap curMap = QgsExpressionUtils::getMapValue( cur, parent );
7195 for ( QVariantMap::const_iterator it = curMap.constBegin(); it != curMap.constEnd(); ++it )
7196 result.insert( it.key(), it.value() );
7197 }
7198 return result;
7199}
7200
7201static QVariant fcnMapAKeys( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7202{
7203 return QStringList( QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).keys() );
7204}
7205
7206static QVariant fcnMapAVals( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7207{
7208 return QgsExpressionUtils::getMapValue( values.at( 0 ), parent ).values();
7209}
7210
7211static QVariant fcnEnvVar( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7212{
7213 const QString envVarName = values.at( 0 ).toString();
7214 if ( !QProcessEnvironment::systemEnvironment().contains( envVarName ) )
7215 return QVariant();
7216
7217 return QProcessEnvironment::systemEnvironment().value( envVarName );
7218}
7219
7220static QVariant fcnBaseFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7221{
7222 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7223 if ( parent->hasEvalError() )
7224 {
7225 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "base_file_name" ) ) );
7226 return QVariant();
7227 }
7228 return QFileInfo( file ).completeBaseName();
7229}
7230
7231static QVariant fcnFileSuffix( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7232{
7233 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7234 if ( parent->hasEvalError() )
7235 {
7236 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_suffix" ) ) );
7237 return QVariant();
7238 }
7239 return QFileInfo( file ).completeSuffix();
7240}
7241
7242static QVariant fcnFileExists( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7243{
7244 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7245 if ( parent->hasEvalError() )
7246 {
7247 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_exists" ) ) );
7248 return QVariant();
7249 }
7250 return QFileInfo::exists( file );
7251}
7252
7253static QVariant fcnFileName( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7254{
7255 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7256 if ( parent->hasEvalError() )
7257 {
7258 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_name" ) ) );
7259 return QVariant();
7260 }
7261 return QFileInfo( file ).fileName();
7262}
7263
7264static QVariant fcnPathIsFile( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7265{
7266 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7267 if ( parent->hasEvalError() )
7268 {
7269 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_file" ) ) );
7270 return QVariant();
7271 }
7272 return QFileInfo( file ).isFile();
7273}
7274
7275static QVariant fcnPathIsDir( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7276{
7277 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7278 if ( parent->hasEvalError() )
7279 {
7280 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "is_directory" ) ) );
7281 return QVariant();
7282 }
7283 return QFileInfo( file ).isDir();
7284}
7285
7286static QVariant fcnFilePath( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7287{
7288 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7289 if ( parent->hasEvalError() )
7290 {
7291 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_path" ) ) );
7292 return QVariant();
7293 }
7294 return QDir::toNativeSeparators( QFileInfo( file ).path() );
7295}
7296
7297static QVariant fcnFileSize( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7298{
7299 const QString file = QgsExpressionUtils::getFilePathValue( values.at( 0 ), context, parent );
7300 if ( parent->hasEvalError() )
7301 {
7302 parent->setEvalErrorString( QObject::tr( "Function `%1` requires a value which represents a possible file path" ).arg( QLatin1String( "file_size" ) ) );
7303 return QVariant();
7304 }
7305 return QFileInfo( file ).size();
7306}
7307
7308static QVariant fcnHash( const QString &str, const QCryptographicHash::Algorithm algorithm )
7309{
7310 return QString( QCryptographicHash::hash( str.toUtf8(), algorithm ).toHex() );
7311}
7312
7313static QVariant fcnGenericHash( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7314{
7315 QVariant hash;
7316 QString str = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7317 QString method = QgsExpressionUtils::getStringValue( values.at( 1 ), parent ).toLower();
7318
7319 if ( method == QLatin1String( "md4" ) )
7320 {
7321 hash = fcnHash( str, QCryptographicHash::Md4 );
7322 }
7323 else if ( method == QLatin1String( "md5" ) )
7324 {
7325 hash = fcnHash( str, QCryptographicHash::Md5 );
7326 }
7327 else if ( method == QLatin1String( "sha1" ) )
7328 {
7329 hash = fcnHash( str, QCryptographicHash::Sha1 );
7330 }
7331 else if ( method == QLatin1String( "sha224" ) )
7332 {
7333 hash = fcnHash( str, QCryptographicHash::Sha224 );
7334 }
7335 else if ( method == QLatin1String( "sha256" ) )
7336 {
7337 hash = fcnHash( str, QCryptographicHash::Sha256 );
7338 }
7339 else if ( method == QLatin1String( "sha384" ) )
7340 {
7341 hash = fcnHash( str, QCryptographicHash::Sha384 );
7342 }
7343 else if ( method == QLatin1String( "sha512" ) )
7344 {
7345 hash = fcnHash( str, QCryptographicHash::Sha512 );
7346 }
7347 else if ( method == QLatin1String( "sha3_224" ) )
7348 {
7349 hash = fcnHash( str, QCryptographicHash::Sha3_224 );
7350 }
7351 else if ( method == QLatin1String( "sha3_256" ) )
7352 {
7353 hash = fcnHash( str, QCryptographicHash::Sha3_256 );
7354 }
7355 else if ( method == QLatin1String( "sha3_384" ) )
7356 {
7357 hash = fcnHash( str, QCryptographicHash::Sha3_384 );
7358 }
7359 else if ( method == QLatin1String( "sha3_512" ) )
7360 {
7361 hash = fcnHash( str, QCryptographicHash::Sha3_512 );
7362 }
7363 else if ( method == QLatin1String( "keccak_224" ) )
7364 {
7365 hash = fcnHash( str, QCryptographicHash::Keccak_224 );
7366 }
7367 else if ( method == QLatin1String( "keccak_256" ) )
7368 {
7369 hash = fcnHash( str, QCryptographicHash::Keccak_256 );
7370 }
7371 else if ( method == QLatin1String( "keccak_384" ) )
7372 {
7373 hash = fcnHash( str, QCryptographicHash::Keccak_384 );
7374 }
7375 else if ( method == QLatin1String( "keccak_512" ) )
7376 {
7377 hash = fcnHash( str, QCryptographicHash::Keccak_512 );
7378 }
7379 else
7380 {
7381 parent->setEvalErrorString( QObject::tr( "Hash method %1 is not available on this system." ).arg( str ) );
7382 }
7383 return hash;
7384}
7385
7386static QVariant fcnHashMd5( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7387{
7388 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Md5 );
7389}
7390
7391static QVariant fcnHashSha256( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7392{
7393 return fcnHash( QgsExpressionUtils::getStringValue( values.at( 0 ), parent ), QCryptographicHash::Sha256 );
7394}
7395
7396static QVariant fcnToBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *, const QgsExpressionNodeFunction * )
7397{
7398 const QByteArray input = values.at( 0 ).toByteArray();
7399 return QVariant( QString( input.toBase64() ) );
7400}
7401
7402static QVariant fcnToFormUrlEncode( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7403{
7404 const QVariantMap map = QgsExpressionUtils::getMapValue( values.at( 0 ), parent );
7405 QUrlQuery query;
7406 for ( auto it = map.cbegin(); it != map.cend(); it++ )
7407 {
7408 query.addQueryItem( it.key(), it.value().toString() );
7409 }
7410 return query.toString( QUrl::ComponentFormattingOption::FullyEncoded );
7411}
7412
7413static QVariant fcnFromBase64( const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction * )
7414{
7415 const QString value = QgsExpressionUtils::getStringValue( values.at( 0 ), parent );
7416 const QByteArray base64 = value.toLocal8Bit();
7417 const QByteArray decoded = QByteArray::fromBase64( base64 );
7418 return QVariant( decoded );
7419}
7420
7421typedef bool ( QgsGeometry::*RelationFunction )( const QgsGeometry &geometry ) const;
7422
7423static 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 )
7424{
7425
7426 const QVariant sourceLayerRef = context->variable( QStringLiteral( "layer" ) ); //used to detect if sourceLayer and targetLayer are the same
7427 // TODO this function is NOT thread safe
7429 QgsVectorLayer *sourceLayer = QgsExpressionUtils::getVectorLayer( sourceLayerRef, context, parent );
7431
7432 QgsFeatureRequest request;
7433 request.setTimeout( 10000 );
7434 request.setRequestMayBeNested( true );
7435 request.setFeedback( context->feedback() );
7436
7437 // First parameter is the overlay layer
7438 QgsExpressionNode *node = QgsExpressionUtils::getNode( values.at( 0 ), parent );
7440
7441 const bool layerCanBeCached = node->isStatic( parent, context );
7442 QVariant targetLayerValue = node->eval( parent, context );
7444
7445 // Second parameter is the expression to evaluate (or null for testonly)
7446 node = QgsExpressionUtils::getNode( values.at( 1 ), parent );
7448 QString subExpString = node->dump();
7449
7450 bool testOnly = ( subExpString == "NULL" );
7451 // TODO this function is NOT thread safe
7453 QgsVectorLayer *targetLayer = QgsExpressionUtils::getVectorLayer( targetLayerValue, context, parent );
7455 if ( !targetLayer ) // No layer, no joy
7456 {
7457 parent->setEvalErrorString( QObject::tr( "Layer '%1' could not be loaded." ).arg( targetLayerValue.toString() ) );
7458 return QVariant();
7459 }
7460
7461 // Third parameter is the filtering expression
7462 node = QgsExpressionUtils::getNode( values.at( 2 ), parent );
7464 QString filterString = node->dump();
7465 if ( filterString != "NULL" )
7466 {
7467 request.setFilterExpression( filterString ); //filter cached features
7468 }
7469
7470 // Fourth parameter is the limit
7471 node = QgsExpressionUtils::getNode( values.at( 3 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7473 QVariant limitValue = node->eval( parent, context );
7475 qlonglong limit = QgsExpressionUtils::getIntValue( limitValue, parent );
7476
7477 // Fifth parameter (for nearest only) is the max distance
7478 double max_distance = 0;
7479 if ( isNearestFunc ) //maxdistance param handling
7480 {
7481 node = QgsExpressionUtils::getNode( values.at( 4 ), parent );
7483 QVariant distanceValue = node->eval( parent, context );
7485 max_distance = QgsExpressionUtils::getDoubleValue( distanceValue, parent );
7486 }
7487
7488 // Fifth or sixth (for nearest only) parameter is the cache toggle
7489 node = QgsExpressionUtils::getNode( values.at( isNearestFunc ? 5 : 4 ), parent );
7491 QVariant cacheValue = node->eval( parent, context );
7493 bool cacheEnabled = cacheValue.toBool();
7494
7495 // Sixth parameter (for intersects only) is the min overlap (area or length)
7496 // Seventh parameter (for intersects only) is the min inscribed circle radius
7497 // Eighth parameter (for intersects only) is the return_details
7498 // Ninth parameter (for intersects only) is the sort_by_intersection_size flag
7499 double minOverlap { -1 };
7500 double minInscribedCircleRadius { -1 };
7501 bool returnDetails = false; //#spellok
7502 bool sortByMeasure = false;
7503 bool sortAscending = false;
7504 bool requireMeasures = false;
7505 bool overlapOrRadiusFilter = false;
7506 if ( isIntersectsFunc )
7507 {
7508
7509 node = QgsExpressionUtils::getNode( values.at( 5 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7511 const QVariant minOverlapValue = node->eval( parent, context );
7513 minOverlap = QgsExpressionUtils::getDoubleValue( minOverlapValue, parent );
7514 node = QgsExpressionUtils::getNode( values.at( 6 ), parent ); //in expressions overlay functions throw the exception: Eval Error: Cannot convert '' to int
7516 const QVariant minInscribedCircleRadiusValue = node->eval( parent, context );
7518 minInscribedCircleRadius = QgsExpressionUtils::getDoubleValue( minInscribedCircleRadiusValue, parent );
7519 node = QgsExpressionUtils::getNode( values.at( 7 ), parent );
7520 // Return measures is only effective when an expression is set
7521 returnDetails = !testOnly && node->eval( parent, context ).toBool(); //#spellok
7522 node = QgsExpressionUtils::getNode( values.at( 8 ), parent );
7523 // Sort by measures is only effective when an expression is set
7524 const QString sorting { node->eval( parent, context ).toString().toLower() };
7525 sortByMeasure = !testOnly && ( sorting.startsWith( "asc" ) || sorting.startsWith( "des" ) );
7526 sortAscending = sorting.startsWith( "asc" );
7527 requireMeasures = sortByMeasure || returnDetails; //#spellok
7528 overlapOrRadiusFilter = minInscribedCircleRadius != -1 || minOverlap != -1;
7529 }
7530
7531
7532 FEAT_FROM_CONTEXT( context, feat )
7533 const QgsGeometry geometry = feat.geometry();
7534
7535 if ( sourceLayer && targetLayer->crs() != sourceLayer->crs() )
7536 {
7537 QgsCoordinateTransformContext TransformContext = context->variable( QStringLiteral( "_project_transform_context" ) ).value<QgsCoordinateTransformContext>();
7538 request.setDestinationCrs( sourceLayer->crs(), TransformContext ); //if crs are not the same, cached target will be reprojected to source crs
7539 }
7540
7541 bool sameLayers = ( sourceLayer && sourceLayer->id() == targetLayer->id() );
7542
7543 QgsRectangle intDomain = geometry.boundingBox();
7544 if ( bboxGrow != 0 )
7545 {
7546 intDomain.grow( bboxGrow ); //optional parameter to enlarge boundary context for touches and equals methods
7547 }
7548
7549 const QString cacheBase { QStringLiteral( "%1:%2:%3" ).arg( targetLayer->id(), subExpString, filterString ) };
7550
7551 // Cache (a local spatial index) is always enabled for nearest function (as we need QgsSpatialIndex::nearestNeighbor)
7552 // Otherwise, it can be toggled by the user
7553 QgsSpatialIndex spatialIndex;
7554 QgsVectorLayer *cachedTarget;
7555 QList<QgsFeature> features;
7556 if ( isNearestFunc || ( layerCanBeCached && cacheEnabled ) )
7557 {
7558 // If the cache (local spatial index) is enabled, we materialize the whole
7559 // layer, then do the request on that layer instead.
7560 const QString cacheLayer { QStringLiteral( "ovrlaylyr:%1" ).arg( cacheBase ) };
7561 const QString cacheIndex { QStringLiteral( "ovrlayidx:%1" ).arg( cacheBase ) };
7562
7563 if ( !context->hasCachedValue( cacheLayer ) ) // should check for same crs. if not the same we could think to reproject target layer before charging cache
7564 {
7565 cachedTarget = targetLayer->materialize( request );
7566 if ( layerCanBeCached )
7567 context->setCachedValue( cacheLayer, QVariant::fromValue( cachedTarget ) );
7568 }
7569 else
7570 {
7571 cachedTarget = context->cachedValue( cacheLayer ).value<QgsVectorLayer *>();
7572 }
7573
7574 if ( !context->hasCachedValue( cacheIndex ) )
7575 {
7576 spatialIndex = QgsSpatialIndex( cachedTarget->getFeatures(), nullptr, QgsSpatialIndex::FlagStoreFeatureGeometries );
7577 if ( layerCanBeCached )
7578 context->setCachedValue( cacheIndex, QVariant::fromValue( spatialIndex ) );
7579 }
7580 else
7581 {
7582 spatialIndex = context->cachedValue( cacheIndex ).value<QgsSpatialIndex>();
7583 }
7584
7585 QList<QgsFeatureId> fidsList;
7586 if ( isNearestFunc )
7587 {
7588 fidsList = spatialIndex.nearestNeighbor( geometry, sameLayers ? limit + 1 : limit, max_distance );
7589 }
7590 else
7591 {
7592 fidsList = spatialIndex.intersects( intDomain );
7593 }
7594
7595 QListIterator<QgsFeatureId> i( fidsList );
7596 while ( i.hasNext() )
7597 {
7598 QgsFeatureId fId2 = i.next();
7599 if ( sameLayers && feat.id() == fId2 )
7600 continue;
7601 features.append( cachedTarget->getFeature( fId2 ) );
7602 }
7603
7604 }
7605 else
7606 {
7607 // If the cache (local spatial index) is not enabled, we directly
7608 // get the features from the target layer
7609 request.setFilterRect( intDomain );
7610 QgsFeatureIterator fit = targetLayer->getFeatures( request );
7611 QgsFeature feat2;
7612 while ( fit.nextFeature( feat2 ) )
7613 {
7614 if ( sameLayers && feat.id() == feat2.id() )
7615 continue;
7616 features.append( feat2 );
7617 }
7618 }
7619
7620 QgsExpression subExpression;
7621 QgsExpressionContext subContext;
7622 if ( !testOnly )
7623 {
7624 const QString expCacheKey { QStringLiteral( "exp:%1" ).arg( cacheBase ) };
7625 const QString ctxCacheKey { QStringLiteral( "ctx:%1" ).arg( cacheBase ) };
7626
7627 if ( !context->hasCachedValue( expCacheKey ) || !context->hasCachedValue( ctxCacheKey ) )
7628 {
7629 subExpression = QgsExpression( subExpString );
7631 subExpression.prepare( &subContext );
7632 }
7633 else
7634 {
7635 subExpression = context->cachedValue( expCacheKey ).value<QgsExpression>();
7636 subContext = context->cachedValue( ctxCacheKey ).value<QgsExpressionContext>();
7637 }
7638 }
7639
7640 // //////////////////////////////////////////////////////////////////
7641 // Helper functions for geometry tests
7642
7643 // Test function for linestring geometries, returns TRUE if test passes
7644 auto testLinestring = [ = ]( const QgsGeometry intersection, double & overlapValue ) -> bool
7645 {
7646 bool testResult { false };
7647 // For return measures:
7648 QVector<double> overlapValues;
7649 for ( auto it = intersection.const_parts_begin(); ! testResult && it != intersection.const_parts_end(); ++it )
7650 {
7651 const QgsCurve *geom = qgsgeometry_cast< const QgsCurve * >( *it );
7652 // Check min overlap for intersection (if set)
7653 if ( minOverlap != -1 || requireMeasures )
7654 {
7655 overlapValue = geom->length();
7656 overlapValues.append( overlapValue );
7657 if ( minOverlap != -1 )
7658 {
7659 if ( overlapValue >= minOverlap )
7660 {
7661 testResult = true;
7662 }
7663 else
7664 {
7665 continue;
7666 }
7667 }
7668 }
7669 }
7670
7671 if ( ! overlapValues.isEmpty() )
7672 {
7673 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
7674 }
7675
7676 return testResult;
7677 };
7678
7679 // Test function for polygon geometries, returns TRUE if test passes
7680 auto testPolygon = [ = ]( const QgsGeometry intersection, double & radiusValue, double & overlapValue ) -> bool
7681 {
7682 // overlap and inscribed circle tests must be checked both (if the values are != -1)
7683 bool testResult { false };
7684 // For return measures:
7685 QVector<double> overlapValues;
7686 QVector<double> radiusValues;
7687 for ( auto it = intersection.const_parts_begin(); ( ! testResult || requireMeasures ) && it != intersection.const_parts_end(); ++it )
7688 {
7689 const QgsCurvePolygon *geom = qgsgeometry_cast< const QgsCurvePolygon * >( *it );
7690 // Check min overlap for intersection (if set)
7691 if ( minOverlap != -1 || requireMeasures )
7692 {
7693 overlapValue = geom->area();
7694 overlapValues.append( geom->area() );
7695 if ( minOverlap != - 1 )
7696 {
7697 if ( overlapValue >= minOverlap )
7698 {
7699 testResult = true;
7700 }
7701 else
7702 {
7703 continue;
7704 }
7705 }
7706 }
7707
7708 // Check min inscribed circle radius for intersection (if set)
7709 if ( minInscribedCircleRadius != -1 || requireMeasures )
7710 {
7711 const QgsRectangle bbox = geom->boundingBox();
7712 const double width = bbox.width();
7713 const double height = bbox.height();
7714 const double size = width > height ? width : height;
7715 const double tolerance = size / 100.0;
7716 radiusValue = QgsGeos( geom ).maximumInscribedCircle( tolerance )->length();
7717 testResult = radiusValue >= minInscribedCircleRadius;
7718 radiusValues.append( radiusValues );
7719 }
7720 } // end for parts
7721
7722 // Get the max values
7723 if ( !radiusValues.isEmpty() )
7724 {
7725 radiusValue = *std::max_element( radiusValues.cbegin(), radiusValues.cend() );
7726 }
7727
7728 if ( ! overlapValues.isEmpty() )
7729 {
7730 overlapValue = *std::max_element( overlapValues.cbegin(), overlapValues.cend() );
7731 }
7732
7733 return testResult;
7734
7735 };
7736
7737
7738 bool found = false;
7739 int foundCount = 0;
7740 QVariantList results;
7741
7742 QListIterator<QgsFeature> i( features );
7743 while ( i.hasNext() && ( sortByMeasure || limit == -1 || foundCount < limit ) )
7744 {
7745
7746 QgsFeature feat2 = i.next();
7747
7748
7749 if ( ! relationFunction || ( geometry.*relationFunction )( feat2.geometry() ) ) // Calls the method provided as template argument for the function (e.g. QgsGeometry::intersects)
7750 {
7751
7752 double overlapValue = -1;
7753 double radiusValue = -1;
7754
7755 if ( isIntersectsFunc && ( requireMeasures || overlapOrRadiusFilter ) )
7756 {
7757 const QgsGeometry intersection { geometry.intersection( feat2.geometry() ) };
7758
7759 // Depending on the intersection geometry type and on the geometry type of
7760 // the tested geometry we can run different tests and collect different measures
7761 // that can be used for sorting (if required).
7762 switch ( intersection.type() )
7763 {
7764
7765 case Qgis::GeometryType::Polygon:
7766 {
7767
7768 // Overlap and inscribed circle tests must be checked both (if the values are != -1)
7769 bool testResult { testPolygon( intersection, radiusValue, overlapValue ) };
7770
7771 if ( ! testResult && overlapOrRadiusFilter )
7772 {
7773 continue;
7774 }
7775
7776 break;
7777 }
7778
7779 case Qgis::GeometryType::Line:
7780 {
7781
7782 // If the intersection is a linestring and a minimum circle is required
7783 // we can discard this result immediately.
7784 if ( minInscribedCircleRadius != -1 )
7785 {
7786 continue;
7787 }
7788
7789 // Otherwise a test for the overlap value is performed.
7790 const bool testResult { testLinestring( intersection, overlapValue ) };
7791
7792 if ( ! testResult && overlapOrRadiusFilter )
7793 {
7794 continue;
7795 }
7796
7797 break;
7798 }
7799
7800 case Qgis::GeometryType::Point:
7801 {
7802
7803 // If the intersection is a point and a minimum circle is required
7804 // we can discard this result immediately.
7805 if ( minInscribedCircleRadius != -1 )
7806 {
7807 continue;
7808 }
7809
7810 bool testResult { false };
7811 if ( minOverlap != -1 || requireMeasures )
7812 {
7813 // Initially set this to 0 because it's a point intersection...
7814 overlapValue = 0;
7815 // ... but if the target geometry is not a point and the source
7816 // geometry is a point, we must record the length or the area
7817 // of the intersected geometry and use that as a measure for
7818 // sorting or reporting.
7819 if ( geometry.type() == Qgis::GeometryType::Point )
7820 {
7821 switch ( feat2.geometry().type() )
7822 {
7823 case Qgis::GeometryType::Unknown:
7824 case Qgis::GeometryType::Null:
7825 case Qgis::GeometryType::Point:
7826 {
7827 break;
7828 }
7829 case Qgis::GeometryType::Line:
7830 {
7831 testResult = testLinestring( feat2.geometry(), overlapValue );
7832 break;
7833 }
7834 case Qgis::GeometryType::Polygon:
7835 {
7836 testResult = testPolygon( feat2.geometry(), radiusValue, overlapValue );
7837 break;
7838 }
7839 }
7840 }
7841
7842 if ( ! testResult && overlapOrRadiusFilter )
7843 {
7844 continue;
7845 }
7846
7847 }
7848 break;
7849 }
7850
7851 case Qgis::GeometryType::Null:
7852 case Qgis::GeometryType::Unknown:
7853 {
7854 continue;
7855 }
7856 }
7857 }
7858
7859 found = true;
7860 foundCount++;
7861
7862 // We just want a single boolean result if there is any intersect: finish and return true
7863 if ( testOnly )
7864 break;
7865
7866 if ( !invert )
7867 {
7868 // We want a list of attributes / geometries / other expression values, evaluate now
7869 subContext.setFeature( feat2 );
7870 const QVariant expResult = subExpression.evaluate( &subContext );
7871
7872 if ( requireMeasures )
7873 {
7874 QVariantMap resultRecord;
7875 resultRecord.insert( QStringLiteral( "id" ), feat2.id() );
7876 resultRecord.insert( QStringLiteral( "result" ), expResult );
7877 // Overlap is always added because return measures was set
7878 resultRecord.insert( QStringLiteral( "overlap" ), overlapValue );
7879 // Radius is only added when is different than -1 (because for linestrings is not set)
7880 if ( radiusValue != -1 )
7881 {
7882 resultRecord.insert( QStringLiteral( "radius" ), radiusValue );
7883 }
7884 results.append( resultRecord );
7885 }
7886 else
7887 {
7888 results.append( expResult );
7889 }
7890 }
7891 else
7892 {
7893 // If not, results is a list of found ids, which we'll inverse and evaluate below
7894 results.append( feat2.id() );
7895 }
7896 }
7897 }
7898
7899 if ( testOnly )
7900 {
7901 if ( invert )
7902 found = !found;//for disjoint condition
7903 return found;
7904 }
7905
7906 if ( !invert )
7907 {
7908 if ( requireMeasures )
7909 {
7910 if ( sortByMeasure )
7911 {
7912 std::sort( results.begin(), results.end(), [ sortAscending ]( const QVariant & recordA, const QVariant & recordB ) -> bool
7913 {
7914 return sortAscending ?
7915 recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble()
7916 : recordA.toMap().value( QStringLiteral( "overlap" ) ).toDouble() > recordB.toMap().value( QStringLiteral( "overlap" ) ).toDouble();
7917 } );
7918 }
7919 // Resize
7920 if ( limit > 0 && results.size() > limit )
7921 {
7922 results.erase( results.begin() + limit );
7923 }
7924
7925 if ( ! returnDetails ) //#spellok
7926 {
7927 QVariantList expResults;
7928 for ( auto it = results.constBegin(); it != results.constEnd(); ++it )
7929 {
7930 expResults.append( it->toMap().value( QStringLiteral( "result" ) ) );
7931 }
7932 return expResults;
7933 }
7934 }
7935
7936 return results;
7937 }
7938
7939 // for disjoint condition returns the results for cached layers not intersected feats
7940 QVariantList disjoint_results;
7941 QgsFeature feat2;
7942 QgsFeatureRequest request2;
7943 request2.setLimit( limit );
7944 if ( context )
7945 request2.setFeedback( context->feedback() );
7946 QgsFeatureIterator fi = targetLayer->getFeatures( request2 );
7947 while ( fi.nextFeature( feat2 ) )
7948 {
7949 if ( !results.contains( feat2.id() ) )
7950 {
7951 subContext.setFeature( feat2 );
7952 disjoint_results.append( subExpression.evaluate( &subContext ) );
7953 }
7954 }
7955 return disjoint_results;
7956
7957}
7958
7959// Intersect functions:
7960
7961static QVariant fcnGeomOverlayIntersects( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7962{
7963 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, false, 0, false, true );
7964}
7965
7966static QVariant fcnGeomOverlayContains( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7967{
7968 return executeGeomOverlay( values, context, parent, &QgsGeometry::contains );
7969}
7970
7971static QVariant fcnGeomOverlayCrosses( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7972{
7973 return executeGeomOverlay( values, context, parent, &QgsGeometry::crosses );
7974}
7975
7976static QVariant fcnGeomOverlayEquals( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7977{
7978 return executeGeomOverlay( values, context, parent, &QgsGeometry::equals, false, 0.01 ); //grow amount should adapt to current units
7979}
7980
7981static QVariant fcnGeomOverlayTouches( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7982{
7983 return executeGeomOverlay( values, context, parent, &QgsGeometry::touches, false, 0.01 ); //grow amount should adapt to current units
7984}
7985
7986static QVariant fcnGeomOverlayWithin( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7987{
7988 return executeGeomOverlay( values, context, parent, &QgsGeometry::within );
7989}
7991static QVariant fcnGeomOverlayDisjoint( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7992{
7993 return executeGeomOverlay( values, context, parent, &QgsGeometry::intersects, true, 0, false, true );
7994}
7995
7996static QVariant fcnGeomOverlayNearest( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction * )
7997{
7998 return executeGeomOverlay( values, context, parent, nullptr, false, 0, true );
7999}
8000
8001const QList<QgsExpressionFunction *> &QgsExpression::Functions()
8002{
8003 // The construction of the list isn't thread-safe, and without the mutex,
8004 // crashes in the WFS provider may occur, since it can parse expressions
8005 // in parallel.
8006 // The mutex needs to be recursive.
8007 static QRecursiveMutex sFunctionsMutex;
8008 QMutexLocker locker( &sFunctionsMutex );
8009
8010 QList<QgsExpressionFunction *> &functions = *sFunctions();
8011
8012 if ( functions.isEmpty() )
8013 {
8015 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
8016 << QgsExpressionFunction::Parameter( QStringLiteral( "group_by" ), true )
8017 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true );
8018
8019 QgsExpressionFunction::ParameterList aggParamsConcat = aggParams;
8020 aggParamsConcat << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8021 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8022
8023 QgsExpressionFunction::ParameterList aggParamsArray = aggParams;
8024 aggParamsArray << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true );
8025
8026 functions
8027 << new QgsStaticExpressionFunction( QStringLiteral( "sqrt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnSqrt, QStringLiteral( "Math" ) )
8028 << new QgsStaticExpressionFunction( QStringLiteral( "radians" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "degrees" ) ), fcnRadians, QStringLiteral( "Math" ) )
8029 << new QgsStaticExpressionFunction( QStringLiteral( "degrees" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "radians" ) ), fcnDegrees, QStringLiteral( "Math" ) )
8030 << new QgsStaticExpressionFunction( QStringLiteral( "azimuth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnAzimuth, QStringLiteral( "GeometryGroup" ) )
8031 << new QgsStaticExpressionFunction( QStringLiteral( "inclination" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point_b" ) ), fcnInclination, QStringLiteral( "GeometryGroup" ) )
8032 << 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" ) )
8033 << new QgsStaticExpressionFunction( QStringLiteral( "abs" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAbs, QStringLiteral( "Math" ) )
8034 << new QgsStaticExpressionFunction( QStringLiteral( "cos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnCos, QStringLiteral( "Math" ) )
8035 << new QgsStaticExpressionFunction( QStringLiteral( "sin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnSin, QStringLiteral( "Math" ) )
8036 << new QgsStaticExpressionFunction( QStringLiteral( "tan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "angle" ) ), fcnTan, QStringLiteral( "Math" ) )
8037 << new QgsStaticExpressionFunction( QStringLiteral( "asin" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAsin, QStringLiteral( "Math" ) )
8038 << new QgsStaticExpressionFunction( QStringLiteral( "acos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAcos, QStringLiteral( "Math" ) )
8039 << new QgsStaticExpressionFunction( QStringLiteral( "atan" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnAtan, QStringLiteral( "Math" ) )
8040 << new QgsStaticExpressionFunction( QStringLiteral( "atan2" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ), fcnAtan2, QStringLiteral( "Math" ) )
8041 << new QgsStaticExpressionFunction( QStringLiteral( "exp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnExp, QStringLiteral( "Math" ) )
8042 << new QgsStaticExpressionFunction( QStringLiteral( "ln" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLn, QStringLiteral( "Math" ) )
8043 << new QgsStaticExpressionFunction( QStringLiteral( "log10" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog10, QStringLiteral( "Math" ) )
8044 << new QgsStaticExpressionFunction( QStringLiteral( "log" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "base" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLog, QStringLiteral( "Math" ) )
8045 << new QgsStaticExpressionFunction( QStringLiteral( "round" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 ), fcnRound, QStringLiteral( "Math" ) );
8046
8047 QgsStaticExpressionFunction *randFunc = new QgsStaticExpressionFunction( QStringLiteral( "rand" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true ), fcnRnd, QStringLiteral( "Math" ) );
8048 randFunc->setIsStatic( false );
8049 functions << randFunc;
8050
8051 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" ) );
8052 randfFunc->setIsStatic( false );
8053 functions << randfFunc;
8054
8055 functions
8056 << new QgsStaticExpressionFunction( QStringLiteral( "max" ), -1, fcnMax, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8057 << new QgsStaticExpressionFunction( QStringLiteral( "min" ), -1, fcnMin, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList(), /* handlesNull = */ true )
8058 << new QgsStaticExpressionFunction( QStringLiteral( "clamp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "min" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "max" ) ), fcnClamp, QStringLiteral( "Math" ) )
8059 << 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" ) )
8060 << 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" ) )
8061 << 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" ) )
8062 << new QgsStaticExpressionFunction( QStringLiteral( "floor" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnFloor, QStringLiteral( "Math" ) )
8063 << new QgsStaticExpressionFunction( QStringLiteral( "ceil" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnCeil, QStringLiteral( "Math" ) )
8064 << new QgsStaticExpressionFunction( QStringLiteral( "pi" ), 0, fcnPi, QStringLiteral( "Math" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$pi" ) )
8065 << new QgsStaticExpressionFunction( QStringLiteral( "to_int" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToInt, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toint" ) )
8066 << new QgsStaticExpressionFunction( QStringLiteral( "to_real" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToReal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "toreal" ) )
8067 << 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" ) )
8068 << 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" ) )
8069 << 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" ) )
8070 << 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" ) )
8071 << 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" ) )
8072 << 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" ) )
8073 << 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" ) )
8074 << new QgsStaticExpressionFunction( QStringLiteral( "to_decimal" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnToDecimal, QStringLiteral( "Conversions" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "todecimal" ) )
8075 << new QgsStaticExpressionFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8076 << new QgsStaticExpressionFunction( QStringLiteral( "nullif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value2" ) ), fcnNullIf, QStringLiteral( "Conditionals" ) )
8077 << 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 )
8078 << new QgsStaticExpressionFunction( QStringLiteral( "try" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "alternative" ), true, QVariant() ), fcnTry, QStringLiteral( "Conditionals" ), QString(), false, QSet<QString>(), true )
8079
8080 << new QgsStaticExpressionFunction( QStringLiteral( "aggregate" ),
8082 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8083 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8084 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8085 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8086 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8087 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8088 fcnAggregate,
8089 QStringLiteral( "Aggregates" ),
8090 QString(),
8091 []( const QgsExpressionNodeFunction * node )
8092 {
8093 // usesGeometry callback: return true if @parent variable is referenced
8094
8095 if ( !node )
8096 return true;
8097
8098 if ( !node->args() )
8099 return false;
8100
8101 QSet<QString> referencedVars;
8102 if ( node->args()->count() > 2 )
8103 {
8104 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8105 referencedVars = subExpressionNode->referencedVariables();
8106 }
8107
8108 if ( node->args()->count() > 3 )
8109 {
8110 QgsExpressionNode *filterNode = node->args()->at( 3 );
8111 referencedVars.unite( filterNode->referencedVariables() );
8112 }
8113 return referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() );
8114 },
8115 []( const QgsExpressionNodeFunction * node )
8116 {
8117 // referencedColumns callback: return AllAttributes if @parent variable is referenced
8118
8119 if ( !node )
8120 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8121
8122 if ( !node->args() )
8123 return QSet<QString>();
8124
8125 QSet<QString> referencedCols;
8126 QSet<QString> referencedVars;
8127
8128 if ( node->args()->count() > 2 )
8129 {
8130 QgsExpressionNode *subExpressionNode = node->args()->at( 2 );
8131 referencedVars = subExpressionNode->referencedVariables();
8132 referencedCols = subExpressionNode->referencedColumns();
8133 }
8134 if ( node->args()->count() > 3 )
8135 {
8136 QgsExpressionNode *filterNode = node->args()->at( 3 );
8137 referencedVars = filterNode->referencedVariables();
8138 referencedCols.unite( filterNode->referencedColumns() );
8139 }
8140
8141 if ( referencedVars.contains( QStringLiteral( "parent" ) ) || referencedVars.contains( QString() ) )
8142 return QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES;
8143 else
8144 return referencedCols;
8145 },
8146 true
8147 )
8148
8149 << new QgsStaticExpressionFunction( QStringLiteral( "relation_aggregate" ), QgsExpressionFunction::ParameterList()
8150 << QgsExpressionFunction::Parameter( QStringLiteral( "relation" ) )
8151 << QgsExpressionFunction::Parameter( QStringLiteral( "aggregate" ) )
8152 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), false, QVariant(), true )
8153 << QgsExpressionFunction::Parameter( QStringLiteral( "concatenator" ), true )
8154 << QgsExpressionFunction::Parameter( QStringLiteral( "order_by" ), true, QVariant(), true ),
8155 fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true )
8156
8157 << new QgsStaticExpressionFunction( QStringLiteral( "count" ), aggParams, fcnAggregateCount, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8158 << new QgsStaticExpressionFunction( QStringLiteral( "count_distinct" ), aggParams, fcnAggregateCountDistinct, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8159 << new QgsStaticExpressionFunction( QStringLiteral( "count_missing" ), aggParams, fcnAggregateCountMissing, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8160 << new QgsStaticExpressionFunction( QStringLiteral( "minimum" ), aggParams, fcnAggregateMin, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8161 << new QgsStaticExpressionFunction( QStringLiteral( "maximum" ), aggParams, fcnAggregateMax, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8162 << new QgsStaticExpressionFunction( QStringLiteral( "sum" ), aggParams, fcnAggregateSum, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8163 << new QgsStaticExpressionFunction( QStringLiteral( "mean" ), aggParams, fcnAggregateMean, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8164 << new QgsStaticExpressionFunction( QStringLiteral( "median" ), aggParams, fcnAggregateMedian, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8165 << new QgsStaticExpressionFunction( QStringLiteral( "stdev" ), aggParams, fcnAggregateStdev, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8166 << new QgsStaticExpressionFunction( QStringLiteral( "range" ), aggParams, fcnAggregateRange, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8167 << new QgsStaticExpressionFunction( QStringLiteral( "minority" ), aggParams, fcnAggregateMinority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8168 << new QgsStaticExpressionFunction( QStringLiteral( "majority" ), aggParams, fcnAggregateMajority, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8169 << new QgsStaticExpressionFunction( QStringLiteral( "q1" ), aggParams, fcnAggregateQ1, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8170 << new QgsStaticExpressionFunction( QStringLiteral( "q3" ), aggParams, fcnAggregateQ3, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8171 << new QgsStaticExpressionFunction( QStringLiteral( "iqr" ), aggParams, fcnAggregateIQR, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8172 << new QgsStaticExpressionFunction( QStringLiteral( "min_length" ), aggParams, fcnAggregateMinLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8173 << new QgsStaticExpressionFunction( QStringLiteral( "max_length" ), aggParams, fcnAggregateMaxLength, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8174 << new QgsStaticExpressionFunction( QStringLiteral( "collect" ), aggParams, fcnAggregateCollectGeometry, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8175 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate" ), aggParamsConcat, fcnAggregateStringConcat, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8176 << new QgsStaticExpressionFunction( QStringLiteral( "concatenate_unique" ), aggParamsConcat, fcnAggregateStringConcatUnique, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8177 << new QgsStaticExpressionFunction( QStringLiteral( "array_agg" ), aggParamsArray, fcnAggregateArray, QStringLiteral( "Aggregates" ), QString(), false, QSet<QString>(), true )
8178
8179 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_match" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpMatch, QStringList() << QStringLiteral( "Conditionals" ) << QStringLiteral( "String" ) )
8180 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_matches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnRegexpMatches, QStringLiteral( "Arrays" ) )
8181
8182 << new QgsStaticExpressionFunction( QStringLiteral( "now" ), 0, fcnNow, QStringLiteral( "Date and Time" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "$now" ) )
8183 << new QgsStaticExpressionFunction( QStringLiteral( "age" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime1" ) )
8184 << QgsExpressionFunction::Parameter( QStringLiteral( "datetime2" ) ),
8185 fcnAge, QStringLiteral( "Date and Time" ) )
8186 << new QgsStaticExpressionFunction( QStringLiteral( "year" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnYear, QStringLiteral( "Date and Time" ) )
8187 << new QgsStaticExpressionFunction( QStringLiteral( "month" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnMonth, QStringLiteral( "Date and Time" ) )
8188 << new QgsStaticExpressionFunction( QStringLiteral( "week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnWeek, QStringLiteral( "Date and Time" ) )
8189 << new QgsStaticExpressionFunction( QStringLiteral( "day" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDay, QStringLiteral( "Date and Time" ) )
8190 << new QgsStaticExpressionFunction( QStringLiteral( "hour" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnHour, QStringLiteral( "Date and Time" ) )
8191 << new QgsStaticExpressionFunction( QStringLiteral( "minute" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnMinute, QStringLiteral( "Date and Time" ) )
8192 << new QgsStaticExpressionFunction( QStringLiteral( "second" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "datetime" ) ), fcnSeconds, QStringLiteral( "Date and Time" ) )
8193 << new QgsStaticExpressionFunction( QStringLiteral( "epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnEpoch, QStringLiteral( "Date and Time" ) )
8194 << new QgsStaticExpressionFunction( QStringLiteral( "datetime_from_epoch" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "long" ) ), fcnDateTimeFromEpoch, QStringLiteral( "Date and Time" ) )
8195 << new QgsStaticExpressionFunction( QStringLiteral( "day_of_week" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "date" ) ), fcnDayOfWeek, QStringLiteral( "Date and Time" ) )
8196 << new QgsStaticExpressionFunction( QStringLiteral( "make_date" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8197 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8198 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) ),
8199 fcnMakeDate, QStringLiteral( "Date and Time" ) )
8200 << new QgsStaticExpressionFunction( QStringLiteral( "make_time" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8201 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8202 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8203 fcnMakeTime, QStringLiteral( "Date and Time" ) )
8204 << new QgsStaticExpressionFunction( QStringLiteral( "make_datetime" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "year" ) )
8205 << QgsExpressionFunction::Parameter( QStringLiteral( "month" ) )
8206 << QgsExpressionFunction::Parameter( QStringLiteral( "day" ) )
8207 << QgsExpressionFunction::Parameter( QStringLiteral( "hour" ) )
8208 << QgsExpressionFunction::Parameter( QStringLiteral( "minute" ) )
8209 << QgsExpressionFunction::Parameter( QStringLiteral( "second" ) ),
8210 fcnMakeDateTime, QStringLiteral( "Date and Time" ) )
8211 << new QgsStaticExpressionFunction( QStringLiteral( "make_interval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "years" ), true, 0 )
8212 << QgsExpressionFunction::Parameter( QStringLiteral( "months" ), true, 0 )
8213 << QgsExpressionFunction::Parameter( QStringLiteral( "weeks" ), true, 0 )
8214 << QgsExpressionFunction::Parameter( QStringLiteral( "days" ), true, 0 )
8215 << QgsExpressionFunction::Parameter( QStringLiteral( "hours" ), true, 0 )
8216 << QgsExpressionFunction::Parameter( QStringLiteral( "minutes" ), true, 0 )
8217 << QgsExpressionFunction::Parameter( QStringLiteral( "seconds" ), true, 0 ),
8218 fcnMakeInterval, QStringLiteral( "Date and Time" ) )
8219 << new QgsStaticExpressionFunction( QStringLiteral( "lower" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnLower, QStringLiteral( "String" ) )
8220 << new QgsStaticExpressionFunction( QStringLiteral( "upper" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnUpper, QStringLiteral( "String" ) )
8221 << new QgsStaticExpressionFunction( QStringLiteral( "title" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTitle, QStringLiteral( "String" ) )
8222 << new QgsStaticExpressionFunction( QStringLiteral( "trim" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnTrim, QStringLiteral( "String" ) )
8223 << new QgsStaticExpressionFunction( QStringLiteral( "ltrim" ), QgsExpressionFunction::ParameterList()
8224 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8225 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnLTrim, QStringLiteral( "String" ) )
8226 << new QgsStaticExpressionFunction( QStringLiteral( "rtrim" ), QgsExpressionFunction::ParameterList()
8227 << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) )
8228 << QgsExpressionFunction::Parameter( QStringLiteral( "characters" ), true, QStringLiteral( " " ) ), fcnRTrim, QStringLiteral( "String" ) )
8229 << new QgsStaticExpressionFunction( QStringLiteral( "levenshtein" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLevenshtein, QStringLiteral( "Fuzzy Matching" ) )
8230 << new QgsStaticExpressionFunction( QStringLiteral( "longest_common_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnLCS, QStringLiteral( "Fuzzy Matching" ) )
8231 << new QgsStaticExpressionFunction( QStringLiteral( "hamming_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "string2" ) ), fcnHamming, QStringLiteral( "Fuzzy Matching" ) )
8232 << new QgsStaticExpressionFunction( QStringLiteral( "soundex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnSoundex, QStringLiteral( "Fuzzy Matching" ) )
8233 << new QgsStaticExpressionFunction( QStringLiteral( "char" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "code" ) ), fcnChar, QStringLiteral( "String" ) )
8234 << new QgsStaticExpressionFunction( QStringLiteral( "ascii" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnAscii, QStringLiteral( "String" ) )
8235 << new QgsStaticExpressionFunction( QStringLiteral( "wordwrap" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "delimiter" ), true, "" ), fcnWordwrap, QStringLiteral( "String" ) )
8236 << new QgsStaticExpressionFunction( QStringLiteral( "length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ), true, "" ), fcnLength, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "GeometryGroup" ) )
8237 << new QgsStaticExpressionFunction( QStringLiteral( "length3D" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLength3D, QStringLiteral( "GeometryGroup" ) )
8238 << new QgsStaticExpressionFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) )
8239 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_replace" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) )
8240 << QgsExpressionFunction::Parameter( QStringLiteral( "replacement" ) ), fcnRegexpReplace, QStringLiteral( "String" ) )
8241 << new QgsStaticExpressionFunction( QStringLiteral( "regexp_substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "input_string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "regex" ) ), fcnRegexpSubstr, QStringLiteral( "String" ) )
8242 << new QgsStaticExpressionFunction( QStringLiteral( "substr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(),
8243 false, QSet< QString >(), false, QStringList(), true )
8244 << new QgsStaticExpressionFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8245 << new QgsStaticExpressionFunction( QStringLiteral( "strpos" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "haystack" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "needle" ) ), fcnStrpos, QStringLiteral( "String" ) )
8246 << new QgsStaticExpressionFunction( QStringLiteral( "left" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnLeft, QStringLiteral( "String" ) )
8247 << new QgsStaticExpressionFunction( QStringLiteral( "right" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "length" ) ), fcnRight, QStringLiteral( "String" ) )
8248 << new QgsStaticExpressionFunction( QStringLiteral( "rpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnRPad, QStringLiteral( "String" ) )
8249 << new QgsStaticExpressionFunction( QStringLiteral( "lpad" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "fill" ) ), fcnLPad, QStringLiteral( "String" ) )
8250 << new QgsStaticExpressionFunction( QStringLiteral( "format" ), -1, fcnFormatString, QStringLiteral( "String" ) )
8251 << new QgsStaticExpressionFunction( QStringLiteral( "format_number" ), QgsExpressionFunction::ParameterList()
8252 << QgsExpressionFunction::Parameter( QStringLiteral( "number" ) )
8253 << QgsExpressionFunction::Parameter( QStringLiteral( "places" ), true, 0 )
8254 << QgsExpressionFunction::Parameter( QStringLiteral( "language" ), true, QVariant() )
8255 << QgsExpressionFunction::Parameter( QStringLiteral( "omit_group_separators" ), true, false )
8256 << QgsExpressionFunction::Parameter( QStringLiteral( "trim_trailing_zeroes" ), true, false ), fcnFormatNumber, QStringLiteral( "String" ) )
8257 << 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" ) )
8258 << new QgsStaticExpressionFunction( QStringLiteral( "color_grayscale_average" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ), fcnColorGrayscaleAverage, QStringLiteral( "Color" ) )
8259 << new QgsStaticExpressionFunction( QStringLiteral( "color_mix_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color1" ) )
8260 << QgsExpressionFunction::Parameter( QStringLiteral( "color2" ) )
8261 << QgsExpressionFunction::Parameter( QStringLiteral( "ratio" ) ),
8262 fcnColorMixRgb, QStringLiteral( "Color" ) )
8263 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8264 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8265 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) ),
8266 fcnColorRgb, QStringLiteral( "Color" ) )
8267 << new QgsStaticExpressionFunction( QStringLiteral( "color_rgba" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "red" ) )
8268 << QgsExpressionFunction::Parameter( QStringLiteral( "green" ) )
8269 << QgsExpressionFunction::Parameter( QStringLiteral( "blue" ) )
8270 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8271 fncColorRgba, QStringLiteral( "Color" ) )
8272 << new QgsStaticExpressionFunction( QStringLiteral( "ramp_color" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "ramp_name" ) )
8273 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8274 fcnRampColor, QStringLiteral( "Color" ) )
8275 << new QgsStaticExpressionFunction( QStringLiteral( "create_ramp" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
8276 << QgsExpressionFunction::Parameter( QStringLiteral( "discrete" ), true, false ),
8277 fcnCreateRamp, QStringLiteral( "Color" ) )
8278 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8279 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8280 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) ),
8281 fcnColorHsl, QStringLiteral( "Color" ) )
8282 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsla" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8283 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8284 << QgsExpressionFunction::Parameter( QStringLiteral( "lightness" ) )
8285 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8286 fncColorHsla, QStringLiteral( "Color" ) )
8287 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsv" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8288 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8289 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8290 fcnColorHsv, QStringLiteral( "Color" ) )
8291 << new QgsStaticExpressionFunction( QStringLiteral( "color_hsva" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "hue" ) )
8292 << QgsExpressionFunction::Parameter( QStringLiteral( "saturation" ) )
8293 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
8294 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8295 fncColorHsva, QStringLiteral( "Color" ) )
8296 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyk" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8297 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8298 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8299 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) ),
8300 fcnColorCmyk, QStringLiteral( "Color" ) )
8301 << new QgsStaticExpressionFunction( QStringLiteral( "color_cmyka" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "cyan" ) )
8302 << QgsExpressionFunction::Parameter( QStringLiteral( "magenta" ) )
8303 << QgsExpressionFunction::Parameter( QStringLiteral( "yellow" ) )
8304 << QgsExpressionFunction::Parameter( QStringLiteral( "black" ) )
8305 << QgsExpressionFunction::Parameter( QStringLiteral( "alpha" ) ),
8306 fncColorCmyka, QStringLiteral( "Color" ) )
8307 << new QgsStaticExpressionFunction( QStringLiteral( "color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8308 << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ),
8309 fncColorPart, QStringLiteral( "Color" ) )
8310 << new QgsStaticExpressionFunction( QStringLiteral( "darker" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8311 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8312 fncDarker, QStringLiteral( "Color" ) )
8313 << new QgsStaticExpressionFunction( QStringLiteral( "lighter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) )
8314 << QgsExpressionFunction::Parameter( QStringLiteral( "factor" ) ),
8315 fncLighter, QStringLiteral( "Color" ) )
8316 << new QgsStaticExpressionFunction( QStringLiteral( "set_color_part" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "color" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "component" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fncSetColorPart, QStringLiteral( "Color" ) )
8317
8318 // file info
8319 << new QgsStaticExpressionFunction( QStringLiteral( "base_file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8320 fcnBaseFileName, QStringLiteral( "Files and Paths" ) )
8321 << new QgsStaticExpressionFunction( QStringLiteral( "file_suffix" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8322 fcnFileSuffix, QStringLiteral( "Files and Paths" ) )
8323 << new QgsStaticExpressionFunction( QStringLiteral( "file_exists" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8324 fcnFileExists, QStringLiteral( "Files and Paths" ) )
8325 << new QgsStaticExpressionFunction( QStringLiteral( "file_name" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8326 fcnFileName, QStringLiteral( "Files and Paths" ) )
8327 << new QgsStaticExpressionFunction( QStringLiteral( "is_file" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8328 fcnPathIsFile, QStringLiteral( "Files and Paths" ) )
8329 << new QgsStaticExpressionFunction( QStringLiteral( "is_directory" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8330 fcnPathIsDir, QStringLiteral( "Files and Paths" ) )
8331 << new QgsStaticExpressionFunction( QStringLiteral( "file_path" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8332 fcnFilePath, QStringLiteral( "Files and Paths" ) )
8333 << new QgsStaticExpressionFunction( QStringLiteral( "file_size" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8334 fcnFileSize, QStringLiteral( "Files and Paths" ) )
8335
8336 << new QgsStaticExpressionFunction( QStringLiteral( "exif" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tag" ), true ),
8337 fcnExif, QStringLiteral( "Files and Paths" ) )
8338 << new QgsStaticExpressionFunction( QStringLiteral( "exif_geotag" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "path" ) ),
8339 fcnExifGeoTag, QStringLiteral( "GeometryGroup" ) )
8340
8341 // hash
8342 << new QgsStaticExpressionFunction( QStringLiteral( "hash" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "method" ) ),
8343 fcnGenericHash, QStringLiteral( "Conversions" ) )
8344 << new QgsStaticExpressionFunction( QStringLiteral( "md5" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8345 fcnHashMd5, QStringLiteral( "Conversions" ) )
8346 << new QgsStaticExpressionFunction( QStringLiteral( "sha256" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8347 fcnHashSha256, QStringLiteral( "Conversions" ) )
8348
8349 //base64
8350 << new QgsStaticExpressionFunction( QStringLiteral( "to_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ),
8351 fcnToBase64, QStringLiteral( "Conversions" ) )
8352 << new QgsStaticExpressionFunction( QStringLiteral( "from_base64" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ),
8353 fcnFromBase64, QStringLiteral( "Conversions" ) )
8354
8355 // deprecated stuff - hidden from users
8356 << new QgsStaticExpressionFunction( QStringLiteral( "$scale" ), QgsExpressionFunction::ParameterList(), fcnMapScale, QStringLiteral( "deprecated" ) );
8357
8358 QgsStaticExpressionFunction *geomFunc = new QgsStaticExpressionFunction( QStringLiteral( "$geometry" ), 0, fcnGeometry, QStringLiteral( "GeometryGroup" ), QString(), true );
8359 geomFunc->setIsStatic( false );
8360 functions << geomFunc;
8361
8362 QgsStaticExpressionFunction *areaFunc = new QgsStaticExpressionFunction( QStringLiteral( "$area" ), 0, fcnGeomArea, QStringLiteral( "GeometryGroup" ), QString(), true );
8363 areaFunc->setIsStatic( false );
8364 functions << areaFunc;
8365
8366 functions << new QgsStaticExpressionFunction( QStringLiteral( "area" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnArea, QStringLiteral( "GeometryGroup" ) );
8367
8368 QgsStaticExpressionFunction *lengthFunc = new QgsStaticExpressionFunction( QStringLiteral( "$length" ), 0, fcnGeomLength, QStringLiteral( "GeometryGroup" ), QString(), true );
8369 lengthFunc->setIsStatic( false );
8370 functions << lengthFunc;
8371
8372 QgsStaticExpressionFunction *perimeterFunc = new QgsStaticExpressionFunction( QStringLiteral( "$perimeter" ), 0, fcnGeomPerimeter, QStringLiteral( "GeometryGroup" ), QString(), true );
8373 perimeterFunc->setIsStatic( false );
8374 functions << perimeterFunc;
8375
8376 functions << new QgsStaticExpressionFunction( QStringLiteral( "perimeter" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPerimeter, QStringLiteral( "GeometryGroup" ) );
8377
8378 functions << new QgsStaticExpressionFunction( QStringLiteral( "roundness" ),
8380 fcnRoundness, QStringLiteral( "GeometryGroup" ) );
8381
8382 QgsStaticExpressionFunction *xFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x" ), 0, fcnX, QStringLiteral( "GeometryGroup" ), QString(), true );
8383 xFunc->setIsStatic( false );
8384 functions << xFunc;
8385
8386 QgsStaticExpressionFunction *yFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y" ), 0, fcnY, QStringLiteral( "GeometryGroup" ), QString(), true );
8387 yFunc->setIsStatic( false );
8388 functions << yFunc;
8389
8390 QgsStaticExpressionFunction *zFunc = new QgsStaticExpressionFunction( QStringLiteral( "$z" ), 0, fcnZ, QStringLiteral( "GeometryGroup" ), QString(), true );
8391 zFunc->setIsStatic( false );
8392 functions << zFunc;
8393
8394 QMap< QString, QgsExpressionFunction::FcnEval > geometry_overlay_definitions
8395 {
8396 { QStringLiteral( "overlay_intersects" ), fcnGeomOverlayIntersects },
8397 { QStringLiteral( "overlay_contains" ), fcnGeomOverlayContains },
8398 { QStringLiteral( "overlay_crosses" ), fcnGeomOverlayCrosses },
8399 { QStringLiteral( "overlay_equals" ), fcnGeomOverlayEquals },
8400 { QStringLiteral( "overlay_touches" ), fcnGeomOverlayTouches },
8401 { QStringLiteral( "overlay_disjoint" ), fcnGeomOverlayDisjoint },
8402 { QStringLiteral( "overlay_within" ), fcnGeomOverlayWithin },
8403 };
8404 QMapIterator< QString, QgsExpressionFunction::FcnEval > i( geometry_overlay_definitions );
8405 while ( i.hasNext() )
8406 {
8407 i.next();
8409 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8410 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8411 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8412 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( -1 ), true )
8413 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false )
8414 << QgsExpressionFunction::Parameter( QStringLiteral( "min_overlap" ), true, QVariant( -1 ), false )
8415 << QgsExpressionFunction::Parameter( QStringLiteral( "min_inscribed_circle_radius" ), true, QVariant( -1 ), false )
8416 << QgsExpressionFunction::Parameter( QStringLiteral( "return_details" ), true, false, false )
8417 << QgsExpressionFunction::Parameter( QStringLiteral( "sort_by_intersection_size" ), true, QString(), false ),
8418 i.value(), QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8419
8420 // The current feature is accessed for the geometry, so this should not be cached
8421 fcnGeomOverlayFunc->setIsStatic( false );
8422 functions << fcnGeomOverlayFunc;
8423 }
8424
8425 QgsStaticExpressionFunction *fcnGeomOverlayNearestFunc = new QgsStaticExpressionFunction( QStringLiteral( "overlay_nearest" ), QgsExpressionFunction::ParameterList()
8426 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8427 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ), true, QVariant(), true )
8428 << QgsExpressionFunction::Parameter( QStringLiteral( "filter" ), true, QVariant(), true )
8429 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, QVariant( 1 ), true )
8430 << QgsExpressionFunction::Parameter( QStringLiteral( "max_distance" ), true, 0 )
8431 << QgsExpressionFunction::Parameter( QStringLiteral( "cache" ), true, QVariant( false ), false ),
8432 fcnGeomOverlayNearest, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES, true );
8433 // The current feature is accessed for the geometry, so this should not be cached
8434 fcnGeomOverlayNearestFunc->setIsStatic( false );
8435 functions << fcnGeomOverlayNearestFunc;
8436
8437 functions
8438 << new QgsStaticExpressionFunction( QStringLiteral( "is_valid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomIsValid, QStringLiteral( "GeometryGroup" ) )
8439 << new QgsStaticExpressionFunction( QStringLiteral( "x" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomX, QStringLiteral( "GeometryGroup" ) )
8440 << new QgsStaticExpressionFunction( QStringLiteral( "y" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomY, QStringLiteral( "GeometryGroup" ) )
8441 << new QgsStaticExpressionFunction( QStringLiteral( "z" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomZ, QStringLiteral( "GeometryGroup" ) )
8442 << new QgsStaticExpressionFunction( QStringLiteral( "m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomM, QStringLiteral( "GeometryGroup" ) )
8443 << new QgsStaticExpressionFunction( QStringLiteral( "point_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ), fcnPointN, QStringLiteral( "GeometryGroup" ) )
8444 << new QgsStaticExpressionFunction( QStringLiteral( "start_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnStartPoint, QStringLiteral( "GeometryGroup" ) )
8445 << new QgsStaticExpressionFunction( QStringLiteral( "end_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnEndPoint, QStringLiteral( "GeometryGroup" ) )
8446 << new QgsStaticExpressionFunction( QStringLiteral( "nodes_to_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8447 << QgsExpressionFunction::Parameter( QStringLiteral( "ignore_closing_nodes" ), true, false ),
8448 fcnNodesToPoints, QStringLiteral( "GeometryGroup" ) )
8449 << new QgsStaticExpressionFunction( QStringLiteral( "segments_to_lines" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnSegmentsToLines, QStringLiteral( "GeometryGroup" ) )
8450 << new QgsStaticExpressionFunction( QStringLiteral( "collect_geometries" ), -1, fcnCollectGeometries, QStringLiteral( "GeometryGroup" ) )
8451 << new QgsStaticExpressionFunction( QStringLiteral( "make_point" ), -1, fcnMakePoint, QStringLiteral( "GeometryGroup" ) )
8452 << new QgsStaticExpressionFunction( QStringLiteral( "make_point_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
8453 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) )
8454 << QgsExpressionFunction::Parameter( QStringLiteral( "m" ) ),
8455 fcnMakePointM, QStringLiteral( "GeometryGroup" ) )
8456 << new QgsStaticExpressionFunction( QStringLiteral( "make_line" ), -1, fcnMakeLine, QStringLiteral( "GeometryGroup" ) )
8457 << new QgsStaticExpressionFunction( QStringLiteral( "make_polygon" ), -1, fcnMakePolygon, QStringLiteral( "GeometryGroup" ) )
8458 << new QgsStaticExpressionFunction( QStringLiteral( "make_triangle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8459 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8460 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) ),
8461 fcnMakeTriangle, QStringLiteral( "GeometryGroup" ) )
8462 << new QgsStaticExpressionFunction( QStringLiteral( "make_circle" ), QgsExpressionFunction::ParameterList()
8463 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8464 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8465 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8466 fcnMakeCircle, QStringLiteral( "GeometryGroup" ) )
8467 << new QgsStaticExpressionFunction( QStringLiteral( "make_ellipse" ), QgsExpressionFunction::ParameterList()
8468 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8469 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_major_axis" ) )
8470 << QgsExpressionFunction::Parameter( QStringLiteral( "semi_minor_axis" ) )
8471 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
8472 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8473 fcnMakeEllipse, QStringLiteral( "GeometryGroup" ) )
8474 << new QgsStaticExpressionFunction( QStringLiteral( "make_regular_polygon" ), QgsExpressionFunction::ParameterList()
8475 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8476 << QgsExpressionFunction::Parameter( QStringLiteral( "radius" ) )
8477 << QgsExpressionFunction::Parameter( QStringLiteral( "number_sides" ) )
8478 << QgsExpressionFunction::Parameter( QStringLiteral( "circle" ), true, 0 ),
8479 fcnMakeRegularPolygon, QStringLiteral( "GeometryGroup" ) )
8480 << new QgsStaticExpressionFunction( QStringLiteral( "make_square" ), QgsExpressionFunction::ParameterList()
8481 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8482 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) ),
8483 fcnMakeSquare, QStringLiteral( "GeometryGroup" ) )
8484 << new QgsStaticExpressionFunction( QStringLiteral( "make_rectangle_3points" ), QgsExpressionFunction::ParameterList()
8485 << QgsExpressionFunction::Parameter( QStringLiteral( "point1" ) )
8486 << QgsExpressionFunction::Parameter( QStringLiteral( "point2" ) )
8487 << QgsExpressionFunction::Parameter( QStringLiteral( "point3" ) )
8488 << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, 0 ),
8489 fcnMakeRectangleFrom3Points, QStringLiteral( "GeometryGroup" ) )
8490 << new QgsStaticExpressionFunction( QStringLiteral( "make_valid" ), QgsExpressionFunction::ParameterList
8491 {
8492 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8493#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<10
8494 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "linework" ) ),
8495#else
8496 QgsExpressionFunction::Parameter( QStringLiteral( "method" ), true, QStringLiteral( "structure" ) ),
8497#endif
8498 QgsExpressionFunction::Parameter( QStringLiteral( "keep_collapsed" ), true, false )
8499 }, fcnGeomMakeValid, QStringLiteral( "GeometryGroup" ) );
8500
8501 functions << new QgsStaticExpressionFunction( QStringLiteral( "x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnXat, QStringLiteral( "GeometryGroup" ) );
8502 functions << new QgsStaticExpressionFunction( QStringLiteral( "y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ), true ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnYat, QStringLiteral( "GeometryGroup" ) );
8503 functions << new QgsStaticExpressionFunction( QStringLiteral( "z_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnZat, QStringLiteral( "GeometryGroup" ) );
8504 functions << new QgsStaticExpressionFunction( QStringLiteral( "m_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ), true ), fcnMat, QStringLiteral( "GeometryGroup" ) );
8505
8506 QgsStaticExpressionFunction *xAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$x_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldXat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "xat" ) );
8507 xAtFunc->setIsStatic( false );
8508 functions << xAtFunc;
8509
8510
8511 QgsStaticExpressionFunction *yAtFunc = new QgsStaticExpressionFunction( QStringLiteral( "$y_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnOldYat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet<QString>(), false, QStringList() << QStringLiteral( "yat" ) );
8512 yAtFunc->setIsStatic( false );
8513 functions << yAtFunc;
8514
8515 functions
8516 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_type" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeometryType, QStringLiteral( "GeometryGroup" ) )
8517 << new QgsStaticExpressionFunction( QStringLiteral( "x_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmin" ) )
8518 << new QgsStaticExpressionFunction( QStringLiteral( "x_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnXMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "xmax" ) )
8519 << new QgsStaticExpressionFunction( QStringLiteral( "y_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymin" ) )
8520 << new QgsStaticExpressionFunction( QStringLiteral( "y_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnYMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "ymax" ) )
8521 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "text" ) ), fcnGeomFromWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromWKT" ) )
8522 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "binary" ) ), fcnGeomFromWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
8523 << new QgsStaticExpressionFunction( QStringLiteral( "geom_from_gml" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "gml" ) ), fcnGeomFromGML, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomFromGML" ) )
8524 << new QgsStaticExpressionFunction( QStringLiteral( "flip_coordinates" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnFlipCoordinates, QStringLiteral( "GeometryGroup" ) )
8525 << new QgsStaticExpressionFunction( QStringLiteral( "relate" ), -1, fcnRelate, QStringLiteral( "GeometryGroup" ) )
8526 << 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" ) )
8527 << new QgsStaticExpressionFunction( QStringLiteral( "disjoint" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8528 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8529 fcnDisjoint, QStringLiteral( "GeometryGroup" ) )
8530 << new QgsStaticExpressionFunction( QStringLiteral( "intersects" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8531 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8532 fcnIntersects, QStringLiteral( "GeometryGroup" ) )
8533 << new QgsStaticExpressionFunction( QStringLiteral( "touches" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8534 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8535 fcnTouches, QStringLiteral( "GeometryGroup" ) )
8536 << new QgsStaticExpressionFunction( QStringLiteral( "crosses" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8537 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8538 fcnCrosses, QStringLiteral( "GeometryGroup" ) )
8539 << new QgsStaticExpressionFunction( QStringLiteral( "contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8540 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8541 fcnContains, QStringLiteral( "GeometryGroup" ) )
8542 << new QgsStaticExpressionFunction( QStringLiteral( "overlaps" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8543 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8544 fcnOverlaps, QStringLiteral( "GeometryGroup" ) )
8545 << new QgsStaticExpressionFunction( QStringLiteral( "within" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8546 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8547 fcnWithin, QStringLiteral( "GeometryGroup" ) )
8548 << new QgsStaticExpressionFunction( QStringLiteral( "translate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8549 << QgsExpressionFunction::Parameter( QStringLiteral( "dx" ) )
8550 << QgsExpressionFunction::Parameter( QStringLiteral( "dy" ) ),
8551 fcnTranslate, QStringLiteral( "GeometryGroup" ) )
8552 << new QgsStaticExpressionFunction( QStringLiteral( "rotate" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8553 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation" ) )
8554 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true )
8555 << QgsExpressionFunction::Parameter( QStringLiteral( "per_part" ), true, false ),
8556 fcnRotate, QStringLiteral( "GeometryGroup" ) )
8557 << new QgsStaticExpressionFunction( QStringLiteral( "scale" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8558 << QgsExpressionFunction::Parameter( QStringLiteral( "x_scale" ) )
8559 << QgsExpressionFunction::Parameter( QStringLiteral( "y_scale" ) )
8560 << QgsExpressionFunction::Parameter( QStringLiteral( "center" ), true ),
8561 fcnScale, QStringLiteral( "GeometryGroup" ) )
8562 << new QgsStaticExpressionFunction( QStringLiteral( "affine_transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8563 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_x" ) )
8564 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_y" ) )
8565 << QgsExpressionFunction::Parameter( QStringLiteral( "rotation_z" ) )
8566 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_x" ) )
8567 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_y" ) )
8568 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_z" ), true, 0 )
8569 << QgsExpressionFunction::Parameter( QStringLiteral( "delta_m" ), true, 0 )
8570 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_z" ), true, 1 )
8571 << QgsExpressionFunction::Parameter( QStringLiteral( "scale_m" ), true, 1 ),
8572 fcnAffineTransform, QStringLiteral( "GeometryGroup" ) )
8573 << new QgsStaticExpressionFunction( QStringLiteral( "buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8574 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8575 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8 )
8576 << QgsExpressionFunction::Parameter( QStringLiteral( "cap" ), true, QStringLiteral( "round" ) )
8577 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, QStringLiteral( "round" ) )
8578 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2 ),
8579 fcnBuffer, QStringLiteral( "GeometryGroup" ) )
8580 << new QgsStaticExpressionFunction( QStringLiteral( "force_rhr" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8581 fcnForceRHR, QStringLiteral( "GeometryGroup" ) )
8582 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_cw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8583 fcnForcePolygonCW, QStringLiteral( "GeometryGroup" ) )
8584 << new QgsStaticExpressionFunction( QStringLiteral( "force_polygon_ccw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8585 fcnForcePolygonCCW, QStringLiteral( "GeometryGroup" ) )
8586 << new QgsStaticExpressionFunction( QStringLiteral( "wedge_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "center" ) )
8587 << QgsExpressionFunction::Parameter( QStringLiteral( "azimuth" ) )
8588 << QgsExpressionFunction::Parameter( QStringLiteral( "width" ) )
8589 << QgsExpressionFunction::Parameter( QStringLiteral( "outer_radius" ) )
8590 << QgsExpressionFunction::Parameter( QStringLiteral( "inner_radius" ), true, 0.0 ), fcnWedgeBuffer, QStringLiteral( "GeometryGroup" ) )
8591 << new QgsStaticExpressionFunction( QStringLiteral( "tapered_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8592 << QgsExpressionFunction::Parameter( QStringLiteral( "start_width" ) )
8593 << QgsExpressionFunction::Parameter( QStringLiteral( "end_width" ) )
8594 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8595 , fcnTaperedBuffer, QStringLiteral( "GeometryGroup" ) )
8596 << new QgsStaticExpressionFunction( QStringLiteral( "buffer_by_m" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8597 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8598 , fcnBufferByM, QStringLiteral( "GeometryGroup" ) )
8599 << new QgsStaticExpressionFunction( QStringLiteral( "offset_curve" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8600 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8601 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8602 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
8603 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
8604 fcnOffsetCurve, QStringLiteral( "GeometryGroup" ) )
8605 << new QgsStaticExpressionFunction( QStringLiteral( "single_sided_buffer" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8606 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8607 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 8.0 )
8608 << QgsExpressionFunction::Parameter( QStringLiteral( "join" ), true, static_cast< int >( Qgis::JoinStyle::Round ) )
8609 << QgsExpressionFunction::Parameter( QStringLiteral( "miter_limit" ), true, 2.0 ),
8610 fcnSingleSidedBuffer, QStringLiteral( "GeometryGroup" ) )
8611 << new QgsStaticExpressionFunction( QStringLiteral( "extend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8612 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) )
8613 << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ),
8614 fcnExtend, QStringLiteral( "GeometryGroup" ) )
8615 << new QgsStaticExpressionFunction( QStringLiteral( "centroid" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCentroid, QStringLiteral( "GeometryGroup" ) )
8616 << new QgsStaticExpressionFunction( QStringLiteral( "point_on_surface" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) )
8617 << new QgsStaticExpressionFunction( QStringLiteral( "pole_of_inaccessibility" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8618 << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnPoleOfInaccessibility, QStringLiteral( "GeometryGroup" ) )
8619 << new QgsStaticExpressionFunction( QStringLiteral( "reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnReverse, QStringLiteral( "GeometryGroup" ) )
8620 << new QgsStaticExpressionFunction( QStringLiteral( "exterior_ring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnExteriorRing, QStringLiteral( "GeometryGroup" ) )
8621 << new QgsStaticExpressionFunction( QStringLiteral( "interior_ring_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8622 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
8623 fcnInteriorRingN, QStringLiteral( "GeometryGroup" ) )
8624 << new QgsStaticExpressionFunction( QStringLiteral( "geometry_n" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8625 << QgsExpressionFunction::Parameter( QStringLiteral( "index" ) ),
8626 fcnGeometryN, QStringLiteral( "GeometryGroup" ) )
8627 << new QgsStaticExpressionFunction( QStringLiteral( "boundary" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundary, QStringLiteral( "GeometryGroup" ) )
8628 << new QgsStaticExpressionFunction( QStringLiteral( "line_merge" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnLineMerge, QStringLiteral( "GeometryGroup" ) )
8629 << new QgsStaticExpressionFunction( QStringLiteral( "shared_paths" ), QgsExpressionFunction::ParameterList
8630 {
8631 QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ),
8632 QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
8633 }, fcnSharedPaths, QStringLiteral( "GeometryGroup" ) )
8634 << new QgsStaticExpressionFunction( QStringLiteral( "bounds" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBounds, QStringLiteral( "GeometryGroup" ) )
8635 << new QgsStaticExpressionFunction( QStringLiteral( "simplify" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplify, QStringLiteral( "GeometryGroup" ) )
8636 << new QgsStaticExpressionFunction( QStringLiteral( "simplify_vw" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "tolerance" ) ), fcnSimplifyVW, QStringLiteral( "GeometryGroup" ) )
8637 << new QgsStaticExpressionFunction( QStringLiteral( "smooth" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "iterations" ), true, 1 )
8638 << QgsExpressionFunction::Parameter( QStringLiteral( "offset" ), true, 0.25 )
8639 << QgsExpressionFunction::Parameter( QStringLiteral( "min_length" ), true, -1 )
8640 << QgsExpressionFunction::Parameter( QStringLiteral( "max_angle" ), true, 180 ), fcnSmooth, QStringLiteral( "GeometryGroup" ) )
8641 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave" ),
8642 {
8643 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8644 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8645 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8646 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8647 }, fcnTriangularWave, QStringLiteral( "GeometryGroup" ) )
8648 << new QgsStaticExpressionFunction( QStringLiteral( "triangular_wave_randomized" ),
8649 {
8650 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8651 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8652 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8653 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8654 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8655 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8656 }, fcnTriangularWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8657 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave" ),
8658 {
8659 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8660 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8661 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8662 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8663 }, fcnSquareWave, QStringLiteral( "GeometryGroup" ) )
8664 << new QgsStaticExpressionFunction( QStringLiteral( "square_wave_randomized" ),
8665 {
8666 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8667 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8668 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8669 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8670 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8671 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8672 }, fcnSquareWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8673 << new QgsStaticExpressionFunction( QStringLiteral( "wave" ),
8674 {
8675 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8676 QgsExpressionFunction::Parameter( QStringLiteral( "wavelength" ) ),
8677 QgsExpressionFunction::Parameter( QStringLiteral( "amplitude" ) ),
8678 QgsExpressionFunction::Parameter( QStringLiteral( "strict" ), true, false )
8679 }, fcnRoundWave, QStringLiteral( "GeometryGroup" ) )
8680 << new QgsStaticExpressionFunction( QStringLiteral( "wave_randomized" ),
8681 {
8682 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8683 QgsExpressionFunction::Parameter( QStringLiteral( "min_wavelength" ) ),
8684 QgsExpressionFunction::Parameter( QStringLiteral( "max_wavelength" ) ),
8685 QgsExpressionFunction::Parameter( QStringLiteral( "min_amplitude" ) ),
8686 QgsExpressionFunction::Parameter( QStringLiteral( "max_amplitude" ) ),
8687 QgsExpressionFunction::Parameter( QStringLiteral( "seed" ), true, 0 )
8688 }, fcnRoundWaveRandomized, QStringLiteral( "GeometryGroup" ) )
8689 << new QgsStaticExpressionFunction( QStringLiteral( "apply_dash_pattern" ),
8690 {
8691 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8692 QgsExpressionFunction::Parameter( QStringLiteral( "pattern" ) ),
8693 QgsExpressionFunction::Parameter( QStringLiteral( "start_rule" ), true, QStringLiteral( "no_rule" ) ),
8694 QgsExpressionFunction::Parameter( QStringLiteral( "end_rule" ), true, QStringLiteral( "no_rule" ) ),
8695 QgsExpressionFunction::Parameter( QStringLiteral( "adjustment" ), true, QStringLiteral( "both" ) ),
8696 QgsExpressionFunction::Parameter( QStringLiteral( "pattern_offset" ), true, 0 ),
8697 }, fcnApplyDashPattern, QStringLiteral( "GeometryGroup" ) )
8698 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_count" ),
8699 {
8700 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8701 QgsExpressionFunction::Parameter( QStringLiteral( "vertices" ) )
8702 }, fcnDensifyByCount, QStringLiteral( "GeometryGroup" ) )
8703 << new QgsStaticExpressionFunction( QStringLiteral( "densify_by_distance" ),
8704 {
8705 QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8706 QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) )
8707 }, fcnDensifyByDistance, QStringLiteral( "GeometryGroup" ) )
8708 << new QgsStaticExpressionFunction( QStringLiteral( "num_points" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumPoints, QStringLiteral( "GeometryGroup" ) )
8709 << new QgsStaticExpressionFunction( QStringLiteral( "num_interior_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumInteriorRings, QStringLiteral( "GeometryGroup" ) )
8710 << new QgsStaticExpressionFunction( QStringLiteral( "num_rings" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumRings, QStringLiteral( "GeometryGroup" ) )
8711 << new QgsStaticExpressionFunction( QStringLiteral( "num_geometries" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnGeomNumGeometries, QStringLiteral( "GeometryGroup" ) )
8712 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_width" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsWidth, QStringLiteral( "GeometryGroup" ) )
8713 << new QgsStaticExpressionFunction( QStringLiteral( "bounds_height" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnBoundsHeight, QStringLiteral( "GeometryGroup" ) )
8714 << new QgsStaticExpressionFunction( QStringLiteral( "is_closed" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsClosed, QStringLiteral( "GeometryGroup" ) )
8715 << new QgsStaticExpressionFunction( QStringLiteral( "close_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnCloseLine, QStringLiteral( "GeometryGroup" ) )
8716 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmpty, QStringLiteral( "GeometryGroup" ) )
8717 << new QgsStaticExpressionFunction( QStringLiteral( "is_empty_or_null" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnIsEmptyOrNull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList(), true )
8718 << new QgsStaticExpressionFunction( QStringLiteral( "convex_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ), fcnConvexHull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "convexHull" ) )
8719#if GEOS_VERSION_MAJOR>3 || ( GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR>=11 )
8720 << new QgsStaticExpressionFunction( QStringLiteral( "concave_hull" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8721 << QgsExpressionFunction::Parameter( QStringLiteral( "target_percent" ) )
8722 << QgsExpressionFunction::Parameter( QStringLiteral( "allow_holes" ), true, false ), fcnConcaveHull, QStringLiteral( "GeometryGroup" ) )
8723#endif
8724 << new QgsStaticExpressionFunction( QStringLiteral( "oriented_bbox" ), QgsExpressionFunction::ParameterList()
8725 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8726 fcnOrientedBBox, QStringLiteral( "GeometryGroup" ) )
8727 << new QgsStaticExpressionFunction( QStringLiteral( "main_angle" ), QgsExpressionFunction::ParameterList()
8728 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8729 fcnMainAngle, QStringLiteral( "GeometryGroup" ) )
8730 << new QgsStaticExpressionFunction( QStringLiteral( "minimal_circle" ), QgsExpressionFunction::ParameterList()
8731 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8732 << QgsExpressionFunction::Parameter( QStringLiteral( "segments" ), true, 36 ),
8733 fcnMinimalCircle, QStringLiteral( "GeometryGroup" ) )
8734 << new QgsStaticExpressionFunction( QStringLiteral( "difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8735 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8736 fcnDifference, QStringLiteral( "GeometryGroup" ) )
8737 << new QgsStaticExpressionFunction( QStringLiteral( "distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8738 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8739 fcnDistance, QStringLiteral( "GeometryGroup" ) )
8740 << new QgsStaticExpressionFunction( QStringLiteral( "hausdorff_distance" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) )
8741 << QgsExpressionFunction::Parameter( QStringLiteral( "densify_fraction" ), true ),
8742 fcnHausdorffDistance, QStringLiteral( "GeometryGroup" ) )
8743 << new QgsStaticExpressionFunction( QStringLiteral( "intersection" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8744 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8745 fcnIntersection, QStringLiteral( "GeometryGroup" ) )
8746 << new QgsStaticExpressionFunction( QStringLiteral( "sym_difference" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8747 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8748 fcnSymDifference, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "symDifference" ) )
8749 << new QgsStaticExpressionFunction( QStringLiteral( "combine" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8750 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8751 fcnCombine, QStringLiteral( "GeometryGroup" ) )
8752 << new QgsStaticExpressionFunction( QStringLiteral( "union" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8753 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8754 fcnCombine, QStringLiteral( "GeometryGroup" ) )
8755 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkt" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8756 << QgsExpressionFunction::Parameter( QStringLiteral( "precision" ), true, 8.0 ),
8757 fcnGeomToWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "geomToWKT" ) )
8758 << new QgsStaticExpressionFunction( QStringLiteral( "geom_to_wkb" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8759 fcnGeomToWKB, QStringLiteral( "GeometryGroup" ), QString(), false, QSet<QString>(), false )
8760 << new QgsStaticExpressionFunction( QStringLiteral( "geometry" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetGeometry, QStringLiteral( "GeometryGroup" ), QString(), true )
8761 << new QgsStaticExpressionFunction( QStringLiteral( "transform" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8762 << QgsExpressionFunction::Parameter( QStringLiteral( "source_auth_id" ) )
8763 << QgsExpressionFunction::Parameter( QStringLiteral( "dest_auth_id" ) ),
8764 fcnTransformGeometry, QStringLiteral( "GeometryGroup" ) )
8765 << new QgsStaticExpressionFunction( QStringLiteral( "extrude" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8766 << QgsExpressionFunction::Parameter( QStringLiteral( "x" ) )
8767 << QgsExpressionFunction::Parameter( QStringLiteral( "y" ) ),
8768 fcnExtrude, QStringLiteral( "GeometryGroup" ), QString() )
8769 << new QgsStaticExpressionFunction( QStringLiteral( "is_multipart" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8770 fcnGeomIsMultipart, QStringLiteral( "GeometryGroup" ) )
8771 << new QgsStaticExpressionFunction( QStringLiteral( "z_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8772 fcnZMax, QStringLiteral( "GeometryGroup" ) )
8773 << new QgsStaticExpressionFunction( QStringLiteral( "z_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8774 fcnZMin, QStringLiteral( "GeometryGroup" ) )
8775 << new QgsStaticExpressionFunction( QStringLiteral( "m_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8776 fcnMMax, QStringLiteral( "GeometryGroup" ) )
8777 << new QgsStaticExpressionFunction( QStringLiteral( "m_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8778 fcnMMin, QStringLiteral( "GeometryGroup" ) )
8779 << new QgsStaticExpressionFunction( QStringLiteral( "sinuosity" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8780 fcnSinuosity, QStringLiteral( "GeometryGroup" ) )
8781 << new QgsStaticExpressionFunction( QStringLiteral( "straight_distance_2d" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) ),
8782 fcnStraightDistance2d, QStringLiteral( "GeometryGroup" ) );
8783
8784
8785 QgsStaticExpressionFunction *orderPartsFunc = new QgsStaticExpressionFunction( QStringLiteral( "order_parts" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8786 << QgsExpressionFunction::Parameter( QStringLiteral( "orderby" ) )
8787 << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ),
8788 fcnOrderParts, QStringLiteral( "GeometryGroup" ), QString() );
8789
8790 orderPartsFunc->setIsStaticFunction(
8791 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
8792 {
8793 const QList< QgsExpressionNode *> argList = node->args()->list();
8794 for ( QgsExpressionNode *argNode : argList )
8795 {
8796 if ( !argNode->isStatic( parent, context ) )
8797 return false;
8798 }
8799
8800 if ( node->args()->count() > 1 )
8801 {
8802 QgsExpressionNode *argNode = node->args()->at( 1 );
8803
8804 QString expString = argNode->eval( parent, context ).toString();
8805
8806 QgsExpression e( expString );
8807
8808 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
8809 return true;
8810 }
8811
8812 return true;
8813 } );
8814
8815 orderPartsFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
8816 {
8817 if ( node->args()->count() > 1 )
8818 {
8819 QgsExpressionNode *argNode = node->args()->at( 1 );
8820 QString expression = argNode->eval( parent, context ).toString();
8821 QgsExpression e( expression );
8822 e.prepare( context );
8823 context->setCachedValue( expression, QVariant::fromValue( e ) );
8824 }
8825 return true;
8826 }
8827 );
8828 functions << orderPartsFunc;
8829
8830 functions
8831 << new QgsStaticExpressionFunction( QStringLiteral( "closest_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8832 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8833 fcnClosestPoint, QStringLiteral( "GeometryGroup" ) )
8834 << new QgsStaticExpressionFunction( QStringLiteral( "shortest_line" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry1" ) )
8835 << QgsExpressionFunction::Parameter( QStringLiteral( "geometry2" ) ),
8836 fcnShortestLine, QStringLiteral( "GeometryGroup" ) )
8837 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8838 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolatePoint, QStringLiteral( "GeometryGroup" ) )
8839 << new QgsStaticExpressionFunction( QStringLiteral( "line_interpolate_angle" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8840 << QgsExpressionFunction::Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolateAngle, QStringLiteral( "GeometryGroup" ) )
8841 << new QgsStaticExpressionFunction( QStringLiteral( "line_locate_point" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8842 << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnLineLocatePoint, QStringLiteral( "GeometryGroup" ) )
8843 << new QgsStaticExpressionFunction( QStringLiteral( "angle_at_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8844 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnAngleAtVertex, QStringLiteral( "GeometryGroup" ) )
8845 << new QgsStaticExpressionFunction( QStringLiteral( "distance_to_vertex" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8846 << QgsExpressionFunction::Parameter( QStringLiteral( "vertex" ) ), fcnDistanceToVertex, QStringLiteral( "GeometryGroup" ) )
8847 << new QgsStaticExpressionFunction( QStringLiteral( "line_substring" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometry" ) )
8848 << QgsExpressionFunction::Parameter( QStringLiteral( "start_distance" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_distance" ) ), fcnLineSubset, QStringLiteral( "GeometryGroup" ) );
8849
8850
8851 // **Record** functions
8852
8853 QgsStaticExpressionFunction *idFunc = new QgsStaticExpressionFunction( QStringLiteral( "$id" ), 0, fcnFeatureId, QStringLiteral( "Record and Attributes" ) );
8854 idFunc->setIsStatic( false );
8855 functions << idFunc;
8856
8857 QgsStaticExpressionFunction *currentFeatureFunc = new QgsStaticExpressionFunction( QStringLiteral( "$currentfeature" ), 0, fcnFeature, QStringLiteral( "Record and Attributes" ) );
8858 currentFeatureFunc->setIsStatic( false );
8859 functions << currentFeatureFunc;
8860
8861 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" ) );
8862 uuidFunc->setIsStatic( false );
8863 functions << uuidFunc;
8864
8865 functions
8866 << new QgsStaticExpressionFunction( QStringLiteral( "feature_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ) ), fcnGetFeatureId, QStringLiteral( "Record and Attributes" ), QString(), true )
8867 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8868 << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) )
8869 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ), true ),
8870 fcnGetFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "QgsExpressionUtils::getFeature" ) )
8871 << new QgsStaticExpressionFunction( QStringLiteral( "get_feature_by_id" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8872 << QgsExpressionFunction::Parameter( QStringLiteral( "feature_id" ) ),
8873 fcnGetFeatureById, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>(), false );
8874
8875 QgsStaticExpressionFunction *attributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true ),
8876 fcnAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8877 attributesFunc->setIsStatic( false );
8878 functions << attributesFunc;
8879 QgsStaticExpressionFunction *representAttributesFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_attributes" ), -1,
8880 fcnRepresentAttributes, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8881 representAttributesFunc->setIsStatic( false );
8882 functions << representAttributesFunc;
8883
8884 QgsStaticExpressionFunction *validateFeature = new QgsStaticExpressionFunction( QStringLiteral( "is_feature_valid" ),
8885 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
8886 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
8887 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
8888 fcnValidateFeature, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8889 validateFeature->setIsStatic( false );
8890 functions << validateFeature;
8891
8892 QgsStaticExpressionFunction *validateAttribute = new QgsStaticExpressionFunction( QStringLiteral( "is_attribute_valid" ),
8893 QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ), false )
8894 << QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ), true )
8895 << QgsExpressionFunction::Parameter( QStringLiteral( "feature" ), true )
8896 << QgsExpressionFunction::Parameter( QStringLiteral( "strength" ), true ),
8897 fcnValidateAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
8898 validateAttribute->setIsStatic( false );
8899 functions << validateAttribute;
8900
8902 QStringLiteral( "maptip" ),
8903 -1,
8904 fcnFeatureMaptip,
8905 QStringLiteral( "Record and Attributes" ),
8906 QString(),
8907 false,
8908 QSet<QString>()
8909 );
8910 maptipFunc->setIsStatic( false );
8911 functions << maptipFunc;
8912
8914 QStringLiteral( "display_expression" ),
8915 -1,
8916 fcnFeatureDisplayExpression,
8917 QStringLiteral( "Record and Attributes" ),
8918 QString(),
8919 false,
8920 QSet<QString>()
8921 );
8922 displayFunc->setIsStatic( false );
8923 functions << displayFunc;
8924
8926 QStringLiteral( "is_selected" ),
8927 -1,
8928 fcnIsSelected,
8929 QStringLiteral( "Record and Attributes" ),
8930 QString(),
8931 false,
8932 QSet<QString>()
8933 );
8934 isSelectedFunc->setIsStatic( false );
8935 functions << isSelectedFunc;
8936
8937 functions
8939 QStringLiteral( "num_selected" ),
8940 -1,
8941 fcnNumSelected,
8942 QStringLiteral( "Record and Attributes" ),
8943 QString(),
8944 false,
8945 QSet<QString>()
8946 );
8947
8948 functions
8950 QStringLiteral( "sqlite_fetch_and_increment" ),
8952 << QgsExpressionFunction::Parameter( QStringLiteral( "database" ) )
8953 << QgsExpressionFunction::Parameter( QStringLiteral( "table" ) )
8954 << QgsExpressionFunction::Parameter( QStringLiteral( "id_field" ) )
8955 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_attribute" ) )
8956 << QgsExpressionFunction::Parameter( QStringLiteral( "filter_value" ) )
8957 << QgsExpressionFunction::Parameter( QStringLiteral( "default_values" ), true ),
8958 fcnSqliteFetchAndIncrement,
8959 QStringLiteral( "Record and Attributes" )
8960 );
8961
8962 // **Fields and Values** functions
8963 QgsStaticExpressionFunction *representValueFunc = new QgsStaticExpressionFunction( QStringLiteral( "represent_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "attribute" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "field_name" ), true ), fcnRepresentValue, QStringLiteral( "Record and Attributes" ) );
8964
8965 representValueFunc->setPrepareFunction( []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
8966 {
8967 Q_UNUSED( context )
8968 if ( node->args()->count() == 1 )
8969 {
8970 QgsExpressionNodeColumnRef *colRef = dynamic_cast<QgsExpressionNodeColumnRef *>( node->args()->at( 0 ) );
8971 if ( colRef )
8972 {
8973 return true;
8974 }
8975 else
8976 {
8977 parent->setEvalErrorString( tr( "If represent_value is called with 1 parameter, it must be an attribute." ) );
8978 return false;
8979 }
8980 }
8981 else if ( node->args()->count() == 2 )
8982 {
8983 return true;
8984 }
8985 else
8986 {
8987 parent->setEvalErrorString( tr( "represent_value must be called with exactly 1 or 2 parameters." ) );
8988 return false;
8989 }
8990 }
8991 );
8992
8993 functions << representValueFunc;
8994
8995 // **General** functions
8996 functions
8997 << new QgsStaticExpressionFunction( QStringLiteral( "layer_property" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
8998 << QgsExpressionFunction::Parameter( QStringLiteral( "property" ) ),
8999 fcnGetLayerProperty, QStringLiteral( "Map Layers" ) )
9000 << new QgsStaticExpressionFunction( QStringLiteral( "decode_uri" ),
9002 << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9003 << QgsExpressionFunction::Parameter( QStringLiteral( "part" ), true ),
9004 fcnDecodeUri, QStringLiteral( "Map Layers" ) )
9005 << new QgsStaticExpressionFunction( QStringLiteral( "mime_type" ),
9007 << QgsExpressionFunction::Parameter( QStringLiteral( "binary_data" ) ),
9008 fcnMimeType, QStringLiteral( "General" ) )
9009 << new QgsStaticExpressionFunction( QStringLiteral( "raster_statistic" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) )
9010 << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) )
9011 << QgsExpressionFunction::Parameter( QStringLiteral( "statistic" ) ), fcnGetRasterBandStat, QStringLiteral( "Rasters" ) );
9012
9013 // **var** function
9014 QgsStaticExpressionFunction *varFunction = new QgsStaticExpressionFunction( QStringLiteral( "var" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnGetVariable, QStringLiteral( "General" ) );
9015 varFunction->setIsStaticFunction(
9016 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9017 {
9018 /* A variable node is static if it has a static name and the name can be found at prepare
9019 * time and is tagged with isStatic.
9020 * It is not static if a variable is set during iteration or not tagged isStatic.
9021 * (e.g. geom_part variable)
9022 */
9023 if ( node->args()->count() > 0 )
9024 {
9025 QgsExpressionNode *argNode = node->args()->at( 0 );
9026
9027 if ( !argNode->isStatic( parent, context ) )
9028 return false;
9029
9030 const QString varName = argNode->eval( parent, context ).toString();
9031 if ( varName == QLatin1String( "feature" ) || varName == QLatin1String( "id" ) || varName == QLatin1String( "geometry" ) )
9032 return false;
9033
9034 const QgsExpressionContextScope *scope = context->activeScopeForVariable( varName );
9035 return scope ? scope->isStatic( varName ) : false;
9036 }
9037 return false;
9038 }
9039 );
9040 varFunction->setUsesGeometryFunction(
9041 []( const QgsExpressionNodeFunction * node ) -> bool
9042 {
9043 if ( node && node->args()->count() > 0 )
9044 {
9045 QgsExpressionNode *argNode = node->args()->at( 0 );
9046 if ( QgsExpressionNodeLiteral *literal = dynamic_cast<QgsExpressionNodeLiteral *>( argNode ) )
9047 {
9048 if ( literal->value() == QLatin1String( "geometry" ) || literal->value() == QLatin1String( "feature" ) )
9049 return true;
9050 }
9051 }
9052 return false;
9053 }
9054 );
9055
9056 functions
9057 << varFunction;
9058
9059 functions << new QgsStaticExpressionFunction( QStringLiteral( "eval_template" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "template" ) ), fcnEvalTemplate, QStringLiteral( "General" ), QString(), true );
9060
9061 QgsStaticExpressionFunction *evalFunc = new QgsStaticExpressionFunction( QStringLiteral( "eval" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ), fcnEval, QStringLiteral( "General" ), QString(), true, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9062 evalFunc->setIsStaticFunction(
9063 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9064 {
9065 if ( node->args()->count() > 0 )
9066 {
9067 QgsExpressionNode *argNode = node->args()->at( 0 );
9068
9069 if ( argNode->isStatic( parent, context ) )
9070 {
9071 QString expString = argNode->eval( parent, context ).toString();
9072
9073 QgsExpression e( expString );
9074
9075 if ( e.rootNode() && e.rootNode()->isStatic( parent, context ) )
9076 return true;
9077 }
9078 }
9079
9080 return false;
9081 } );
9082
9083 functions << evalFunc;
9084
9085 QgsStaticExpressionFunction *attributeFunc = new QgsStaticExpressionFunction( QStringLiteral( "attribute" ), -1, fcnAttribute, QStringLiteral( "Record and Attributes" ), QString(), false, QSet<QString>() << QgsFeatureRequest::ALL_ATTRIBUTES );
9086 attributeFunc->setIsStaticFunction(
9087 []( const QgsExpressionNodeFunction * node, QgsExpression * parent, const QgsExpressionContext * context )
9088 {
9089 const QList< QgsExpressionNode *> argList = node->args()->list();
9090 for ( QgsExpressionNode *argNode : argList )
9091 {
9092 if ( !argNode->isStatic( parent, context ) )
9093 return false;
9094 }
9095
9096 if ( node->args()->count() == 1 )
9097 {
9098 // not static -- this is the variant which uses the current feature taken direct from the expression context
9099 return false;
9100 }
9101
9102 return true;
9103 } );
9104 functions << attributeFunc;
9105
9106 functions
9107 << new QgsStaticExpressionFunction( QStringLiteral( "env" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "name" ) ), fcnEnvVar, QStringLiteral( "General" ), QString() )
9109 << new QgsStaticExpressionFunction( QStringLiteral( "raster_value" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterValue, QStringLiteral( "Rasters" ) )
9110 << new QgsStaticExpressionFunction( QStringLiteral( "raster_attributes" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "layer" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "band" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "point" ) ), fcnRasterAttributes, QStringLiteral( "Rasters" ) )
9111
9112 // functions for arrays
9115 << new QgsStaticExpressionFunction( QStringLiteral( "array" ), -1, fcnArray, QStringLiteral( "Arrays" ), QString(), false, QSet<QString>(), false, QStringList(), true )
9116 << new QgsStaticExpressionFunction( QStringLiteral( "array_sort" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "ascending" ), true, true ), fcnArraySort, QStringLiteral( "Arrays" ) )
9117 << new QgsStaticExpressionFunction( QStringLiteral( "array_length" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLength, QStringLiteral( "Arrays" ) )
9118 << new QgsStaticExpressionFunction( QStringLiteral( "array_contains" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayContains, QStringLiteral( "Arrays" ) )
9119 << new QgsStaticExpressionFunction( QStringLiteral( "array_count" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayCount, QStringLiteral( "Arrays" ) )
9120 << new QgsStaticExpressionFunction( QStringLiteral( "array_all" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array_a" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_b" ) ), fcnArrayAll, QStringLiteral( "Arrays" ) )
9121 << new QgsStaticExpressionFunction( QStringLiteral( "array_find" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayFind, QStringLiteral( "Arrays" ) )
9122 << new QgsStaticExpressionFunction( QStringLiteral( "array_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayGet, QStringLiteral( "Arrays" ) )
9123 << new QgsStaticExpressionFunction( QStringLiteral( "array_first" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayFirst, QStringLiteral( "Arrays" ) )
9124 << new QgsStaticExpressionFunction( QStringLiteral( "array_last" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayLast, QStringLiteral( "Arrays" ) )
9125 << new QgsStaticExpressionFunction( QStringLiteral( "array_min" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMinimum, QStringLiteral( "Arrays" ) )
9126 << new QgsStaticExpressionFunction( QStringLiteral( "array_max" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMaximum, QStringLiteral( "Arrays" ) )
9127 << new QgsStaticExpressionFunction( QStringLiteral( "array_mean" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMean, QStringLiteral( "Arrays" ) )
9128 << new QgsStaticExpressionFunction( QStringLiteral( "array_median" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayMedian, QStringLiteral( "Arrays" ) )
9129 << new QgsStaticExpressionFunction( QStringLiteral( "array_majority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMajority, QStringLiteral( "Arrays" ) )
9130 << new QgsStaticExpressionFunction( QStringLiteral( "array_minority" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "option" ), true, QVariant( "all" ) ), fcnArrayMinority, QStringLiteral( "Arrays" ) )
9131 << new QgsStaticExpressionFunction( QStringLiteral( "array_sum" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArraySum, QStringLiteral( "Arrays" ) )
9132 << new QgsStaticExpressionFunction( QStringLiteral( "array_append" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayAppend, QStringLiteral( "Arrays" ) )
9133 << new QgsStaticExpressionFunction( QStringLiteral( "array_prepend" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayPrepend, QStringLiteral( "Arrays" ) )
9134 << new QgsStaticExpressionFunction( QStringLiteral( "array_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnArrayInsert, QStringLiteral( "Arrays" ) )
9135 << new QgsStaticExpressionFunction( QStringLiteral( "array_remove_at" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "pos" ) ), fcnArrayRemoveAt, QStringLiteral( "Arrays" ) )
9136 << 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 )
9137 << new QgsStaticExpressionFunction( QStringLiteral( "array_replace" ), -1, fcnArrayReplace, QStringLiteral( "Arrays" ) )
9138 << new QgsStaticExpressionFunction( QStringLiteral( "array_prioritize" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array_prioritize" ) ), fcnArrayPrioritize, QStringLiteral( "Arrays" ) )
9139 << new QgsStaticExpressionFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) )
9140 << new QgsStaticExpressionFunction( QStringLiteral( "array_slice" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "start_pos" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "end_pos" ) ), fcnArraySlice, QStringLiteral( "Arrays" ) )
9141 << new QgsStaticExpressionFunction( QStringLiteral( "array_reverse" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayReverse, QStringLiteral( "Arrays" ) )
9142 << new QgsStaticExpressionFunction( QStringLiteral( "array_intersect" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array1" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) )
9143 << new QgsStaticExpressionFunction( QStringLiteral( "array_distinct" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) ), fcnArrayDistinct, QStringLiteral( "Arrays" ) )
9144 << 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" ) )
9145 << 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" ) )
9146 << 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" ) )
9147 << new QgsStaticExpressionFunction( QStringLiteral( "geometries_to_array" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "geometries" ) ), fcnGeometryCollectionAsArray, QStringLiteral( "Arrays" ) )
9148
9149 //functions for maps
9150 << new QgsStaticExpressionFunction( QStringLiteral( "from_json" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnLoadJson, QStringLiteral( "Maps" ), QString(), false, QSet<QString>(), false, QStringList() << QStringLiteral( "json_to_map" ) )
9151 << 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" ) )
9152 << new QgsStaticExpressionFunction( QStringLiteral( "hstore_to_map" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "string" ) ), fcnHstoreToMap, QStringLiteral( "Maps" ) )
9153 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_hstore" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapToHstore, QStringLiteral( "Maps" ) )
9154 << new QgsStaticExpressionFunction( QStringLiteral( "map" ), -1, fcnMap, QStringLiteral( "Maps" ) )
9155 << new QgsStaticExpressionFunction( QStringLiteral( "map_get" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapGet, QStringLiteral( "Maps" ) )
9156 << new QgsStaticExpressionFunction( QStringLiteral( "map_exist" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapExist, QStringLiteral( "Maps" ) )
9157 << new QgsStaticExpressionFunction( QStringLiteral( "map_delete" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ), fcnMapDelete, QStringLiteral( "Maps" ) )
9158 << new QgsStaticExpressionFunction( QStringLiteral( "map_insert" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "key" ) ) << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) ), fcnMapInsert, QStringLiteral( "Maps" ) )
9159 << new QgsStaticExpressionFunction( QStringLiteral( "map_concat" ), -1, fcnMapConcat, QStringLiteral( "Maps" ) )
9160 << new QgsStaticExpressionFunction( QStringLiteral( "map_akeys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAKeys, QStringLiteral( "Maps" ) )
9161 << new QgsStaticExpressionFunction( QStringLiteral( "map_avals" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ), fcnMapAVals, QStringLiteral( "Maps" ) )
9162 << new QgsStaticExpressionFunction( QStringLiteral( "map_prefix_keys" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) )
9163 << QgsExpressionFunction::Parameter( QStringLiteral( "prefix" ) ),
9164 fcnMapPrefixKeys, QStringLiteral( "Maps" ) )
9165 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_table" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9166 fcnMapToHtmlTable, QStringLiteral( "Maps" ) )
9167 << new QgsStaticExpressionFunction( QStringLiteral( "map_to_html_dl" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9168 fcnMapToHtmlDefinitionList, QStringLiteral( "Maps" ) )
9169 << new QgsStaticExpressionFunction( QStringLiteral( "url_encode" ), QgsExpressionFunction::ParameterList() << QgsExpressionFunction::Parameter( QStringLiteral( "map" ) ),
9170 fcnToFormUrlEncode, QStringLiteral( "Maps" ) )
9171
9172 ;
9173
9175
9176 //QgsExpression has ownership of all built-in functions
9177 for ( QgsExpressionFunction *func : std::as_const( functions ) )
9178 {
9179 *sOwnedFunctions() << func;
9180 *sBuiltinFunctions() << func->name();
9181 sBuiltinFunctions()->append( func->aliases() );
9182 }
9183 }
9184 return functions;
9185}
9186
9187bool QgsExpression::registerFunction( QgsExpressionFunction *function, bool transferOwnership )
9188{
9189 int fnIdx = functionIndex( function->name() );
9190 if ( fnIdx != -1 )
9191 {
9192 return false;
9193 }
9194 sFunctions()->append( function );
9195 if ( transferOwnership )
9196 sOwnedFunctions()->append( function );
9197 return true;
9198}
9199
9200bool QgsExpression::unregisterFunction( const QString &name )
9201{
9202 // You can never override the built in functions.
9203 if ( QgsExpression::BuiltinFunctions().contains( name ) )
9204 {
9205 return false;
9206 }
9207 int fnIdx = functionIndex( name );
9208 if ( fnIdx != -1 )
9209 {
9210 sFunctions()->removeAt( fnIdx );
9211 return true;
9212 }
9213 return false;
9214}
9215
9217{
9218 qDeleteAll( *sOwnedFunctions() );
9219 sOwnedFunctions()->clear();
9220}
9222const QStringList &QgsExpression::BuiltinFunctions()
9223{
9224 if ( sBuiltinFunctions()->isEmpty() )
9225 {
9226 Functions(); // this method builds the gmBuiltinFunctions as well
9227 }
9228 return *sBuiltinFunctions();
9229}
9231
9233 : QgsExpressionFunction( QStringLiteral( "array_foreach" ), QgsExpressionFunction::ParameterList() // skip-keyword-check
9234 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9235 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9236 QStringLiteral( "Arrays" ) )
9237{
9238
9239}
9240
9242{
9243 bool isStatic = false;
9244
9245 QgsExpressionNode::NodeList *args = node->args();
9247 if ( args->count() < 2 )
9248 return false;
9249
9250 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9251 {
9252 isStatic = true;
9253 }
9254 return isStatic;
9255}
9256
9258{
9259 Q_UNUSED( node )
9260 QVariantList result;
9261
9262 if ( args->count() < 2 )
9263 // error
9264 return result;
9265
9266 QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9267
9268 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9269 std::unique_ptr< QgsExpressionContext > tempContext;
9270 if ( !subContext )
9271 {
9272 tempContext = std::make_unique< QgsExpressionContext >();
9273 subContext = tempContext.get();
9274 }
9275
9277 subContext->appendScope( subScope );
9278
9279 for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it )
9281 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), *it, true ) );
9282 result << args->at( 1 )->eval( parent, subContext );
9283 }
9284
9285 if ( context )
9286 delete subContext->popScope();
9287
9288 return result;
9289}
9290
9291QVariant QgsArrayForeachExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9293 // This is a dummy function, all the real handling is in run
9294 Q_UNUSED( values )
9295 Q_UNUSED( context )
9296 Q_UNUSED( parent )
9297 Q_UNUSED( node )
9298
9299 Q_ASSERT( false );
9300 return QVariant();
9301}
9302
9304{
9305 QgsExpressionNode::NodeList *args = node->args();
9306
9307 if ( args->count() < 2 )
9308 // error
9309 return false;
9310
9311 args->at( 0 )->prepare( parent, context );
9312
9313 QgsExpressionContext subContext;
9314 if ( context )
9315 subContext = *context;
9316
9318 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9319 subContext.appendScope( subScope );
9320
9321 args->at( 1 )->prepare( parent, &subContext );
9322
9323 return true;
9324}
9327 : QgsExpressionFunction( QStringLiteral( "array_filter" ), QgsExpressionFunction::ParameterList()
9328 << QgsExpressionFunction::Parameter( QStringLiteral( "array" ) )
9329 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) )
9330 << QgsExpressionFunction::Parameter( QStringLiteral( "limit" ), true, 0 ),
9331 QStringLiteral( "Arrays" ) )
9332{
9333
9334}
9335
9337{
9338 bool isStatic = false;
9339
9340 QgsExpressionNode::NodeList *args = node->args();
9342 if ( args->count() < 2 )
9343 return false;
9344
9345 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9346 {
9347 isStatic = true;
9348 }
9349 return isStatic;
9350}
9351
9353{
9354 Q_UNUSED( node )
9355 QVariantList result;
9356
9357 if ( args->count() < 2 )
9358 // error
9359 return result;
9360
9361 const QVariantList array = args->at( 0 )->eval( parent, context ).toList();
9362
9363 QgsExpressionContext *subContext = const_cast<QgsExpressionContext *>( context );
9364 std::unique_ptr< QgsExpressionContext > tempContext;
9365 if ( !subContext )
9366 {
9367 tempContext = std::make_unique< QgsExpressionContext >();
9368 subContext = tempContext.get();
9369 }
9370
9372 subContext->appendScope( subScope );
9373
9374 int limit = 0;
9375 if ( args->count() >= 3 )
9376 {
9377 const QVariant limitVar = args->at( 2 )->eval( parent, context );
9378
9379 if ( QgsExpressionUtils::isIntSafe( limitVar ) )
9380 {
9381 limit = limitVar.toInt();
9382 }
9383 else
9384 {
9385 return result;
9386 }
9387 }
9388
9389 for ( const QVariant &value : array )
9390 {
9391 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), value, true ) );
9392 if ( args->at( 1 )->eval( parent, subContext ).toBool() )
9393 {
9394 result << value;
9395
9396 if ( limit > 0 && limit == result.size() )
9397 break;
9398 }
9399 }
9400
9401 if ( context )
9402 delete subContext->popScope();
9403
9404 return result;
9405}
9406
9407QVariant QgsArrayFilterExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9409 // This is a dummy function, all the real handling is in run
9410 Q_UNUSED( values )
9411 Q_UNUSED( context )
9412 Q_UNUSED( parent )
9413 Q_UNUSED( node )
9414
9415 Q_ASSERT( false );
9416 return QVariant();
9417}
9418
9420{
9421 QgsExpressionNode::NodeList *args = node->args();
9422
9423 if ( args->count() < 2 )
9424 // error
9425 return false;
9426
9427 args->at( 0 )->prepare( parent, context );
9428
9429 QgsExpressionContext subContext;
9430 if ( context )
9431 subContext = *context;
9432
9434 subScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "element" ), QVariant(), true ) );
9435 subContext.appendScope( subScope );
9436
9437 args->at( 1 )->prepare( parent, &subContext );
9438
9439 return true;
9442 : QgsExpressionFunction( QStringLiteral( "with_variable" ), QgsExpressionFunction::ParameterList() <<
9443 QgsExpressionFunction::Parameter( QStringLiteral( "name" ) )
9444 << QgsExpressionFunction::Parameter( QStringLiteral( "value" ) )
9445 << QgsExpressionFunction::Parameter( QStringLiteral( "expression" ) ),
9446 QStringLiteral( "General" ) )
9447{
9448
9449}
9450
9452{
9453 bool isStatic = false;
9454
9455 QgsExpressionNode::NodeList *args = node->args();
9456
9457 if ( args->count() < 3 )
9458 return false;
9459
9460 // We only need to check if the node evaluation is static, if both - name and value - are static.
9461 if ( args->at( 0 )->isStatic( parent, context ) && args->at( 1 )->isStatic( parent, context ) )
9462 {
9463 QVariant name = args->at( 0 )->eval( parent, context );
9464 QVariant value = args->at( 1 )->eval( parent, context );
9466 // Temporarily append a new scope to provide the variable
9467 appendTemporaryVariable( context, name.toString(), value );
9468 if ( args->at( 2 )->isStatic( parent, context ) )
9469 isStatic = true;
9470 popTemporaryVariable( context );
9471 }
9472
9473 return isStatic;
9474}
9475
9477{
9478 Q_UNUSED( node )
9479 QVariant result;
9480
9481 if ( args->count() < 3 )
9482 // error
9483 return result;
9484
9485 QVariant name = args->at( 0 )->eval( parent, context );
9486 QVariant value = args->at( 1 )->eval( parent, context );
9487
9488 const QgsExpressionContext *updatedContext = context;
9489 std::unique_ptr< QgsExpressionContext > tempContext;
9490 if ( !updatedContext )
9491 {
9492 tempContext = std::make_unique< QgsExpressionContext >();
9493 updatedContext = tempContext.get();
9495
9496 appendTemporaryVariable( updatedContext, name.toString(), value );
9497 result = args->at( 2 )->eval( parent, updatedContext );
9498
9499 if ( context )
9500 popTemporaryVariable( updatedContext );
9501
9502 return result;
9503}
9504
9505QVariant QgsWithVariableExpressionFunction::func( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node )
9507 // This is a dummy function, all the real handling is in run
9508 Q_UNUSED( values )
9509 Q_UNUSED( context )
9510 Q_UNUSED( parent )
9511 Q_UNUSED( node )
9512
9513 Q_ASSERT( false );
9514 return QVariant();
9515}
9516
9518{
9519 QgsExpressionNode::NodeList *args = node->args();
9520
9521 if ( args->count() < 3 )
9522 // error
9523 return false;
9524
9525 QVariant name = args->at( 0 )->prepare( parent, context );
9526 QVariant value = args->at( 1 )->prepare( parent, context );
9527
9528 const QgsExpressionContext *updatedContext = context;
9529 std::unique_ptr< QgsExpressionContext > tempContext;
9530 if ( !updatedContext )
9531 {
9532 tempContext = std::make_unique< QgsExpressionContext >();
9533 updatedContext = tempContext.get();
9534 }
9535
9536 appendTemporaryVariable( updatedContext, name.toString(), value );
9537 args->at( 2 )->prepare( parent, updatedContext );
9538
9539 if ( context )
9540 popTemporaryVariable( updatedContext );
9541
9542 return true;
9543}
9544
9545void QgsWithVariableExpressionFunction::popTemporaryVariable( const QgsExpressionContext *context ) const
9546{
9547 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
9548 delete updatedContext->popScope();
9549}
9550
9551void QgsWithVariableExpressionFunction::appendTemporaryVariable( const QgsExpressionContext *context, const QString &name, const QVariant &value ) const
9552{
9555
9556 QgsExpressionContext *updatedContext = const_cast<QgsExpressionContext *>( context );
9557 updatedContext->appendScope( scope );
9558}
DashPatternSizeAdjustment
Dash pattern size adjustment options.
Definition: qgis.h:2251
@ 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.
JoinStyle
Join styles for buffers.
Definition: qgis.h:1502
EndCapStyle
End cap styles for buffers.
Definition: qgis.h:1489
DashPatternLineEndingRule
Dash pattern line ending rules.
Definition: qgis.h:2236
@ 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:1515
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
@ Structure
Structured method, first makes all rings valid and then merges shells and subtracts holes from shells...
@ PointM
PointM.
@ PointZ
PointZ.
@ PointZM
PointZM.
Abstract base class for all geometries.
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
virtual QgsAbstractGeometry * boundary() const =0
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
bool is3D() const SIP_HOLDGIL
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.
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 const QgsAbstractGeometry * simplifiedTypeRef() const SIP_HOLDGIL
Returns a reference to the simplest lossless representation of this geometry, e.g.
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.
Qgis::WkbType wkbType() const SIP_HOLDGIL
Returns the WKB type of the geometry.
part_iterator parts_begin()
Returns STL-style iterator pointing to the first part of the geometry.
bool isMeasure() const SIP_HOLDGIL
Returns true if the geometry contains m values.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
Aggregate
Available aggregates to calculate.
@ StringConcatenateUnique
Concatenate unique values with a joining string (string fields only). Specify the delimiter using set...
@ StringMaximumLength
Maximum length of string (string fields only)
@ ThirdQuartile
Third quartile (numeric fields only)
@ Range
Range of values (max - min) (numeric and datetime fields only)
@ ArrayAggregate
Create an array of values.
@ InterQuartileRange
Inter quartile range (IQR) (numeric fields only)
@ FirstQuartile
First quartile (numeric fields only)
@ Median
Median of values (numeric fields only)
@ GeometryCollect
Create a multipart geometry from aggregated geometries.
@ CountMissing
Number of missing (null) values.
@ StDevSample
Sample standard deviation of values (numeric fields only)
@ Majority
Majority of values.
@ StringConcatenate
Concatenate values with a joining string (string fields only). Specify the delimiter using setDelimit...
@ Mean
Mean of values (numeric fields only)
@ StringMinimumLength
Minimum length of string (string fields only)
@ CountDistinct
Number of distinct values.
@ Minority
Minority of values.
static 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:44
Abstract base class for color ramps.
Definition: qgscolorramp.h:30
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.
@ FlagDegreesUseStringSuffix
Include a direction suffix (eg 'N', 'E', 'S' or 'W'), otherwise a "-" prefix is used for west and sou...
@ FlagDegreesPadMinutesSeconds
Pad minute and second values with leading zeros, eg '05' instead of '5'.
static QString formatX(double x, Format format, int precision=12, FormatFlags flags=FlagDegreesUseStringSuffix)
Formats an x coordinate value according to the specified parameters.
This class represents a coordinate reference system (CRS).
static QgsCoordinateReferenceSystem fromOgcWmsCrs(const QString &ogcCrs)
Creates a CRS from a given OGC WMS-format Coordinate Reference System string.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Q_GADGET Qgis::DistanceUnit mapUnits
QString toProj() const
Returns a Proj string representation of this 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.
Definition: qgsexception.h:67
Curve polygon geometry type.
int ringCount(int part=0) const override SIP_HOLDGIL
Returns the number of rings of which this geometry is built.
bool isEmpty() const override SIP_HOLDGIL
Returns true if the geometry is empty.
const QgsCurve * interiorRing(int i) const SIP_HOLDGIL
Retrieves an interior ring from the curve polygon.
const QgsCurve * exteriorRing() const SIP_HOLDGIL
Returns the curve polygon's exterior ring.
double roundness() const
Returns the roundness of the curve polygon.
double area() const override SIP_HOLDGIL
Returns the planar, 2-dimensional area of the geometry.
int numInteriorRings() const SIP_HOLDGIL
Returns the number of interior rings contained with the curve polygon.
Abstract base class for curved geometry type.
Definition: qgscurve.h:36
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 bool isClosed() const SIP_HOLDGIL
Returns true if the curve is closed.
Definition: qgscurve.cpp:53
virtual QgsCurve * curveSubstring(double startDistance, double endDistance) const =0
Returns a new curve representing a substring of this curve.
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 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:40
QString what() const
Definition: qgsexception.h:49
Contains utilities for working with EXIF tags in images.
Definition: qgsexiftools.h:33
static QgsPoint getGeoTag(const QString &imagePath, bool &ok)
Returns the geotagged coordinate stored in the image at imagePath.
static QVariant readTag(const QString &imagePath, const QString &key)
Returns the value of of an exif tag key stored in the image at imagePath.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
bool isStatic(const QString &name) const
Tests whether the variable with the specified name is static and can be cached.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
static void registerContextFunctions()
Registers all known core functions provided by QgsExpressionContextScope objects.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void setCachedValue(const QString &key, const QVariant &value) const
Sets a value to cache within the expression context.
QgsGeometry geometry() const
Convenience function for retrieving the geometry for the context, if set.
QgsFeature feature() const
Convenience function for retrieving the feature for the context, if set.
QgsExpressionContextScope * activeScopeForVariable(const QString &name)
Returns the currently active scope from the context for a specified variable name.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly by the expression to check if evaluation sh...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
bool hasGeometry() const
Returns true if the context has a geometry associated with it.
bool hasCachedValue(const QString &key) const
Returns true if the expression context contains a cached value with a matching key.
QVariant variable(const QString &name) const
Fetches a matching variable from the context.
QVariant cachedValue(const QString &key) const
Returns the matching cached value, if set.
bool hasFeature() const
Returns true if the context has a feature associated with it.
QgsFields fields() const
Convenience function for retrieving the fields for the context, if set.
Represents a single parameter passed to a function.
A abstract base class for defining QgsExpression functions.
QList< QgsExpressionFunction::Parameter > ParameterList
List of parameters, used for function definition.
bool operator==(const QgsExpressionFunction &other) const
virtual bool isDeprecated() const
Returns true if the function is deprecated and should not be presented as a valid option to users in ...
virtual bool isStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const
Will be called during prepare to determine if the function is static.
virtual QStringList aliases() const
Returns a list of possible aliases for the function.
bool lazyEval() const
true if this function should use lazy evaluation.
static bool allParamsStatic(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context)
This will return true if all the params for the provided function node are static within the constrai...
QString name() const
The name of the function.
virtual QVariant run(QgsExpressionNode::NodeList *args, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node)
Evaluates the function, first evaluating all required arguments before passing them to the function's...
virtual QVariant func(const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent, const QgsExpressionNodeFunction *node)=0
Returns result of evaluating the function.
virtual QSet< QString > referencedColumns(const QgsExpressionNodeFunction *node) const
Returns a set of field names which are required for this function.
virtual bool handlesNull() const
Returns true if the function handles NULL values in arguments by itself, and the default NULL value h...
virtual bool prepare(const QgsExpressionNodeFunction *node, QgsExpression *parent, const QgsExpressionContext *context) const
This will be called during the prepare step() of an expression if it is not static.
virtual bool usesGeometry(const QgsExpressionNodeFunction *node) const
Does this function use a geometry object.
An expression node which takes it value from a feature's field.
QString name() const
The name of the column.
An expression node for expression functions.
QgsExpressionNode::NodeList * args() const
Returns a list of arguments specified for the function.
An expression node for literal values.
A list of expression nodes.
QList< QgsExpressionNode * > list()
Gets a list of all the nodes.
QgsExpressionNode * at(int i)
Gets the node at position i in the list.
int count() const
Returns the number of nodes in the list.
Abstract base class for all nodes that can appear in an expression.
virtual QString dump() const =0
Dump this node into a serialized (part) of an expression.
QVariant eval(QgsExpression *parent, const QgsExpressionContext *context)
Evaluate this node with the given context and parent.
virtual bool isStatic(QgsExpression *parent, const QgsExpressionContext *context) const =0
Returns true if this node can be evaluated for a static value.
bool prepare(QgsExpression *parent, const QgsExpressionContext *context)
Prepare this node for evaluation.
virtual QSet< QString > referencedColumns() const =0
Abstract virtual method which returns a list of columns required to evaluate this node.
virtual QSet< QString > referencedVariables() const =0
Returns a set of all variables which are used in this expression.
A set of expression-related functions.
Class for parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
static const QList< QgsExpressionFunction * > & Functions()
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 QString quotedValue(const QVariant &value)
Returns a string representation of a literal value, including appropriate quotations where required.
static int functionIndex(const QString &name)
Returns index of the function in Functions array.
static const QStringList & BuiltinFunctions()
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QVariant::Type fieldType=QVariant::Type::Invalid)
Create an expression allowing to evaluate if a field is equal to a value.
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 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)
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 & 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 & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
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...
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
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:56
QgsFields fields
Definition: qgsfeature.h:66
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:230
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:216
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:335
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:167
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
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:714
Container of fields for a vector layer.
Definition: qgsfields.h:45
int indexFromName(const QString &fieldName) const
Gets the field index from the field name.
Definition: qgsfields.cpp:202
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
int size() const
Returns number of items.
Definition: qgsfields.cpp:138
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Definition: qgsfields.cpp:163
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Definition: qgsfields.cpp:359
Geometry collection.
int numGeometries() const SIP_HOLDGIL
Returns the number of geometries within the collection.
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.
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.
Definition: qgsgeometry.h:164
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...
double lineLocatePoint(const QgsGeometry &point) const
Returns a distance representing the location along this linestring of the closest point on this lines...
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
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 concaveHull(double targetPercent, bool allowHoles=false) const SIP_THROW(QgsNotSupportedException)
Returns a possibly concave polygon that contains all the points in the geometry.
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.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
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 ...
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.
Q_GADGET bool isNull
Definition: qgsgeometry.h:166
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.
static QgsGeometry fromRect(const QgsRectangle &rect) SIP_HOLDGIL
Creates a new geometry from a QgsRectangle.
bool isMultipart() const SIP_HOLDGIL
Returns true if WKB of the geometry is of WKBMulti* type.
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
Definition: qgsgeometry.h:167
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.
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.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
QString lastError() const SIP_HOLDGIL
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false) const SIP_THROW(QgsNotSupportedException)
Attempts to make an invalid geometry valid without losing vertices.
QgsGeometry convexHull() const
Returns the smallest convex polygon that contains all the points in the geometry.
QgsGeometry sharedPaths(const QgsGeometry &other) const
Find paths shared between the two given lineal geometries (this and other).
void fromWkb(unsigned char *wkb, int length)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
QgsGeometry symDifference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points making up this geometry that do not make up other.
QgsGeometry minimalEnclosingCircle(QgsPointXY &center, double &radius, unsigned int segments=36) const
Returns the minimal enclosing circle for the geometry.
QgsGeometry mergeLines() const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
static QgsGeometry fromWkt(const QString &wkt)
Creates a new geometry from a WKT string.
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...
QString asWkt(int precision=17) const
Exports the geometry to WKT.
bool intersects(const QgsRectangle &rectangle) const
Returns true if this geometry exactly intersects with a rectangle.
QgsAbstractGeometry::vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
bool overlaps(const QgsGeometry &geometry) const
Returns true if the geometry overlaps another geometry.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Does vector analysis using the geos library and handles import, export, exception handling*.
Definition: qgsgeos.h:99
std::unique_ptr< QgsAbstractGeometry > maximumInscribedCircle(double tolerance, QString *errorMsg=nullptr) const
Returns the maximum inscribed circle.
Definition: qgsgeos.cpp:2458
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:42
bool isValid() const
Returns true if the interval is valid.
Definition: qgsinterval.h:261
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.
Definition: qgsinterval.h:242
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.
Definition: qgslinestring.h:45
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
Base class for all map layer types.
Definition: qgsmaplayer.h:73
QString name
Definition: qgsmaplayer.h:76
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.
QString publicSource() const
Gets a version of the internal layer definition that has sensitive bits removed (for example,...
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:79
QString attribution() const
Returns the attribution of the layer used by QGIS Server in GetCapabilities request.
Definition: qgsmaplayer.h:396
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
QgsLayerMetadata metadata
Definition: qgsmaplayer.h:78
Qgis::LayerType type
Definition: qgsmaplayer.h:80
virtual bool isEditable() const
Returns true if the layer can be edited.
QString dataUrl() const
Returns the DataUrl of the layer used by QGIS Server in GetCapabilities request.
Definition: qgsmaplayer.h:360
QString attributionUrl() const
Returns the attribution URL of the layer used by QGIS Server in GetCapabilities request.
Definition: qgsmaplayer.h:413
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:83
Implementation of GeometrySimplifier using the "MapToPixel" algorithm.
@ Visvalingam
The simplification gives each point in a line an importance weighting, so that least important points...
@ SimplifyGeometry
The geometries can be simplified using the current map2pixel context state.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Multi line string geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi point geometry collection.
Definition: qgsmultipoint.h:30
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.
Definition: qgsexception.h:119
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:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
bool isValid(QString &error, Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const override SIP_HOLDGIL
Checks validity of the geometry, and returns true if the geometry is valid.
Definition: qgspoint.cpp:424
QgsPoint project(double distance, double azimuth, double inclination=90.0) const SIP_HOLDGIL
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition: qgspoint.cpp:735
Q_GADGET double x
Definition: qgspoint.h:52
double z
Definition: qgspoint.h:54
double m
Definition: qgspoint.h:55
double y
Definition: qgspoint.h:53
double inclination(const QgsPoint &other) const SIP_HOLDGIL
Calculates Cartesian inclination between this point and other one (starting from zenith = 0 to nadir ...
Definition: qgspoint.cpp:723
QgsRelationManager * relationManager
Definition: qgsproject.h:117
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:484
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) SIP_HOLDGIL
Construct a QgsQuadrilateral as a square from a diagonal.
QgsPolygon * toPolygon(bool force2D=false) const
Returns the quadrilateral as a new polygon.
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...
static QgsQuadrilateral rectangleFrom3Points(const QgsPoint &p1, const QgsPoint &p2, const QgsPoint &p3, ConstructionOption mode) SIP_HOLDGIL
Construct a QgsQuadrilateral as a Rectangle from 3 points.
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.
Definition: qgsrectangle.h:42
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:193
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:183
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:188
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:198
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
Definition: qgsrectangle.h:230
void grow(double delta)
Grows the rectangle in place by the specified amount.
Definition: qgsrectangle.h:296
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
Definition: qgsrectangle.h:223
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Definition: qgsrectangle.h:251
Regular Polygon geometry type.
ConstructionOption
A regular polygon can be constructed inscribed in a circle or circumscribed about a circle.
@ CircumscribedCircle
Circumscribed about a circle (the radius is the distance from the center to the midpoints of the side...
@ InscribedCircle
Inscribed in a circle (the radius is the distance between the center and vertices)
QgsPolygon * toPolygon() const
Returns as a polygon.
QList< QgsRelation > relationsByName(const QString &name) const
Returns a list of relations with matching names.
Q_INVOKABLE QgsRelation relation(const QString &id) const
Gets access to a relation by its id.
QgsVectorLayer * referencedLayer
Definition: qgsrelation.h:47
QgsVectorLayer * referencingLayer
Definition: qgsrelation.h:46
bool isValid
Definition: qgsrelation.h:49
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.
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:474
static QgsStyle * defaultStyle()
Returns default application-wide style.
Definition: qgsstyle.cpp:145
QgsRectangle boundingBox() const override
Returns the minimal bounding box for the geometry.
Definition: qgssurface.h:43
static QColor decodeColor(const QString &str)
static QString encodeColor(const QColor &color)
static bool runOnMainThread(const Func &func, QgsFeedback *feedback=nullptr)
Guarantees that func is executed on the main thread.
This class allows including a set of layers in a database-side transaction, provided the layer data p...
virtual bool executeSql(const QString &sql, QString &error, bool isDirty=false, const QString &name=QString())=0
Execute the sql string.
Triangle geometry type.
Definition: qgstriangle.h:34
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
static bool isNull(const QVariant &variant)
Returns true if the specified variant should be considered a NULL value.
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.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
QString displayExpression
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
QgsEditorWidgetSetup editorWidgetSetup(int index) const
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
QgsFeature getFeature(QgsFeatureId fid) const
Queries the layer for the feature with the given id.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
QVariant aggregate(QgsAggregateCalculator::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.
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) SIP_HOLDGIL
Returns a display string for a geometry type.
static Qgis::WkbType flatType(Qgis::WkbType type) SIP_HOLDGIL
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:629
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)
Definition: MathUtils.cpp:786
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.
CORE_EXPORT QgsMeshVertex centroid(const QgsMeshFace &face, const QVector< QgsMeshVertex > &vertices)
Returns the centroid of the face.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
uint qHash(const QVariant &variant)
Hash for QVariant.
Definition: qgis.cpp:198
#define str(x)
Definition: qgis.cpp:38
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition: qgis.cpp:120
#define Q_NOWARN_DEPRECATED_POP
Definition: qgis.h:4572
#define Q_NOWARN_DEPRECATED_PUSH
Definition: qgis.h:4571
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
Definition: qgis.h:4042
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:3988
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
QList< QgsGradientStop > QgsGradientStopsList
List of gradient stops.
Q_DECLARE_METATYPE(QgsDatabaseQueryLogEntry)
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
QList< QgsExpressionFunction * > ExpressionFunctionList
#define ENSURE_GEOM_TYPE(f, g, geomtype)
QVariant fcnRampColor(const QVariantList &values, const QgsExpressionContext *, QgsExpression *parent, const QgsExpressionNodeFunction *)
bool(QgsGeometry::* RelationFunction)(const QgsGeometry &geometry) const
#define ENSURE_NO_EVAL_ERROR
#define FEAT_FROM_CONTEXT(c, f)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28
const QgsField & field
Definition: qgsfield.h:554
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
Definition: qgsmaplayer.h:2255
QLineF segment(int index, QRectF rect, double radius)
int precision
A bundle of parameters controlling aggregate calculation.
QString filter
Optional filter for calculating aggregate over a subset of features, or an empty string to use all fe...
QString delimiter
Delimiter to use for joining values with the StringConcatenate aggregate.
QgsFeatureRequest::OrderBy orderBy
Optional order by clauses.
Single variable definition for use within a QgsExpressionContextScope.
The Context struct stores the current layer and coordinate transform context.
Definition: qgsogcutils.h:62
const QgsMapLayer * layer
Definition: qgsogcutils.h:72
QgsCoordinateTransformContext transformContext
Definition: qgsogcutils.h:73
Utility class for identifying a unique vertex within a geometry.
Definition: qgsvertexid.h:31