QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
qgsexpressiontreeview.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsexpressiontreeview.cpp
3 --------------------------------------
4 Date : march 2020 - quarantine day 9
5 Copyright : (C) 2020 by Denis Rouzaud
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#include <QMenu>
17#include <QMessageBox>
18#include <QVersionNumber>
19
21#include "moc_qgsexpressiontreeview.cpp"
22#include "qgis.h"
23#include "qgsvectorlayer.h"
25#include "qgssettings.h"
26#include "qgsrelationmanager.h"
27#include "qgsapplication.h"
28#include "qgsiconutils.h"
29
30
32QString formatRelationHelp( const QgsRelation &relation )
33{
34 QString text = QStringLiteral( "<h3>%1</h3>\n<div class=\"description\"><p>%2</p></div>" )
35 .arg( QCoreApplication::translate( "relation_help", "relation %1" ).arg( relation.name() ), QObject::tr( "Inserts the relation ID for the relation named '%1'." ).arg( relation.name() ) );
36
37 text += QStringLiteral( "<h4>%1</h4><div class=\"description\"><pre>%2</pre></div>" )
38 .arg( QObject::tr( "Current value" ), relation.id() );
39
40 return text;
41}
42
43
45QString formatLayerHelp( const QgsMapLayer *layer )
46{
47 QString text = QStringLiteral( "<h3>%1</h3>\n<div class=\"description\"><p>%2</p></div>" )
48 .arg( QCoreApplication::translate( "layer_help", "map layer %1" ).arg( layer->name() ), QObject::tr( "Inserts the layer ID for the layer named '%1'." ).arg( layer->name() ) );
49
50 text += QStringLiteral( "<h4>%1</h4><div class=\"description\"><pre>%2</pre></div>" )
51 .arg( QObject::tr( "Current value" ), layer->id() );
52
53 return text;
54}
55
57QString formatRecentExpressionHelp( const QString &label, const QString &expression )
58{
59 QString text = QStringLiteral( "<h3>%1</h3>\n<div class=\"description\"><p>%2</p></div>" )
60 .arg( QCoreApplication::translate( "recent_expression_help", "expression %1" ).arg( label ), QCoreApplication::translate( "recent_expression_help", "Recently used expression." ) );
61
62 text += QStringLiteral( "<h4>%1</h4><div class=\"description\"><pre>%2</pre></div>" )
63 .arg( QObject::tr( "Expression" ), expression );
64
65 return text;
66}
67
69QString formatUserExpressionHelp( const QString &label, const QString &expression, const QString &description )
70{
71 QString text = QStringLiteral( "<h3>%1</h3>\n<div class=\"description\"><p>%2</p></div>" )
72 .arg( QCoreApplication::translate( "user_expression_help", "expression %1" ).arg( label ), description );
73
74 text += QStringLiteral( "<h4>%1</h4><div class=\"description\"><pre>%2</pre></div>" )
75 .arg( QObject::tr( "Expression" ), expression );
76
77 return text;
78}
79
81QString formatVariableHelp( const QString &variable, const QString &description, bool showValue, const QVariant &value )
82{
83 QString text = QStringLiteral( "<h3>%1</h3>\n<div class=\"description\"><p>%2</p></div>" )
84 .arg( QCoreApplication::translate( "variable_help", "variable %1" ).arg( variable ), description );
85
86 if ( showValue )
87 {
88 QString valueString = !value.isValid()
89 ? QCoreApplication::translate( "variable_help", "not set" )
90 : QStringLiteral( "<pre>%1</pre>" ).arg( QgsExpression::formatPreviewString( value ) );
91
92 text += QStringLiteral( "<h4>%1</h4><div class=\"description\"><p>%2</p></div>" )
93 .arg( QObject::tr( "Current value" ), valueString );
94 }
95
96 return text;
97}
98
99
100// ****************************
101// ****************************
102// QgsExpressionTreeView
103// ****************************
104
105
107 : QTreeView( parent )
108 , mProject( QgsProject::instance() )
109{
110 connect( this, &QTreeView::doubleClicked, this, &QgsExpressionTreeView::onDoubleClicked );
111
112 mModel = std::make_unique<QStandardItemModel>();
113 mProxyModel = std::make_unique<QgsExpressionItemSearchProxy>();
114 mProxyModel->setDynamicSortFilter( true );
115 mProxyModel->setSourceModel( mModel.get() );
116 setModel( mProxyModel.get() );
117 setSortingEnabled( true );
118 sortByColumn( 0, Qt::AscendingOrder );
119
120 setSelectionMode( QAbstractItemView::SelectionMode::SingleSelection );
121
122 setContextMenuPolicy( Qt::CustomContextMenu );
123 connect( this, &QWidget::customContextMenuRequested, this, &QgsExpressionTreeView::showContextMenu );
124 connect( selectionModel(), &QItemSelectionModel::currentChanged, this, &QgsExpressionTreeView::currentItemChanged );
125
126 updateFunctionTree();
128
129 // select the first item in the function list
130 // in order to avoid a blank help widget
131 QModelIndex firstItem = mProxyModel->index( 0, 0, QModelIndex() );
132 setCurrentIndex( firstItem );
133}
134
136{
137 mLayer = layer;
138
139 //TODO - remove existing layer scope from context
140
141 if ( mLayer )
142 mExpressionContext << QgsExpressionContextUtils::layerScope( mLayer );
143
145}
146
148{
149 mExpressionContext = context;
150 updateFunctionTree();
152 loadRecent( mRecentKey );
154}
155
157{
158 mMenuProvider = provider;
159}
160
162{
163 updateFunctionTree();
165 loadRecent( mRecentKey );
167}
168
170{
171 QModelIndex idx = mProxyModel->mapToSource( currentIndex() );
172 QgsExpressionItem *item = static_cast<QgsExpressionItem *>( mModel->itemFromIndex( idx ) );
173 return item;
174}
175
176QStandardItemModel *QgsExpressionTreeView::model()
177{
178 return mModel.get();
179}
180
182{
183 return mProject;
184}
185
187{
188 mProject = project;
189 updateFunctionTree();
190}
191
192
193void QgsExpressionTreeView::setSearchText( const QString &text )
194{
195 mProxyModel->setFilterString( text );
196 if ( text.isEmpty() )
197 {
198 collapseAll();
199 }
200 else
201 {
202 expandAll();
203 QModelIndex index = mProxyModel->index( 0, 0 );
204 if ( mProxyModel->hasChildren( index ) )
205 {
206 QModelIndex child = mProxyModel->index( 0, 0, index );
207 selectionModel()->setCurrentIndex( child, QItemSelectionModel::ClearAndSelect );
208 }
209 }
210}
211
212void QgsExpressionTreeView::onDoubleClicked( const QModelIndex &index )
213{
214 QModelIndex idx = mProxyModel->mapToSource( index );
215 QgsExpressionItem *item = static_cast<QgsExpressionItem *>( mModel->itemFromIndex( idx ) );
216 if ( !item )
217 return;
218
219 // Don't handle the double-click if we are on a header node.
220 if ( item->getItemType() == QgsExpressionItem::Header )
221 return;
222
224}
225
226void QgsExpressionTreeView::showContextMenu( QPoint pt )
227{
228 QModelIndex idx = indexAt( pt );
229 idx = mProxyModel->mapToSource( idx );
230 QgsExpressionItem *item = static_cast<QgsExpressionItem *>( mModel->itemFromIndex( idx ) );
231 if ( !item )
232 return;
233
234 if ( !mMenuProvider )
235 return;
236
237 QMenu *menu = mMenuProvider->createContextMenu( item );
238
239 if ( menu )
240 menu->popup( mapToGlobal( pt ) );
241}
242
243void QgsExpressionTreeView::currentItemChanged( const QModelIndex &index, const QModelIndex & )
244{
245 // Get the item
246 QModelIndex idx = mProxyModel->mapToSource( index );
247 QgsExpressionItem *item = static_cast<QgsExpressionItem *>( mModel->itemFromIndex( idx ) );
248 if ( !item )
249 return;
250
251 emit currentExpressionItemChanged( item );
252}
253
254void QgsExpressionTreeView::updateFunctionTree()
255{
256 mModel->clear();
257 mExpressionGroups.clear();
258
259 //list of pairs where the first is the name and the second is the expression value when adding it
260 static const QList<QPair<QString, QString>> operators = QList<QPair<QString, QString>>()
261 << QPair<QString, QString>( QStringLiteral( "+" ), QStringLiteral( " + " ) )
262 << QPair<QString, QString>( QStringLiteral( "-" ), QStringLiteral( " - " ) )
263 << QPair<QString, QString>( QStringLiteral( "*" ), QStringLiteral( " * " ) )
264 << QPair<QString, QString>( QStringLiteral( "/" ), QStringLiteral( " / " ) )
265 << QPair<QString, QString>( QStringLiteral( "//" ), QStringLiteral( " // " ) )
266 << QPair<QString, QString>( QStringLiteral( "%" ), QStringLiteral( " % " ) )
267 << QPair<QString, QString>( QStringLiteral( "^" ), QStringLiteral( " ^ " ) )
268 << QPair<QString, QString>( QStringLiteral( "=" ), QStringLiteral( " = " ) )
269 << QPair<QString, QString>( QStringLiteral( "~" ), QStringLiteral( " ~ " ) )
270 << QPair<QString, QString>( QStringLiteral( ">" ), QStringLiteral( " > " ) )
271 << QPair<QString, QString>( QStringLiteral( "<" ), QStringLiteral( " < " ) )
272 << QPair<QString, QString>( QStringLiteral( "<>" ), QStringLiteral( " <> " ) )
273 << QPair<QString, QString>( QStringLiteral( "<=" ), QStringLiteral( " <= " ) )
274 << QPair<QString, QString>( QStringLiteral( ">=" ), QStringLiteral( " >= " ) )
275 << QPair<QString, QString>( QStringLiteral( "[]" ), QStringLiteral( "[]" ) )
276 << QPair<QString, QString>( QStringLiteral( "||" ), QStringLiteral( " || " ) )
277 << QPair<QString, QString>( QStringLiteral( "BETWEEN" ), QStringLiteral( " BETWEEN " ) )
278 << QPair<QString, QString>( QStringLiteral( "NOT BETWEEN" ), QStringLiteral( " NOT BETWEEN " ) )
279 << QPair<QString, QString>( QStringLiteral( "IN" ), QStringLiteral( " IN " ) )
280 << QPair<QString, QString>( QStringLiteral( "LIKE" ), QStringLiteral( " LIKE " ) )
281 << QPair<QString, QString>( QStringLiteral( "ILIKE" ), QStringLiteral( " ILIKE " ) )
282 << QPair<QString, QString>( QStringLiteral( "IS" ), QStringLiteral( " IS " ) )
283 << QPair<QString, QString>( QStringLiteral( "IS NOT" ), QStringLiteral( " IS NOT " ) )
284 << QPair<QString, QString>( QStringLiteral( "OR" ), QStringLiteral( " OR " ) )
285 << QPair<QString, QString>( QStringLiteral( "AND" ), QStringLiteral( " AND " ) )
286 << QPair<QString, QString>( QStringLiteral( "NOT" ), QStringLiteral( " NOT " ) );
287 for ( const auto &name : operators )
288 {
289 registerItem( QStringLiteral( "Operators" ), name.first, name.second, QString(), QgsExpressionItem::ExpressionNode, false, -1, QIcon(), QgsExpression::tags( name.first ) );
290 }
291
292 QString casestring = QStringLiteral( "CASE WHEN condition THEN result END" );
293 registerItem( QStringLiteral( "Conditionals" ), QStringLiteral( "CASE" ), casestring, QString(), QgsExpressionItem::ExpressionNode, false, -1, QIcon(), QgsExpression::tags( "CASE" ) );
294
295 // use -1 as sort order here -- NULL should always show before the field list
296 registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "NULL" ), QStringLiteral( "NULL" ), QString(), QgsExpressionItem::ExpressionNode, false, -1 );
297
298 // Load the functions from the QgsExpression class
299 int count = QgsExpression::functionCount();
300 for ( int i = 0; i < count; i++ )
301 {
303 QString name = func->name();
304 if ( name.startsWith( '_' ) ) // do not display private functions
305 continue;
306 if ( func->isDeprecated() ) // don't show deprecated functions
307 continue;
308 if ( func->isContextual() )
309 {
310 //don't show contextual functions by default - it's up the the QgsExpressionContext
311 //object to provide them if supported
312 continue;
313 }
314 if ( func->params() != 0 )
315 name += '(';
316 else if ( !name.startsWith( '$' ) )
317 name += QLatin1String( "()" );
318 // this is where the functions are being registered, including functions under "Custom"
319 registerItemForAllGroups( func->groups(), func->name(), ' ' + name + ' ', func->helpText(), QgsExpressionItem::ExpressionNode, mExpressionContext.isHighlightedFunction( func->name() ), 1, QgsExpression::tags( func->name() ) );
320 }
321
322 // load relation names
323 loadRelations();
324
325 // load layer IDs
326 loadLayers();
327
328 loadExpressionContext();
329}
330
331QgsExpressionItem *QgsExpressionTreeView::registerItem( const QString &group, const QString &label, const QString &expressionText, const QString &helpText, QgsExpressionItem::ItemType type, bool highlightedItem, int sortOrder, const QIcon &icon, const QStringList &tags, const QString &name )
332{
333 QgsExpressionItem *item = new QgsExpressionItem( label, expressionText, helpText, type );
334 item->setData( label, Qt::UserRole );
335 item->setData( sortOrder, QgsExpressionItem::CUSTOM_SORT_ROLE );
336 item->setData( tags, QgsExpressionItem::SEARCH_TAGS_ROLE );
337 item->setData( name, QgsExpressionItem::ITEM_NAME_ROLE );
338 item->setIcon( icon );
339
340 // Look up the group and insert the new function.
341 if ( mExpressionGroups.contains( group ) )
342 {
343 QgsExpressionItem *groupNode = mExpressionGroups.value( group );
344 groupNode->appendRow( item );
345 }
346 else
347 {
348 // If the group doesn't exist yet we make it first.
349 QgsExpressionItem *newgroupNode = new QgsExpressionItem( QgsExpression::group( group ), QString(), QgsExpressionItem::Header );
350 newgroupNode->setData( group, Qt::UserRole );
351 //Recent group should always be last group
352 newgroupNode->setData( group.startsWith( QLatin1String( "Recent (" ) ) ? 2 : 1, QgsExpressionItem::CUSTOM_SORT_ROLE );
353 newgroupNode->appendRow( item );
354 newgroupNode->setBackground( QBrush( QColor( 150, 150, 150, 150 ) ) );
355 mModel->appendRow( newgroupNode );
356 mExpressionGroups.insert( group, newgroupNode );
357 }
358
359 if ( highlightedItem )
360 {
361 //insert a copy as a top level item
362 QgsExpressionItem *topLevelItem = new QgsExpressionItem( label, expressionText, helpText, type );
363 topLevelItem->setData( label, Qt::UserRole );
364 item->setData( 0, QgsExpressionItem::CUSTOM_SORT_ROLE );
365 QFont font = topLevelItem->font();
366 font.setBold( true );
367 topLevelItem->setFont( font );
368 mModel->appendRow( topLevelItem );
369 }
370 return item;
371}
372
373void QgsExpressionTreeView::registerItemForAllGroups( const QStringList &groups, const QString &label, const QString &expressionText, const QString &helpText, QgsExpressionItem::ItemType type, bool highlightedItem, int sortOrder, const QStringList &tags )
374{
375 const auto constGroups = groups;
376 for ( const QString &group : constGroups )
377 {
378 registerItem( group, label, expressionText, helpText, type, highlightedItem, sortOrder, QIcon(), tags );
379 }
380}
381
382void QgsExpressionTreeView::loadExpressionContext()
383{
384 QStringList variableNames = mExpressionContext.filteredVariableNames();
385 const auto constVariableNames = variableNames;
386 for ( const QString &variable : constVariableNames )
387 {
388 registerItem( QStringLiteral( "Variables" ), variable, " @" + variable + ' ', formatVariableHelp( variable, mExpressionContext.description( variable ), true, mExpressionContext.variable( variable ) ), QgsExpressionItem::ExpressionNode, mExpressionContext.isHighlightedVariable( variable ) );
389 }
390
391 // Load the functions from the expression context
392 QStringList contextFunctions = mExpressionContext.functionNames();
393 const auto constContextFunctions = contextFunctions;
394 for ( const QString &functionName : constContextFunctions )
395 {
396 QgsExpressionFunction *func = mExpressionContext.function( functionName );
397 QString name = func->name();
398 if ( name.startsWith( '_' ) ) // do not display private functions
399 continue;
400 if ( func->params() != 0 )
401 name += '(';
402 registerItemForAllGroups( func->groups(), func->name(), ' ' + name + ' ', func->helpText(), QgsExpressionItem::ExpressionNode, mExpressionContext.isHighlightedFunction( func->name() ), 1, QgsExpression::tags( func->name() ) );
403 }
404}
405
406void QgsExpressionTreeView::loadLayers()
407{
408 if ( !mProject )
409 return;
410
411 QMap<QString, QgsMapLayer *> layers = mProject->mapLayers();
412 QMap<QString, QgsMapLayer *>::const_iterator layerIt = layers.constBegin();
413 for ( ; layerIt != layers.constEnd(); ++layerIt )
414 {
415 QIcon icon = QgsIconUtils::iconForLayer( layerIt.value() );
416 QgsExpressionItem *parentItem = registerItem( QStringLiteral( "Map Layers" ), layerIt.value()->name(), QStringLiteral( "'%1'" ).arg( layerIt.key() ), formatLayerHelp( layerIt.value() ), QgsExpressionItem::ExpressionNode, false, 99, icon );
417 loadLayerFields( qobject_cast<QgsVectorLayer *>( layerIt.value() ), parentItem );
418 }
419}
420
421void QgsExpressionTreeView::loadLayerFields( QgsVectorLayer *layer, QgsExpressionItem *parentItem )
422{
423 if ( !layer )
424 return;
425
426 const QgsFields fields = layer->fields();
427 for ( int fieldIdx = 0; fieldIdx < fields.count(); ++fieldIdx )
428 {
429 const QgsField field = fields.at( fieldIdx );
430 QIcon icon = fields.iconForField( fieldIdx );
431 const QString label { field.displayNameWithAlias() };
432 QgsExpressionItem *item = new QgsExpressionItem( label, " '" + field.name() + "' ", QString(), QgsExpressionItem::Field );
433 item->setData( label, Qt::UserRole );
434 item->setData( 99, QgsExpressionItem::CUSTOM_SORT_ROLE );
435 item->setData( QStringList(), QgsExpressionItem::SEARCH_TAGS_ROLE );
436 item->setData( field.name(), QgsExpressionItem::ITEM_NAME_ROLE );
437 item->setData( layer->id(), QgsExpressionItem::LAYER_ID_ROLE );
438 item->setIcon( icon );
439 parentItem->appendRow( item );
440 }
441}
442
444{
445 for ( int i = 0; i < fields.count(); ++i )
446 {
447 const QgsField field = fields.at( i );
448 QIcon icon = fields.iconForField( i );
449 registerItem( QStringLiteral( "Fields and Values" ), field.displayNameWithAlias(), " \"" + field.name() + "\" ", QString(), QgsExpressionItem::Field, false, i, icon, QStringList(), field.name() );
450 }
451}
452
453void QgsExpressionTreeView::loadFieldNames()
454{
455 // Cleanup
456 if ( mExpressionGroups.contains( QStringLiteral( "Fields and Values" ) ) )
457 {
458 QgsExpressionItem *node = mExpressionGroups.value( QStringLiteral( "Fields and Values" ) );
459 node->removeRows( 0, node->rowCount() );
460 // Re-add NULL and feature variables
461 // use -1 as sort order here -- NULL and feature variables should always show before the field list
462 registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "NULL" ), QStringLiteral( "NULL" ), QString(), QgsExpressionItem::ExpressionNode, false, -1 );
463 }
464
465 if ( mLayer )
466 {
467 // Add feature variables to record and attributes group (and highlighted items)
468
469 const QString currentFeatureHelp = formatVariableHelp( QStringLiteral( "feature" ), QgsExpression::variableHelpText( QStringLiteral( "feature" ) ), false, QVariant() );
470 const QString currentFeatureIdHelp = formatVariableHelp( QStringLiteral( "id" ), QgsExpression::variableHelpText( QStringLiteral( "id" ) ), false, QVariant() );
471 const QString currentGeometryHelp = formatVariableHelp( QStringLiteral( "geometry" ), QgsExpression::variableHelpText( QStringLiteral( "geometry" ) ), false, QVariant() );
472
473 registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "feature" ), QStringLiteral( "@feature" ), currentFeatureHelp, QgsExpressionItem::ExpressionNode, false, -1 );
474 registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "id" ), QStringLiteral( "@id" ), currentFeatureIdHelp, QgsExpressionItem::ExpressionNode, false, -1 );
475 registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "geometry" ), QStringLiteral( "@geometry" ), currentGeometryHelp, QgsExpressionItem::ExpressionNode, false, -1 );
476
477 registerItem( QStringLiteral( "Variables" ), QStringLiteral( "feature" ), QStringLiteral( "@feature" ), currentFeatureHelp, QgsExpressionItem::ExpressionNode );
478 registerItem( QStringLiteral( "Variables" ), QStringLiteral( "id" ), QStringLiteral( "@id" ), currentFeatureIdHelp, QgsExpressionItem::ExpressionNode );
479 registerItem( QStringLiteral( "Variables" ), QStringLiteral( "geometry" ), QStringLiteral( "@geometry" ), currentGeometryHelp, QgsExpressionItem::ExpressionNode, false );
480
481 registerItem( QStringLiteral( "Record and Attributes" ), QStringLiteral( "feature" ), QStringLiteral( "@feature" ), currentFeatureHelp, QgsExpressionItem::ExpressionNode, true, -1 );
482 registerItem( QStringLiteral( "Record and Attributes" ), QStringLiteral( "id" ), QStringLiteral( "@id" ), currentFeatureIdHelp, QgsExpressionItem::ExpressionNode, true, -1 );
483 registerItem( QStringLiteral( "Record and Attributes" ), QStringLiteral( "geometry" ), QStringLiteral( "@geometry" ), currentGeometryHelp, QgsExpressionItem::ExpressionNode, true, -1 );
484 }
485
486 // this can happen if fields are manually set
487 if ( !mLayer )
488 return;
489
490 const QgsFields &fields = mLayer->fields();
491
492 loadFieldNames( fields );
493}
494
495void QgsExpressionTreeView::loadRelations()
496{
497 if ( !mProject )
498 return;
499
500 QMap<QString, QgsRelation> relations = mProject->relationManager()->relations();
501 QMap<QString, QgsRelation>::const_iterator relIt = relations.constBegin();
502 for ( ; relIt != relations.constEnd(); ++relIt )
503 {
504 registerItemForAllGroups( QStringList() << tr( "Relations" ), relIt->name(), QStringLiteral( "'%1'" ).arg( relIt->id() ), formatRelationHelp( relIt.value() ) );
505 }
506}
507
508void QgsExpressionTreeView::loadRecent( const QString &collection )
509{
510 mRecentKey = collection;
511 QString name = tr( "Recent (%1)" ).arg( collection );
512 if ( mExpressionGroups.contains( name ) )
513 {
514 QgsExpressionItem *node = mExpressionGroups.value( name );
515 node->removeRows( 0, node->rowCount() );
516 }
517
518 QgsSettings settings;
519 const QString location = QStringLiteral( "/expressions/recent/%1" ).arg( collection );
520 const QStringList expressions = settings.value( location ).toStringList();
521 int i = 0;
522 for ( const QString &expression : expressions )
523 {
524 QString help = formatRecentExpressionHelp( expression, expression );
525 QString label = expression;
526 label.replace( '\n', ' ' );
527 registerItem( name, label, expression, help, QgsExpressionItem::ExpressionNode, false, i );
528 i++;
529 }
530}
531
532void QgsExpressionTreeView::saveToRecent( const QString &expressionText, const QString &collection )
533{
534 QgsSettings settings;
535 QString location = QStringLiteral( "/expressions/recent/%1" ).arg( collection );
536 QStringList expressions = settings.value( location ).toStringList();
537 expressions.removeAll( expressionText );
538
539 expressions.prepend( expressionText );
540
541 while ( expressions.count() > 20 )
542 {
543 expressions.pop_back();
544 }
545
546 settings.setValue( location, expressions );
547 loadRecent( collection );
548}
549
550void QgsExpressionTreeView::saveToUserExpressions( const QString &label, const QString &expression, const QString &helpText )
551{
552 QgsSettings settings;
553 const QString location = QStringLiteral( "user" );
554 settings.beginGroup( location, QgsSettings::Section::Expressions );
555 settings.beginGroup( label );
556 settings.setValue( QStringLiteral( "expression" ), expression );
557 settings.setValue( QStringLiteral( "helpText" ), helpText );
559 // Scroll
560 const QModelIndexList idxs { mModel->match( mModel->index( 0, 0 ), Qt::DisplayRole, label, 1, Qt::MatchFlag::MatchRecursive ) };
561 if ( !idxs.isEmpty() )
562 {
563 scrollTo( idxs.first() );
564 }
565}
566
568{
569 QgsSettings settings;
570 settings.remove( QStringLiteral( "user/%1" ).arg( label ), QgsSettings::Section::Expressions );
572}
573
574// this is potentially very slow if there are thousands of user expressions, every time entire cleanup and load
576{
577 // Cleanup
578 if ( mExpressionGroups.contains( QStringLiteral( "UserGroup" ) ) )
579 {
580 QgsExpressionItem *node = mExpressionGroups.value( QStringLiteral( "UserGroup" ) );
581 node->removeRows( 0, node->rowCount() );
582 }
583
584 QgsSettings settings;
585 const QString location = QStringLiteral( "user" );
586 settings.beginGroup( location, QgsSettings::Section::Expressions );
587 QString helpText;
588 QString expression;
589 int i = 0;
590 mUserExpressionLabels = settings.childGroups();
591 for ( const auto &label : std::as_const( mUserExpressionLabels ) )
592 {
593 settings.beginGroup( label );
594 expression = settings.value( QStringLiteral( "expression" ) ).toString();
595 helpText = formatUserExpressionHelp( label, expression, settings.value( QStringLiteral( "helpText" ) ).toString() );
596 registerItem( QStringLiteral( "UserGroup" ), label, expression, helpText, QgsExpressionItem::ExpressionNode, false, i++ );
597 settings.endGroup();
598 }
599}
600
602{
603 return mUserExpressionLabels;
604}
605
607{
608 const QString group = QStringLiteral( "user" );
609 QgsSettings settings;
610 QJsonArray exportList;
611 QJsonObject exportObject {
612 { "qgis_version", Qgis::version() },
613 { "exported_at", QDateTime::currentDateTime().toString( Qt::ISODate ) },
614 { "author", QgsApplication::userFullName() },
615 { "expressions", exportList }
616 };
617
619
620 mUserExpressionLabels = settings.childGroups();
621
622 for ( const QString &label : std::as_const( mUserExpressionLabels ) )
623 {
624 settings.beginGroup( label );
625
626 const QString expression = settings.value( QStringLiteral( "expression" ) ).toString();
627 const QString helpText = settings.value( QStringLiteral( "helpText" ) ).toString();
628 const QJsonObject expressionObject {
629 { "name", label },
630 { "type", "expression" },
631 { "expression", expression },
632 { "group", group },
633 { "description", helpText }
634 };
635 exportList.push_back( expressionObject );
636
637 settings.endGroup();
638 }
639
640 exportObject[QStringLiteral( "expressions" )] = exportList;
641 QJsonDocument exportJson = QJsonDocument( exportObject );
642
643 return exportJson;
644}
645
646void QgsExpressionTreeView::loadExpressionsFromJson( const QJsonDocument &expressionsDocument )
647{
648 // if the root of the json document is not an object, it means it's a wrong file
649 if ( !expressionsDocument.isObject() )
650 return;
651
652 QJsonObject expressionsObject = expressionsDocument.object();
653
654 // validate json for manadatory fields
655 if ( !expressionsObject[QStringLiteral( "qgis_version" )].isString()
656 || !expressionsObject[QStringLiteral( "exported_at" )].isString()
657 || !expressionsObject[QStringLiteral( "author" )].isString()
658 || !expressionsObject[QStringLiteral( "expressions" )].isArray() )
659 return;
660
661 // validate versions
662 QVersionNumber qgisJsonVersion = QVersionNumber::fromString( expressionsObject[QStringLiteral( "qgis_version" )].toString() );
663 QVersionNumber qgisVersion = QVersionNumber::fromString( Qgis::version() );
664
665 // if the expressions are from newer version of QGIS, we ask the user to confirm
666 // they want to proceed
667 if ( qgisJsonVersion > qgisVersion )
668 {
669 QMessageBox::StandardButtons buttons = QMessageBox::Yes | QMessageBox::No;
670 switch ( QMessageBox::question( this, tr( "QGIS Version Mismatch" ), tr( "The imported expressions are from newer version of QGIS (%1) "
671 "and some of the expression might not work the current version (%2). "
672 "Are you sure you want to continue?" )
673 .arg( qgisJsonVersion.toString(), qgisVersion.toString() ),
674 buttons ) )
675 {
676 case QMessageBox::No:
677 return;
678
679 case QMessageBox::Yes:
680 break;
681
682 default:
683 break;
684 }
685 }
686
687 // we store the number of
688 QStringList skippedExpressionLabels;
689 bool isApplyToAll = false;
690 bool isOkToOverwrite = false;
691
692 QgsSettings settings;
693 settings.beginGroup( QStringLiteral( "user" ), QgsSettings::Section::Expressions );
694 mUserExpressionLabels = settings.childGroups();
695
696 const QJsonArray expressions = expressionsObject[QStringLiteral( "expressions" )].toArray();
697 for ( const QJsonValue &&expressionValue : expressions )
698 {
699 // validate the type of the array element, can be anything
700 if ( !expressionValue.isObject() )
701 {
702 // try to stringify and put and indicator what happened
703 skippedExpressionLabels.append( expressionValue.toString() );
704 continue;
705 }
706
707 QJsonObject expressionObj = expressionValue.toObject();
708
709 // make sure the required keys are the correct types
710 if ( !expressionObj[QStringLiteral( "name" )].isString()
711 || !expressionObj[QStringLiteral( "type" )].isString()
712 || !expressionObj[QStringLiteral( "expression" )].isString()
713 || !expressionObj[QStringLiteral( "group" )].isString()
714 || !expressionObj[QStringLiteral( "description" )].isString() )
715 {
716 // try to stringify and put an indicator what happened. Try to stringify the name, if fails, go with the expression.
717 if ( !expressionObj[QStringLiteral( "name" )].toString().isEmpty() )
718 skippedExpressionLabels.append( expressionObj[QStringLiteral( "name" )].toString() );
719 else
720 skippedExpressionLabels.append( expressionObj[QStringLiteral( "expression" )].toString() );
721
722 continue;
723 }
724
725 // we want to import only items of type expression for now
726 if ( expressionObj[QStringLiteral( "type" )].toString() != QLatin1String( "expression" ) )
727 {
728 skippedExpressionLabels.append( expressionObj[QStringLiteral( "name" )].toString() );
729 continue;
730 }
731
732 // we want to import only items of type expression for now
733 if ( expressionObj[QStringLiteral( "group" )].toString() != QLatin1String( "user" ) )
734 {
735 skippedExpressionLabels.append( expressionObj[QStringLiteral( "name" )].toString() );
736 continue;
737 }
738
739 const QString label = expressionObj[QStringLiteral( "name" )].toString();
740 const QString expression = expressionObj[QStringLiteral( "expression" )].toString();
741 const QString helpText = expressionObj[QStringLiteral( "description" )].toString();
742
743 // make sure they have valid name
744 if ( label.contains( QLatin1String( "\\" ) ) || label.contains( '/' ) )
745 {
746 skippedExpressionLabels.append( expressionObj[QStringLiteral( "name" )].toString() );
747 continue;
748 }
749
750 settings.beginGroup( label );
751 const QString oldExpression = settings.value( QStringLiteral( "expression" ) ).toString();
752 settings.endGroup();
753
754 // TODO would be nice to skip the cases when labels and expressions match
755 if ( mUserExpressionLabels.contains( label ) && expression != oldExpression )
756 {
757 if ( !isApplyToAll )
758 showMessageBoxConfirmExpressionOverwrite( isApplyToAll, isOkToOverwrite, label, oldExpression, expression );
759
760 if ( isOkToOverwrite )
761 saveToUserExpressions( label, expression, helpText );
762 else
763 {
764 skippedExpressionLabels.append( label );
765 continue;
766 }
767 }
768 else
769 {
770 saveToUserExpressions( label, expression, helpText );
771 }
772 }
773
775
776 if ( !skippedExpressionLabels.isEmpty() )
777 {
778 QStringList skippedExpressionLabelsQuoted;
779 skippedExpressionLabelsQuoted.reserve( skippedExpressionLabels.size() );
780 for ( const QString &skippedExpressionLabel : skippedExpressionLabels )
781 skippedExpressionLabelsQuoted.append( QStringLiteral( "'%1'" ).arg( skippedExpressionLabel ) );
782
783 QMessageBox::information( this, tr( "Skipped Expression Imports" ), QStringLiteral( "%1\n%2" ).arg( tr( "The following expressions have been skipped:" ), skippedExpressionLabelsQuoted.join( QLatin1String( ", " ) ) ) );
784 }
785}
786
787const QList<QgsExpressionItem *> QgsExpressionTreeView::findExpressions( const QString &label )
788{
789 QList<QgsExpressionItem *> result;
790 const QList<QStandardItem *> found { mModel->findItems( label, Qt::MatchFlag::MatchRecursive ) };
791 result.reserve( found.size() );
792 std::transform( found.begin(), found.end(), std::back_inserter( result ), []( QStandardItem *item ) -> QgsExpressionItem * { return static_cast<QgsExpressionItem *>( item ); } );
793 return result;
794}
795
796void QgsExpressionTreeView::showMessageBoxConfirmExpressionOverwrite(
797 bool &isApplyToAll,
798 bool &isOkToOverwrite,
799 const QString &label,
800 const QString &oldExpression,
801 const QString &newExpression
802)
803{
804 QMessageBox::StandardButtons buttons = QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll;
805 switch ( QMessageBox::question( this, tr( "Expression Overwrite" ), tr( "The expression with label '%1' was already defined."
806 "The old expression \"%2\" will be overwritten by \"%3\"."
807 "Are you sure you want to overwrite the expression?" )
808 .arg( label, oldExpression, newExpression ),
809 buttons ) )
810 {
811 case QMessageBox::NoToAll:
812 isApplyToAll = true;
813 isOkToOverwrite = false;
814 break;
815
816 case QMessageBox::No:
817 isApplyToAll = false;
818 isOkToOverwrite = false;
819 break;
820
821 case QMessageBox::YesToAll:
822 isApplyToAll = true;
823 isOkToOverwrite = true;
824 break;
825
826 case QMessageBox::Yes:
827 isApplyToAll = false;
828 isOkToOverwrite = true;
829 break;
830
831 default:
832 break;
833 }
834}
835
836
837// ****************************
838// ****************************
839// QgsExpressionItemSearchProxy
840// ****************************
841
842
844{
845 setFilterCaseSensitivity( Qt::CaseInsensitive );
846}
847
848bool QgsExpressionItemSearchProxy::filterAcceptsRow( int source_row, const QModelIndex &source_parent ) const
849{
850 QModelIndex index = sourceModel()->index( source_row, 0, source_parent );
851 const QgsExpressionItem::ItemType itemType = QgsExpressionItem::ItemType( sourceModel()->data( index, QgsExpressionItem::ITEM_TYPE_ROLE ).toInt() );
852
853 if ( itemType == QgsExpressionItem::Header )
854 {
855 // show header if any child item matches
856 int count = sourceModel()->rowCount( index );
857 bool matchchild = false;
858 for ( int i = 0; i < count; ++i )
859 {
860 if ( filterAcceptsRow( i, index ) )
861 {
862 matchchild = true;
863 break;
864 }
865 }
866 return matchchild;
867 }
868
869 // check match of item label or tags
870 const QString name = sourceModel()->data( index, Qt::DisplayRole ).toString();
871 if ( name.contains( mFilterString, Qt::CaseInsensitive ) )
872 {
873 return true;
874 }
875
876 const QStringList tags = sourceModel()->data( index, QgsExpressionItem::SEARCH_TAGS_ROLE ).toStringList();
877 return std::any_of( tags.begin(), tags.end(), [this]( const QString &tag ) {
878 return tag.contains( mFilterString, Qt::CaseInsensitive );
879 } );
880}
881
883{
884 mFilterString = string;
885 invalidate();
886}
887
888bool QgsExpressionItemSearchProxy::lessThan( const QModelIndex &left, const QModelIndex &right ) const
889{
890 int leftSort = sourceModel()->data( left, QgsExpressionItem::CUSTOM_SORT_ROLE ).toInt();
891 int rightSort = sourceModel()->data( right, QgsExpressionItem::CUSTOM_SORT_ROLE ).toInt();
892 if ( leftSort != rightSort )
893 return leftSort < rightSort;
894
895 QString leftString = sourceModel()->data( left, Qt::DisplayRole ).toString();
896 QString rightString = sourceModel()->data( right, Qt::DisplayRole ).toString();
897
898 //ignore $ prefixes when sorting
899 if ( leftString.startsWith( '$' ) )
900 leftString = leftString.mid( 1 );
901 if ( rightString.startsWith( '$' ) )
902 rightString = rightString.mid( 1 );
903
904 return QString::localeAwareCompare( leftString, rightString ) < 0;
905}
static QString version()
Version string.
Definition qgis.cpp:259
static QString userFullName()
Returns the user's operating system login account full display name.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QString description(const QString &name) const
Returns a translated description string for the variable with specified name.
QStringList functionNames() const
Retrieves a list of function names contained in the context.
bool isHighlightedFunction(const QString &name) const
Returns true if the specified function name is intended to be highlighted to the user.
QStringList filteredVariableNames() const
Returns a filtered list of variables names set by all scopes in the context.
bool isHighlightedVariable(const QString &name) const
Returns true if the specified variable name is intended to be highlighted to the user.
QgsExpressionFunction * function(const QString &name) const
Fetches a matching function from the context.
QVariant variable(const QString &name) const
Fetches a matching variable from the context.
A abstract base class for defining QgsExpression functions.
bool isContextual() const
Returns whether the function is only available if provided by a QgsExpressionContext object.
int params() const
The number of parameters this function takes.
QStringList groups() const
Returns a list of the groups the function belongs to.
virtual bool isDeprecated() const
Returns true if the function is deprecated and should not be presented as a valid option to users in ...
QString name() const
The name of the function.
const QString helpText() const
The help text for the function.
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override
void setFilterString(const QString &string)
Sets the search filter string.
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
An expression item that can be used in the QgsExpressionBuilderWidget tree.
static const int LAYER_ID_ROLE
Layer ID role.
QString getExpressionText() const
static const int SEARCH_TAGS_ROLE
Search tags role.
static const int ITEM_TYPE_ROLE
Item type role.
static const int CUSTOM_SORT_ROLE
Custom sort order role.
QgsExpressionItem::ItemType getItemType() const
Gets the type of expression item, e.g., header, field, ExpressionNode.
static const int ITEM_NAME_ROLE
Item name role.
Implementation of this interface can be implemented to allow QgsExpressionTreeView instance to provid...
virtual QMenu * createContextMenu(QgsExpressionItem *item)
Returns a newly created menu instance.
QgsProject * project()
Returns the project currently associated with the widget.
void refresh()
Refreshes the content of the tree.
void setProject(QgsProject *project)
Sets the project currently associated with the widget.
void saveToUserExpressions(const QString &label, const QString &expression, const QString &helpText)
Stores the user expression with given label and helpText.
QgsExpressionItem * currentItem() const
Returns the current item or a nullptr.
void setLayer(QgsVectorLayer *layer)
Sets layer in order to get the fields and values.
void setMenuProvider(MenuProvider *provider)
Sets the menu provider.
QStringList userExpressionLabels() const
Returns the user expression labels.
void expressionItemDoubleClicked(const QString &text)
Emitted when a expression item is double clicked.
void currentExpressionItemChanged(QgsExpressionItem *item)
Emitter when the current expression item changed.
QJsonDocument exportUserExpressions()
Create the expressions JSON document storing all the user expressions to be exported.
QgsExpressionTreeView(QWidget *parent=nullptr)
Constructor.
void loadExpressionsFromJson(const QJsonDocument &expressionsDocument)
Load and permanently store the expressions from the expressions JSON document.
void saveToRecent(const QString &expressionText, const QString &collection="generic")
Adds the current expression to the given collection.
void setSearchText(const QString &text)
Sets the text to filter the expression tree.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context for the tree view.
const QList< QgsExpressionItem * > findExpressions(const QString &label)
Returns the list of expression items matching a label.
void removeFromUserExpressions(const QString &label)
Removes the expression label from the user stored expressions.
void loadRecent(const QString &collection=QStringLiteral("generic"))
Loads the recent expressions from the given collection.
void loadUserExpressions()
Loads the user expressions.
Q_DECL_DEPRECATED QStandardItemModel * model()
Returns a pointer to the dialog's function item model.
void loadFieldNames(const QgsFields &fields)
This allows loading fields without specifying a layer.
static const QList< QgsExpressionFunction * > & Functions()
static int functionCount()
Returns the number of functions defined in the parser.
static QString variableHelpText(const QString &variableName)
Returns the help text for a specified variable.
static QString formatPreviewString(const QVariant &value, bool htmlOutput=true, int maximumPreviewLength=60)
Formats an expression result for friendly display to the user.
static QStringList tags(const QString &name)
Returns a string list of search tags for a specified function.
static QString group(const QString &group)
Returns the translated name for a function group.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
QString name
Definition qgsfield.h:62
QString displayNameWithAlias() const
Returns the name to use when displaying this field and adds the alias in parenthesis if it is defined...
Definition qgsfield.cpp:103
Container of fields for a vector layer.
Definition qgsfields.h:46
int count
Definition qgsfields.h:50
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
QIcon iconForField(int fieldIdx, bool considerOrigin=false) const
Returns an icon corresponding to a field index, based on the field's type and source.
static QIcon iconForLayer(const QgsMapLayer *layer)
Returns the icon corresponding to a specified map layer.
Base class for all map layer types.
Definition qgsmaplayer.h:76
QString name
Definition qgsmaplayer.h:80
QString id
Definition qgsmaplayer.h:79
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
Represents a relationship between two vector layers.
Definition qgsrelation.h:44
QString name
Definition qgsrelation.h:50
QString id
Definition qgsrelation.h:47
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
QStringList childGroups(Qgis::SettingsOrigin origin=Qgis::SettingsOrigin::Any) const
Returns a list of all key top-level groups that contain keys that can be read using the QSettings obj...
void endGroup()
Resets the group to what it was before the corresponding beginGroup() call.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void beginGroup(const QString &prefix, QgsSettings::Section section=QgsSettings::NoSection)
Appends prefix to the current group.
void remove(const QString &key, QgsSettings::Section section=QgsSettings::NoSection)
Removes the setting key and any sub-settings of key in a section.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
Represents a vector layer which manages a vector based data sets.
QString formatLayerHelp(const QgsMapLayer *layer)
Returns a HTML formatted string for use as a layer item help.
QString formatUserExpressionHelp(const QString &label, const QString &expression, const QString &description)
Returns a HTML formatted string for use as a user expression item help.
QString formatVariableHelp(const QString &variable, const QString &description, bool showValue, const QVariant &value)
Returns a HTML formatted string for use as a variable item help.
QString formatRecentExpressionHelp(const QString &label, const QString &expression)
Returns a HTML formatted string for use as a recent expression item help.
QString formatRelationHelp(const QgsRelation &relation)
Returns a HTML formatted string for use as a relation item help.