37#include <QDomDocument>
44 , mMaximumScale( scaleMinDenom )
45 , mMinimumScale( scaleMaxDenom )
46 , mFilterExp( filterExp )
49 , mElseRule( elseRule )
52 mFilterExp = QStringLiteral(
"ELSE" );
54 mRuleKey = QUuid::createUuid().toString();
60 qDeleteAll( mChildren );
66 if ( mFilterExp.trimmed().compare( QLatin1String(
"ELSE" ), Qt::CaseInsensitive ) == 0 )
71 else if ( mFilterExp.trimmed().isEmpty() )
79 mFilter = std::make_unique< QgsExpression >( mFilterExp );
85 mChildren.append( rule );
92 mChildren.insert( i, rule );
99 mChildren.removeAll( rule );
106 delete mChildren.takeAt( i );
112 mChildren.removeAll( rule );
113 rule->mParent =
nullptr;
120 Rule *rule = mChildren.takeAt( i );
121 rule->mParent =
nullptr;
130 if ( key == mRuleKey )
133 const auto constMChildren = mChildren;
134 for (
Rule *rule : constMChildren )
136 Rule *r = rule->findRuleByKey( key );
143void QgsRuleBasedRenderer::Rule::updateElseRules()
146 const auto constMChildren = mChildren;
147 for (
Rule *rule : constMChildren )
149 if ( rule->isElse() )
156 mFilterExp = QStringLiteral(
"ELSE" );
174 if ( !mChildren.empty() )
176 for (
const Rule *rule : mChildren )
179 if ( !rule->accept( visitor ) )
193 off.fill( QChar(
' ' ), indent );
194 QString symbolDump = ( mSymbol ? mSymbol->dump() : QStringLiteral(
"[]" ) );
195 QString msg = off + QStringLiteral(
"RULE %1 - scale [%2,%3] - filter %4 - symbol %5\n" )
196 .arg( mLabel ).arg( mMaximumScale ).arg( mMinimumScale )
197 .arg( mFilterExp, symbolDump );
200 const auto constMChildren = mChildren;
201 for (
Rule *rule : constMChildren )
203 lst.append( rule->dump( indent + 2 ) );
205 msg += lst.join( QLatin1Char(
'\n' ) );
214 attrs.unite( mFilter->referencedColumns() );
216 attrs.unite( mSymbol->usedAttributes( context ) );
219 const auto constMChildren = mChildren;
220 for (
Rule *rule : constMChildren )
222 attrs.unite( rule->usedAttributes( context ) );
229 if ( mFilter && mFilter->needsGeometry() )
232 const auto constMChildren = mChildren;
233 for (
Rule *rule : constMChildren )
235 if ( rule->needsGeometry() )
246 lst.append( mSymbol.get() );
248 const auto constMChildren = mChildren;
249 for (
Rule *rule : constMChildren )
251 lst += rule->symbols( context );
258 mSymbol.reset( sym );
263 mFilterExp = filterExp;
270 if ( currentLevel != -1 )
272 lst <<
QgsLegendSymbolItem( mSymbol.get(), mLabel, mRuleKey,
true, mMaximumScale, mMinimumScale, currentLevel, mParent ? mParent->mRuleKey : QString() );
275 for ( RuleList::const_iterator it = mChildren.constBegin(); it != mChildren.constEnd(); ++it )
286 if ( ! mFilter || mElseRule || ! context )
315 Rule *newrule =
new Rule( sym, mMaximumScale, mMinimumScale, mFilterExp, mLabel, mDescription );
318 const auto constMChildren = mChildren;
319 for (
Rule *rule : constMChildren )
326 QDomElement ruleElem = doc.createElement( QStringLiteral(
"rule" ) );
330 int symbolIndex = symbolMap.size();
331 symbolMap[QString::number( symbolIndex )] = mSymbol.get();
332 ruleElem.setAttribute( QStringLiteral(
"symbol" ), symbolIndex );
334 if ( !mFilterExp.isEmpty() )
335 ruleElem.setAttribute( QStringLiteral(
"filter" ), mFilterExp );
336 if ( mMaximumScale != 0 )
337 ruleElem.setAttribute( QStringLiteral(
"scalemindenom" ), mMaximumScale );
338 if ( mMinimumScale != 0 )
339 ruleElem.setAttribute( QStringLiteral(
"scalemaxdenom" ), mMinimumScale );
340 if ( !mLabel.isEmpty() )
341 ruleElem.setAttribute( QStringLiteral(
"label" ), mLabel );
342 if ( !mDescription.isEmpty() )
343 ruleElem.setAttribute( QStringLiteral(
"description" ), mDescription );
345 ruleElem.setAttribute( QStringLiteral(
"checkstate" ), 0 );
346 ruleElem.setAttribute( QStringLiteral(
"key" ), mRuleKey );
348 const auto constMChildren = mChildren;
349 for (
Rule *rule : constMChildren )
351 ruleElem.appendChild( rule->save( doc, symbolMap ) );
360 toSld( doc, element, context );
367 if (
symbols( context ).isEmpty() )
371 QVariantMap props = oldProps;
372 if ( !mFilterExp.isEmpty() )
374 QString
filter = props.value( QStringLiteral(
"filter" ), QString() ).toString();
376 filter += QLatin1String(
" AND " );
378 props[ QStringLiteral(
"filter" )] =
filter;
386 QDomElement ruleElem = doc.createElement( QStringLiteral(
"se:Rule" ) );
390 QDomElement nameElem = doc.createElement( QStringLiteral(
"se:Name" ) );
391 nameElem.appendChild( doc.createTextNode( mLabel ) );
392 ruleElem.appendChild( nameElem );
394 if ( !mLabel.isEmpty() || !mDescription.isEmpty() )
396 QDomElement descrElem = doc.createElement( QStringLiteral(
"se:Description" ) );
397 if ( !mLabel.isEmpty() )
399 QDomElement titleElem = doc.createElement( QStringLiteral(
"se:Title" ) );
400 titleElem.appendChild( doc.createTextNode( mLabel ) );
401 descrElem.appendChild( titleElem );
403 if ( !mDescription.isEmpty() )
405 QDomElement abstractElem = doc.createElement( QStringLiteral(
"se:Abstract" ) );
406 abstractElem.appendChild( doc.createTextNode( mDescription ) );
407 descrElem.appendChild( abstractElem );
409 ruleElem.appendChild( descrElem );
412 if ( !props.value( QStringLiteral(
"filter" ), QString() ).toString().isEmpty() )
420 mSymbol->toSld( doc, ruleElem, exportContext );
426 element.appendChild( ruleElem );
432 for (
Rule *rule : std::as_const( mChildren ) )
434 if ( !rule->toSld( doc, element, exportContext ) )
443 mActiveChildren.clear();
456 mSymbol->startRender( context, fields );
460 QStringList subfilters;
461 const auto constMChildren = mChildren;
462 for (
Rule *rule : constMChildren )
465 if ( rule->startRender( context, fields, subfilter ) )
468 mActiveChildren.append( rule );
469 subfilters.append( subfilter );
477 if ( subfilters.length() > 1 || !subfilters.value( 0 ).isEmpty() )
479 if ( subfilters.contains( QStringLiteral(
"TRUE" ) ) )
481 sf = QStringLiteral(
"TRUE" );
492 else if ( subfilters.count() > 50 )
494 std::function<QString(
const QStringList & )>bt = [ &bt ](
const QStringList & subf )
496 if ( subf.count( ) == 1 )
500 else if ( subf.count( ) == 2 )
502 return subf.join( QLatin1String(
") OR (" ) ).prepend(
'(' ).append(
')' );
506 int midpos =
static_cast<int>( subf.length() / 2 );
507 return QStringLiteral(
"(%1) OR (%2)" ).arg( bt( subf.mid( 0, midpos ) ), bt( subf.mid( midpos ) ) );
510 sf = bt( subfilters );
514 sf = subfilters.join( QLatin1String(
") OR (" ) ).prepend(
'(' ).append(
')' );
526 if ( mSymbol || sf.isEmpty() )
527 filter = QStringLiteral(
"TRUE" );
533 else if ( !mFilterExp.trimmed().isEmpty() && !sf.isEmpty() )
534 filter = QStringLiteral(
"(%1) AND (%2)" ).arg( mFilterExp, sf );
535 else if ( !mFilterExp.trimmed().isEmpty() )
537 else if ( sf.isEmpty() )
538 filter = QStringLiteral(
"TRUE" );
549 return !mActiveChildren.empty();
554 QSet<int> symbolZLevelsSet;
560 for (
int i = 0; i < mSymbol->symbolLayerCount(); i++ )
562 symbolZLevelsSet.insert( mSymbol->symbolLayer( i )->renderingPass() );
567 QList<Rule *>::iterator it;
568 for ( it = mActiveChildren.begin(); it != mActiveChildren.end(); ++it )
573 return symbolZLevelsSet;
580 for (
int i = 0; i < mSymbol->symbolLayerCount(); i++ )
582 int normLevel = zLevelsToNormLevels.value( mSymbol->symbolLayer( i )->renderingPass() );
583 mSymbolNormZLevels.insert( normLevel );
588 const auto constMActiveChildren = mActiveChildren;
589 for (
Rule *rule : constMActiveChildren )
591 rule->setNormZLevels( zLevelsToNormLevels );
601 bool rendered =
false;
604 if ( mSymbol && mIsActive )
607 const auto constMSymbolNormZLevels = mSymbolNormZLevels;
608 for (
int normZLevel : constMSymbolNormZLevels )
611 renderQueue[normZLevel].jobs.append(
new RenderJob( featToRender, mSymbol.get() ) );
616 bool matchedAChild =
false;
619 const auto constMChildren = mChildren;
620 for (
Rule *rule : constMChildren )
623 if ( !rule->isElse() )
625 const RenderResult res = rule->renderFeature( featToRender, context, renderQueue );
633 if ( !matchedAChild )
635 const auto constMElseRules = mElseRules;
636 for (
Rule *rule : constMElseRules )
638 const RenderResult res = rule->renderFeature( featToRender, context, renderQueue );
643 if ( !mIsActive || ( mSymbol && !rendered ) || ( matchedAChild && !rendered ) )
659 const auto constMActiveChildren = mActiveChildren;
660 for (
Rule *rule : constMActiveChildren )
662 if ( rule->isElse() )
664 if ( rule->children().isEmpty() )
667 lst.removeOne( rule );
676 return rule->willRenderFeature( feature, context );
679 else if ( rule->willRenderFeature( feature, context ) )
693 lst.append( mSymbol.get() );
695 const auto constMActiveChildren = mActiveChildren;
696 for (
Rule *rule : constMActiveChildren )
698 lst += rule->symbolsForFeature( feature, context );
709 res.insert( mRuleKey );
712 bool matchedNonElseRule =
false;
713 for (
Rule *rule : std::as_const( mActiveChildren ) )
715 if ( rule->isElse() )
719 if ( rule->willRenderFeature( feature, context ) )
721 res.unite( rule->legendKeysForFeature( feature, context ) );
722 matchedNonElseRule =
true;
727 if ( !matchedNonElseRule )
729 for (
Rule *rule : std::as_const( mActiveChildren ) )
731 if ( rule->isElse() )
733 if ( rule->children().isEmpty() )
736 lst.removeOne( rule );
740 res.unite( rule->legendKeysForFeature( feature, context ) );
745 res.unite( rule->legendKeysForFeature( feature, context ) );
764 listChildren = mActiveChildren;
766 for (
Rule *rule : std::as_const( listChildren ) )
768 lst += rule->rulesForFeature( feature, context, onlyActive );
776 mSymbol->stopRender( context );
778 const auto constMActiveChildren = mActiveChildren;
779 for (
Rule *rule : constMActiveChildren )
781 rule->stopRender( context );
784 mActiveChildren.clear();
785 mSymbolNormZLevels.clear();
790 QString symbolIdx = ruleElem.attribute( QStringLiteral(
"symbol" ) );
792 if ( !symbolIdx.isEmpty() )
794 if ( symbolMap.contains( symbolIdx ) )
796 symbol = symbolMap.take( symbolIdx );
800 QgsDebugError(
"symbol for rule " + symbolIdx +
" not found!" );
804 QString filterExp = ruleElem.attribute( QStringLiteral(
"filter" ) );
805 QString
label = ruleElem.attribute( QStringLiteral(
"label" ) );
806 QString
description = ruleElem.attribute( QStringLiteral(
"description" ) );
807 int scaleMinDenom = ruleElem.attribute( QStringLiteral(
"scalemindenom" ), QStringLiteral(
"0" ) ).toInt();
808 int scaleMaxDenom = ruleElem.attribute( QStringLiteral(
"scalemaxdenom" ), QStringLiteral(
"0" ) ).toInt();
811 ruleKey = ruleElem.attribute( QStringLiteral(
"key" ) );
813 ruleKey = QUuid::createUuid().toString();
819 rule->
setActive( ruleElem.attribute( QStringLiteral(
"checkstate" ), QStringLiteral(
"1" ) ).toInt() );
821 QDomElement childRuleElem = ruleElem.firstChildElement( QStringLiteral(
"rule" ) );
822 while ( !childRuleElem.isNull() )
824 Rule *childRule =
create( childRuleElem, symbolMap );
831 QgsDebugError( QStringLiteral(
"failed to init a child rule!" ) );
833 childRuleElem = childRuleElem.nextSiblingElement( QStringLiteral(
"rule" ) );
845 l +=
c->descendants();
852 if ( ruleElem.localName() != QLatin1String(
"Rule" ) )
854 QgsDebugError( QStringLiteral(
"invalid element: Rule element expected, %1 found!" ).arg( ruleElem.tagName() ) );
859 int scaleMinDenom = 0, scaleMaxDenom = 0;
863 QDomElement childElem = ruleElem.firstChildElement();
864 while ( !childElem.isNull() )
866 if ( childElem.localName() == QLatin1String(
"Name" ) )
870 if (
label.isEmpty() )
871 label = childElem.firstChild().nodeValue();
873 else if ( childElem.localName() == QLatin1String(
"Description" ) )
876 QDomElement titleElem = childElem.firstChildElement( QStringLiteral(
"Title" ) );
877 if ( !titleElem.isNull() )
879 label = titleElem.firstChild().nodeValue();
882 QDomElement abstractElem = childElem.firstChildElement( QStringLiteral(
"Abstract" ) );
883 if ( !abstractElem.isNull() )
885 description = abstractElem.firstChild().nodeValue();
888 else if ( childElem.localName() == QLatin1String(
"Abstract" ) )
893 else if ( childElem.localName() == QLatin1String(
"Title" ) )
896 label = childElem.firstChild().nodeValue();
898 else if ( childElem.localName() == QLatin1String(
"Filter" ) )
903 if (
filter->hasParserError() )
909 filterExp =
filter->expression();
914 else if ( childElem.localName() == QLatin1String(
"ElseFilter" ) )
916 filterExp = QLatin1String(
"ELSE" );
919 else if ( childElem.localName() == QLatin1String(
"MinScaleDenominator" ) )
922 int v = childElem.firstChild().nodeValue().toInt( &ok );
926 else if ( childElem.localName() == QLatin1String(
"MaxScaleDenominator" ) )
929 int v = childElem.firstChild().nodeValue().toInt( &ok );
933 else if ( childElem.localName().endsWith( QLatin1String(
"Symbolizer" ) ) )
939 childElem = childElem.nextSiblingElement();
944 if ( !layers.isEmpty() )
1002 std::function< void(
Rule *rule ) > exploreRule;
1003 exploreRule = [&res, &exploreRule](
Rule * rule )
1016 exploreRule( child );
1028 bool drawVertexMarker )
1047 QSet<int> symbolZLevelsSet =
mRootRule->collectZLevels();
1048 QList<int> symbolZLevels( symbolZLevelsSet.begin(), symbolZLevelsSet.end() );
1049 std::sort( symbolZLevels.begin(), symbolZLevels.end() );
1053 QMap<int, int> zLevelsToNormLevels;
1054 int maxNormLevel = -1;
1055 const auto constSymbolZLevels = symbolZLevels;
1056 for (
int zLevel : constSymbolZLevels )
1058 zLevelsToNormLevels[zLevel] = ++maxNormLevel;
1060 QgsDebugMsgLevel( QStringLiteral(
"zLevel %1 -> %2" ).arg( zLevel ).arg( maxNormLevel ), 4 );
1063 mRootRule->setNormZLevels( zLevelsToNormLevels );
1083 for (
const RenderLevel &level : constMRenderQueue )
1087 for (
const RenderJob *job : std::as_const( level.jobs ) )
1094 for (
int i = 0; i < count; i++ )
1101 int flags = job->ftr.flags;
1126 return mRootRule->usedAttributes( context );
1143 Q_ASSERT( origDescendants.count() == clonedDescendants.count() );
1144 for (
int i = 0; i < origDescendants.count(); ++i )
1145 clonedDescendants[i]->setRuleKey( origDescendants[i]->ruleKey() );
1157 toSld( doc, element, context );
1162 return mRootRule->toSld( doc, element, context );
1174 rendererElem.setAttribute( QStringLiteral(
"type" ), QStringLiteral(
"RuleRenderer" ) );
1179 rulesElem.setTagName( QStringLiteral(
"rules" ) );
1180 rendererElem.appendChild( rulesElem );
1183 rendererElem.appendChild( symbolsElem );
1187 return rendererElem;
1198 return rule ? rule->
active() :
true;
1215 std::function<QString(
Rule *rule )> ruleToExpression;
1216 ruleToExpression = [&ruleToExpression](
Rule * rule ) -> QString
1222 QStringList otherRules;
1223 const QList<QgsRuleBasedRenderer::Rule *> siblings = rule->
parent()->
children();
1224 for (
Rule *sibling : siblings )
1226 if ( sibling == rule || sibling->
isElse() )
1229 const QString siblingExpression = ruleToExpression( sibling );
1230 if ( siblingExpression.isEmpty() )
1231 return QStringLiteral(
"FALSE" );
1233 otherRules.append( siblingExpression );
1236 if ( otherRules.empty() )
1237 return QStringLiteral(
"TRUE" );
1240 otherRules.size() > 1
1241 ? QStringLiteral(
"NOT ((%1))" ).arg( otherRules.join( QLatin1String(
") OR (" ) ) )
1242 : QStringLiteral(
"NOT (%1)" ).arg( otherRules.at( 0 ) )
1247 QStringList ruleParts;
1252 ruleParts.append( QStringLiteral(
"@map_scale <= %1" ).arg( rule->
minimumScale() ) );
1255 ruleParts.append( QStringLiteral(
"@map_scale >= %1" ).arg( rule->
maximumScale() ) );
1257 if ( !ruleParts.empty() )
1260 ruleParts.size() > 1
1261 ? QStringLiteral(
"(%1)" ).arg( ruleParts.join( QLatin1String(
") AND (" ) ) )
1275 const QString ruleFilter = ruleToExpression( rule );
1276 if ( !ruleFilter.isEmpty() )
1277 parts.append( ruleFilter );
1283 return parts.empty() ? QStringLiteral(
"TRUE" )
1284 : ( parts.size() > 1
1285 ? QStringLiteral(
"(%1)" ).arg( parts.join( QLatin1String(
") AND (" ) ) )
1307 QDomElement symbolsElem = element.firstChildElement( QStringLiteral(
"symbols" ) );
1308 if ( symbolsElem.isNull() )
1313 QDomElement rulesElem = element.firstChildElement( QStringLiteral(
"rules" ) );
1330 Rule *root =
nullptr;
1332 QDomElement ruleElem = element.firstChildElement( QStringLiteral(
"Rule" ) );
1333 while ( !ruleElem.isNull() )
1340 root =
new Rule(
nullptr );
1345 ruleElem = ruleElem.nextSiblingElement( QStringLiteral(
"Rule" ) );
1373 const auto constCategories = r->
categories();
1380 else if ( cat.value().userType() == QMetaType::Type::Int )
1381 value = cat.value().toString();
1382 else if ( cat.value().userType() == QMetaType::Type::Double )
1385 value = QString::number( cat.value().toDouble(),
'f', 4 );
1388 const QString
filter = QStringLiteral(
"%1 %2 %3" ).arg( attr,
QgsVariantUtils::isNull( cat.value() ) ? QStringLiteral(
"IS" ) : QStringLiteral(
"=" ), value );
1389 const QString label = !cat.label().isEmpty() ? cat.label() :
1390 cat.value().isValid() ? value : QString();
1406 else if ( !testExpr.
isField() )
1409 attr = QStringLiteral(
"(%1)" ).arg( attr );
1412 bool firstRange =
true;
1413 const auto constRanges = r->
ranges();
1418 QString
filter = QStringLiteral(
"%1 %2 %3 AND %1 <= %4" ).arg( attr, firstRange ? QStringLiteral(
">=" ) : QStringLiteral(
">" ),
1419 QString::number( rng.lowerValue(),
'f', 4 ),
1420 QString::number( rng.upperValue(),
'f', 4 ) );
1422 QString label = rng.label().isEmpty() ?
filter : rng.label();
1429 std::sort( scales.begin(), scales.end() );
1433 const auto constScales = scales;
1434 for (
int scale : constScales )
1438 if ( maxDenom != 0 && maxDenom <= scale )
1440 initialRule->
appendChild(
new Rule( symbol->
clone(), oldScale, scale, QString(), QStringLiteral(
"%1 - %2" ).arg( oldScale ).arg( scale ) ) );
1444 initialRule->
appendChild(
new Rule( symbol->
clone(), oldScale, maxDenom, QString(), QStringLiteral(
"%1 - %2" ).arg( oldScale ).arg( maxDenom ) ) );
1449 QString msg( QStringLiteral(
"Rule-based renderer:\n" ) );
1456 return mRootRule->willRenderFeature( feature, &context );
1461 return mRootRule->symbolsForFeature( feature, &context );
1466 return mRootRule->symbolsForFeature( feature, &context );
1471 return mRootRule->legendKeysForFeature( feature, &context );
1481 std::unique_ptr< QgsRuleBasedRenderer > r;
1482 if ( renderer->
type() == QLatin1String(
"RuleRenderer" ) )
1486 else if ( renderer->
type() == QLatin1String(
"singleSymbol" ) )
1489 if ( !singleSymbolRenderer )
1492 std::unique_ptr< QgsSymbol > origSymbol( singleSymbolRenderer->
symbol()->
clone() );
1493 r = std::make_unique< QgsRuleBasedRenderer >( origSymbol.release() );
1495 else if ( renderer->
type() == QLatin1String(
"categorizedSymbol" ) )
1498 if ( !categorizedRenderer )
1503 bool isField =
false;
1513 if ( isField && !attr.contains(
'\"' ) )
1519 auto rootrule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1526 auto rule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1528 rule->setLabel( category.
label() );
1531 if ( category.
value().userType() == QMetaType::Type::QVariantList )
1534 const QVariantList list = category.
value().toList();
1535 for (
const QVariant &v : list )
1538 if ( QVariant( v ).convert( QMetaType::Type::Double ) )
1540 values << v.toString();
1548 if ( values.empty() )
1550 expression = QStringLiteral(
"ELSE" );
1554 expression = QStringLiteral(
"%1 IN (%2)" ).arg( attr, values.join(
',' ) );
1560 if ( category.
value().convert( QMetaType::Type::Double ) )
1562 value = category.
value().toString();
1570 if ( value == QLatin1String(
"''" ) )
1572 expression = QStringLiteral(
"ELSE" );
1576 expression = QStringLiteral(
"%1 = %2" ).arg( attr, value );
1579 rule->setFilterExpression( expression );
1585 std::unique_ptr< QgsSymbol > origSymbol( category.
symbol()->
clone() );
1586 rule->setSymbol( origSymbol.release() );
1588 rootrule->appendChild( rule.release() );
1591 r = std::make_unique< QgsRuleBasedRenderer >( rootrule.release() );
1593 else if ( renderer->
type() == QLatin1String(
"graduatedSymbol" ) )
1596 if ( !graduatedRenderer )
1602 bool isField =
false;
1612 if ( isField && !attr.contains(
'\"' ) )
1617 else if ( !isField )
1620 attr = QStringLiteral(
"(%1)" ).arg( attr );
1623 auto rootrule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1627 const bool isInverted = ranges.size() > 1 ?
1628 ranges.at( 0 ).upperValue() > ranges.at( 1 ).upperValue() :
1631 for (
int i = 0; i < ranges.size(); ++i )
1633 range = ranges.value( i );
1634 auto rule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1636 rule->setLabel( range.
label() );
1637 const QString upperValue = QString::number( range.
upperValue(),
'f', 16 );
1638 const QString lowerValue = QString::number( range.
lowerValue(),
'f', 16 );
1642 expression = !isInverted ?
1643 QStringLiteral(
"%1 <= %2" ).arg( attr, upperValue ) :
1644 QStringLiteral(
"%1 > %2" ).arg( attr, lowerValue );
1646 else if ( i == ranges.size() - 1 )
1648 expression = !isInverted ?
1649 QStringLiteral(
"%1 > %2" ).arg( attr, lowerValue ) :
1650 QStringLiteral(
"%1 <= %2" ).arg( attr, upperValue );
1654 expression = attr +
" > " + lowerValue +
" AND " + \
1655 attr +
" <= " + upperValue;
1657 rule->setFilterExpression( expression );
1663 std::unique_ptr< QgsSymbol > symbol( range.
symbol()->
clone() );
1664 rule->setSymbol( symbol.release() );
1666 rootrule->appendChild( rule.release() );
1669 r = std::make_unique< QgsRuleBasedRenderer >( rootrule.release() );
1671 else if ( renderer->
type() == QLatin1String(
"pointDisplacement" ) || renderer->
type() == QLatin1String(
"pointCluster" ) )
1676 else if ( renderer->
type() == QLatin1String(
"invertedPolygonRenderer" ) )
1681 else if ( renderer->
type() == QLatin1String(
"mergedFeatureRenderer" ) )
1686 else if ( renderer->
type() == QLatin1String(
"embeddedSymbol" ) && layer )
1690 auto rootrule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1697 while ( it.
nextFeature( feature ) && rootrule->children().size() < 500 )
1701 auto rule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1702 rule->setFilterExpression( QStringLiteral(
"$id=%1" ).arg( feature.
id() ) );
1703 rule->setLabel( QString::number( feature.
id() ) );
1705 rootrule->appendChild( rule.release() );
1709 auto rule = std::make_unique< QgsRuleBasedRenderer::Rule >(
nullptr );
1710 rule->setFilterExpression( QStringLiteral(
"ELSE" ) );
1711 rule->setLabel( QObject::tr(
"All other features" ) );
1713 rootrule->appendChild( rule.release() );
1715 r = std::make_unique< QgsRuleBasedRenderer >( rootrule.release() );
1728 QString sizeExpression;
1729 switch ( symbol->
type() )
1735 if ( ! sizeScaleField.isEmpty() )
1737 sizeExpression = QStringLiteral(
"%1*(%2)" ).arg( msl->
size() ).arg( sizeScaleField );
1740 if ( ! rotationField.isEmpty() )
1747 if ( ! sizeScaleField.isEmpty() )
1754 sizeExpression = QStringLiteral(
"%1*(%2)" ).arg( lsl->
width() ).arg( sizeScaleField );
1763 sizeExpression = QStringLiteral(
"%1*(%2)" ).arg( msl->
size() ).arg( sizeScaleField );
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ EmbeddedSymbols
Retrieve any embedded feature symbology.
QFlags< FeatureRendererFlag > FeatureRendererFlags
Flags controlling behavior of vector feature renderers.
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
@ AffectsLabeling
If present, indicates that the symbol will participate in the map labeling problem.
A feature renderer which represents features using a list of renderer categories.
const QgsCategoryList & categories() const
Returns a list of all categories recognized by the renderer.
QString classAttribute() const
Returns the class attribute for the renderer, which is the field name or expression string from the l...
A vector feature renderer which uses embedded feature symbology to render per-feature symbols.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
static QString quotedString(QString text)
Returns a quoted version of a string (in single quotes).
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
bool isField() const
Checks whether an expression consists only of a single field reference.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes).
static int expressionToLayerFieldIndex(const QString &expression, const QgsVectorLayer *layer)
Attempts to resolve an expression to a field index from the given layer.
static bool attemptReduceToInClause(const QStringList &expressions, QString &result)
Attempts to reduce a list of expressions to a single "field IN (val1, val2, ... )" type expression.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
QgsFeatureRenderer(const QString &type)
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
void copyRendererData(QgsFeatureRenderer *destRenderer) const
Clones generic renderer data to another renderer.
void saveRendererData(QDomDocument &doc, QDomElement &element, const QgsReadWriteContext &context)
Saves generic renderer data into the specified element.
void renderFeatureWithSymbol(const QgsFeature &feature, QgsSymbol *symbol, QgsRenderContext &context, int layer, bool selected, bool drawVertexMarker)
Render the feature with the symbol using context.
virtual const QgsFeatureRenderer * embeddedRenderer() const
Returns the current embedded renderer (subrenderer) for this feature renderer.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
const QgsSymbol * embeddedSymbol() const
Returns the feature's embedded symbology, or nullptr if the feature has no embedded symbol.
Container of fields for a vector layer.
A fill symbol type, for rendering Polygon and MultiPolygon geometries.
A vector feature renderer which uses numeric attributes to classify features into different ranges.
QString classAttribute() const
Returns the attribute name (or expression) used for the classification.
const QgsRangeList & ranges() const
Returns a list of all ranges used in the classification.
A polygon-only feature renderer used to display features inverted.
Stores information about one class/rule of a vector layer renderer in a unified way that can be used ...
Abstract base class for line symbol layers.
virtual double width() const
Returns the estimated width for the line symbol layer.
A line symbol type, for rendering LineString and MultiLineString geometries.
Abstract base class for marker symbol layers.
double size() const
Returns the symbol size.
A marker symbol type, for rendering Point and MultiPoint geometries.
A polygon or line-only feature renderer used to render a set of features merged (or dissolved) into a...
static QgsExpression * expressionFromOgcFilter(const QDomElement &element, QgsVectorLayer *layer=nullptr)
Parse XML with OGC filter into QGIS expression.
An abstract base class for distance based point renderers (e.g., clusterer and displacement renderers...
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
A container for the context for various read/write operations on objects.
Contains information about the context of a rendering operation.
double rendererScale() const
Returns the renderer map scale.
QgsExpressionContext & expressionContext()
Gets the expression context.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
Represents an individual category (class) from a QgsCategorizedSymbolRenderer.
QgsSymbol * symbol() const
Returns the symbol which will be used to render this category.
QVariant value() const
Returns the value corresponding to this category.
QString label() const
Returns the label for this category, which is used to represent the category within legends and the l...
Represents a value range for a QgsGraduatedSymbolRenderer.
QString label() const
Returns the label used for the range.
QgsSymbol * symbol() const
Returns the symbol used for the range.
double upperValue() const
Returns the upper bound of the range.
double lowerValue() const
Returns the lower bound of the range.
Represents an individual rule for a rule-based renderer.
bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all child rules associated with the rule...
QgsRuleBasedRenderer::RuleList descendants() const
Returns all children, grand-children, grand-grand-children, grand-gra... you get it.
void setSymbol(QgsSymbol *sym)
Sets a new symbol (or nullptr). Deletes old symbol.
void removeChild(QgsRuleBasedRenderer::Rule *rule)
delete child rule
QgsRuleBasedRenderer::Rule * findRuleByKey(const QString &key)
Try to find a rule given its unique key.
void insertChild(int i, QgsRuleBasedRenderer::Rule *rule)
add child rule, take ownership, sets this as parent
QString ruleKey() const
Unique rule identifier (for identification of rule within renderer).
bool needsGeometry() const
Returns true if this rule or one of its children needs the geometry to be applied.
QgsRuleBasedRenderer::Rule * takeChild(QgsRuleBasedRenderer::Rule *rule)
take child rule out, set parent as nullptr
const QgsRuleBasedRenderer::RuleList & children() const
Returns all children rules of this rule.
RenderResult
The result of rendering a rule.
@ Inactive
The rule is inactive.
@ Filtered
The rule does not apply.
@ Rendered
Something was rendered.
QgsRuleBasedRenderer::RuleList rulesForFeature(const QgsFeature &feature, QgsRenderContext *context=nullptr, bool onlyActive=true)
Returns the list of rules used to render the feature in a specific context.
double maximumScale() const
Returns the maximum map scale (i.e.
QgsRuleBasedRenderer::Rule * parent()
The parent rule.
void setIsElse(bool iselse)
Sets if this rule is an ELSE rule.
QgsSymbolList symbolsForFeature(const QgsFeature &feature, QgsRenderContext *context=nullptr)
tell which symbols will be used to render the feature
bool isElse() const
Check if this rule is an ELSE rule.
QSet< QString > legendKeysForFeature(const QgsFeature &feature, QgsRenderContext *context=nullptr)
Returns which legend keys match the feature.
QgsRuleBasedRenderer::Rule * clone() const
clone this rule, return new instance
bool willRenderFeature(const QgsFeature &feature, QgsRenderContext *context=nullptr)
only tell whether a feature will be rendered without actually rendering it
void removeChildAt(int i)
delete child rule
void setActive(bool state)
Sets if this rule is active.
Rule(QgsSymbol *symbol, int maximumScale=0, int minimumScale=0, const QString &filterExp=QString(), const QString &label=QString(), const QString &description=QString(), bool elseRule=false)
Constructor takes ownership of the symbol.
bool isFilterOK(const QgsFeature &f, QgsRenderContext *context=nullptr) const
Check if a given feature shall be rendered by this rule.
QgsSymbolList symbols(const QgsRenderContext &context=QgsRenderContext()) const
Returns a list of the symbols used by this rule and all children of this rule.
bool isScaleOK(double scale) const
Check if this rule applies for a given scale.
static QgsRuleBasedRenderer::Rule * createFromSld(QDomElement &element, Qgis::GeometryType geomType)
Create a rule from the SLD provided in element and for the specified geometry type.
QgsExpression * filter() const
A filter that will check if this rule applies.
void setNormZLevels(const QMap< int, int > &zLevelsToNormLevels)
assign normalized z-levels [0..N-1] for this rule's symbol for quick access during rendering
QDomElement save(QDomDocument &doc, QgsSymbolMap &symbolMap) const
void appendChild(QgsRuleBasedRenderer::Rule *rule)
add child rule, take ownership, sets this as parent
QgsRuleBasedRenderer::Rule * takeChildAt(int i)
take child rule out, set parent as nullptr
QSet< int > collectZLevels()
Gets all used z-levels from this rule and children.
double minimumScale() const
Returns the minimum map scale (i.e.
QString description() const
A human readable description for this rule.
void stopRender(QgsRenderContext &context)
Stop a rendering process.
bool hasActiveChildren() const
Returns true if the rule has any active children.
QgsRuleBasedRenderer::Rule::RenderResult renderFeature(QgsRuleBasedRenderer::FeatureToRender &featToRender, QgsRenderContext &context, QgsRuleBasedRenderer::RenderQueue &renderQueue)
Render a given feature, will recursively call subclasses and only render if the constraints apply.
QgsLegendSymbolList legendSymbolItems(int currentLevel=-1) const
QSet< QString > usedAttributes(const QgsRenderContext &context) const
Returns the attributes used to evaluate the expression of this rule.
void setFilterExpression(const QString &filterExp)
Set the expression used to check if a given feature shall be rendered with this rule.
QString dump(int indent=0) const
Dump for debug purpose.
void setRuleKey(const QString &key)
Override the assigned rule key (should be used just internally by rule-based renderer).
bool startRender(QgsRenderContext &context, const QgsFields &fields, QString &filter)
prepare the rule for rendering and its children (build active children array)
static QgsRuleBasedRenderer::Rule * create(QDomElement &ruleElem, QgsSymbolMap &symbolMap, bool reuseId=true)
Create a rule from an XML definition.
QString filterExpression() const
A filter that will check if this rule applies.
bool active() const
Returns if this rule is active.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, QVariantMap props) const
Saves the symbol layer as SLD.
static void refineRuleCategories(QgsRuleBasedRenderer::Rule *initialRule, QgsCategorizedSymbolRenderer *r)
take a rule and create a list of new rules based on the categories from categorized symbol renderer
static void convertToDataDefinedSymbology(QgsSymbol *symbol, const QString &sizeScaleField, const QString &rotationField=QString())
helper function to convert the size scale and rotation fields present in some other renderers to data...
bool legendSymbolItemChecked(const QString &key) override
Returns true if the legend symbology item with the specified key is checked.
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) override
Stores renderer properties to an XML element.
void setLegendSymbolItem(const QString &key, QgsSymbol *symbol) override
Sets the symbol to be used for a legend symbol item.
bool canSkipRender() override
Returns true if the renderer can be entirely skipped, i.e.
void checkLegendSymbolItem(const QString &key, bool state=true) override
Sets whether the legend symbology item with the specified ley should be checked.
QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns symbol for current feature. Should not be used individually: there could be more symbols for ...
QList< QgsRuleBasedRenderer::RenderLevel > RenderQueue
Rendering queue: a list of rendering levels.
QSet< QString > legendKeysForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns legend keys matching a specified feature.
static void refineRuleRanges(QgsRuleBasedRenderer::Rule *initialRule, QgsGraduatedSymbolRenderer *r)
take a rule and create a list of new rules based on the ranges from graduated symbol renderer
QgsSymbolList symbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns list of symbols used for rendering the feature.
QString dump() const override
Returns debug information about this renderer.
QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
static QgsRuleBasedRenderer * convertFromRenderer(const QgsFeatureRenderer *renderer, QgsVectorLayer *layer=nullptr)
Creates a new QgsRuleBasedRenderer from an existing renderer.
bool legendSymbolItemsCheckable() const override
Returns true if symbology items in legend are checkable.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns a list of attributes required by this renderer.
QString filter(const QgsFields &fields=QgsFields()) override
If a renderer does not require all the features this method may be overridden and return an expressio...
bool willRenderFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns whether the renderer will render a feature or not.
static void refineRuleScales(QgsRuleBasedRenderer::Rule *initialRule, QList< int > scales)
take a rule and create a list of new rules with intervals of scales given by the passed scale denomin...
QList< QgsRuleBasedRenderer::Rule * > RuleList
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
Rule * mRootRule
the root node with hierarchical list of rules
~QgsRuleBasedRenderer() override
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
bool filterNeedsGeometry() const override
Returns true if this renderer requires the geometry to apply the filter.
Qgis::FeatureRendererFlags flags() const override
Returns flags associated with the renderer.
QgsRuleBasedRenderer * clone() const override
Create a deep copy of this renderer.
static QgsFeatureRenderer * create(QDomElement &element, const QgsReadWriteContext &context)
Creates a new rule-based renderer instance from XML.
QgsLegendSymbolList legendSymbolItems() const override
Returns a list of symbology items for the legend.
static QgsFeatureRenderer * createFromSld(QDomElement &element, Qgis::GeometryType geomType)
Creates a new rule based renderer from an SLD XML element.
QList< FeatureToRender > mCurrentFeatures
QString legendKeyToExpression(const QString &key, QgsVectorLayer *layer, bool &ok) const override
Attempts to convert the specified legend rule key to a QGIS expression matching the features displaye...
bool renderFeature(const QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false) override
Render a feature using this renderer in the given context.
QgsRuleBasedRenderer(QgsRuleBasedRenderer::Rule *root)
Constructs the renderer from given tree of rules (takes ownership).
QgsSymbolList symbols(QgsRenderContext &context) const override
Returns list of symbols used by the renderer.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props=QVariantMap()) const override
Used from subclasses to create SLD Rule elements following SLD v1.1 specs.
static bool equalToOrGreaterThanMinimumScale(const double scale, const double minScale)
Returns whether the scale is equal to or greater than the minScale, taking non-round numbers into acc...
static bool lessThanMaximumScale(const double scale, const double maxScale)
Returns whether the scale is less than the maxScale, taking non-round numbers into account.
A feature renderer which renders all features with the same symbol.
QgsSymbol * symbol() const
Returns the symbol which will be rendered for every feature.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
An interface for classes which can visit style entity (e.g.
@ SymbolRule
Rule based symbology or label child rule.
virtual bool visitExit(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor stops visiting a node.
virtual bool visitEnter(const QgsStyleEntityVisitorInterface::Node &node)
Called when the visitor starts visiting a node.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
A symbol entity for QgsStyle databases.
static void applyScaleDependency(QDomDocument &doc, QDomElement &ruleElem, QVariantMap &props)
Checks if the properties contain scaleMinDenom and scaleMaxDenom, if available, they are added into t...
static Q_DECL_DEPRECATED bool createFunctionElement(QDomDocument &doc, QDomElement &element, const QString &function)
Creates an OGC function element.
static bool hasSldSymbolizer(const QDomElement &element)
Returns true if a DOM element contains an SLD Symbolizer element.
static bool createSymbolLayerListFromSld(QDomElement &element, Qgis::GeometryType geomType, QList< QgsSymbolLayer * > &layers)
Creates a symbol layer list from a DOM element.
static void mergeScaleDependencies(double mScaleMinDenom, double mScaleMaxDenom, QVariantMap &props)
Merges the local scale limits, if any, with the ones already in the map, if any.
static void clearSymbolMap(QgsSymbolMap &symbols)
static QgsSymbolMap loadSymbols(QDomElement &element, const QgsReadWriteContext &context)
Reads a collection of symbols from XML and returns them in a map. Caller is responsible for deleting ...
static QDomElement saveSymbols(QgsSymbolMap &symbols, const QString &tagName, QDomDocument &doc, const QgsReadWriteContext &context)
Writes a collection of symbols to XML with specified tagName for the top-level element.
@ StrokeWidth
Stroke width.
virtual QString layerType() const =0
Returns a string that represents this layer type.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
virtual void setDataDefinedProperty(Property key, const QgsProperty &property)
Sets a data defined property for the layer.
virtual QgsSymbol * subSymbol()
Returns the symbol's sub symbol, if present.
Abstract base class for all rendered symbols.
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
virtual QgsSymbol * clone() const =0
Returns a deep copy of this symbol.
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Qgis::SymbolType type() const
Returns the symbol's type.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
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
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
QList< QgsLegendSymbolItem > QgsLegendSymbolList
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
#define RENDERER_TAG_NAME
QMap< QString, QgsSymbol * > QgsSymbolMap
QList< QgsSymbol * > QgsSymbolList
QList< QgsRendererRange > QgsRangeList
QList< QgsSymbolLayer * > QgsSymbolLayerList
Feature for rendering by a QgsRuleBasedRenderer.
A QgsRuleBasedRenderer rendering job, consisting of a feature to be rendered with a particular symbol...
Render level: a list of jobs to be drawn at particular level for a QgsRuleBasedRenderer.
Contains information relating to a node (i.e.
Contains information relating to the style entity currently being visited.