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