27#include "moc_qgsvectorlayertemporalproperties.cpp"
42 return range.
isInfinite() || mFixedRange.isInfinite() || mFixedRange.overlaps( range );
56 QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer );
68 if ( fieldIndex >= 0 )
74 const QDateTime min = minVal.toDateTime();
75 const QDateTime maxStartTime = maxVal.toDateTime();
85 const int durationFieldIndex = vectorLayer->
fields().
lookupField( mDurationFieldName );
86 if ( fieldIndex >= 0 && durationFieldIndex >= 0 )
88 const QDateTime minTime = vectorLayer->
minimumValue( fieldIndex ).toDateTime();
96 const QDateTime start = f.
attribute( fieldIndex ).toDateTime();
97 if ( start.isValid() )
99 const QVariant durationValue = f.
attribute( durationFieldIndex );
100 if ( durationValue.isValid() )
102 const double duration = durationValue.toDouble();
103 const QDateTime end = start.addMSecs(
QgsInterval( duration, mDurationUnit ).seconds() * 1000.0 );
105 maxTime = maxTime.isValid() ? std::max( maxTime, end ) : end;
116 const int startFieldIndex = vectorLayer->
fields().
lookupField( mStartFieldName );
118 if ( startFieldIndex >= 0 && endFieldIndex >= 0 )
120 QVariant startMinVal;
121 QVariant startMaxVal;
128 endMinVal.toDateTime() ),
129 std::max( startMaxVal.toDateTime(),
130 endMaxVal.toDateTime() ) );
132 else if ( startFieldIndex >= 0 )
134 QVariant startMinVal;
135 QVariant startMaxVal;
138 startMaxVal.toDateTime() );
140 else if ( endFieldIndex >= 0 )
146 endMaxVal.toDateTime() );
153 const bool hasStartExpression = !mStartExpression.isEmpty();
154 const bool hasEndExpression = !mEndExpression.isEmpty();
155 if ( !hasStartExpression && !hasEndExpression )
166 if ( hasStartExpression )
173 if ( hasEndExpression )
179 QSet< QString > fields;
180 if ( hasStartExpression )
182 if ( hasEndExpression )
198 const QDateTime start = hasStartExpression ?
startExpression.evaluate( &context ).toDateTime() : QDateTime();
199 const QDateTime end = hasEndExpression ?
endExpression.evaluate( &context ).toDateTime() : QDateTime();
201 if ( start.isValid() )
203 minTime = minTime.isValid() ? std::min( minTime, start ) : start;
204 if ( !hasEndExpression )
205 maxTime = maxTime.isValid() ? std::max( maxTime, start ) : start;
209 maxTime = maxTime.isValid() ? std::max( maxTime, end ) : end;
210 if ( !hasStartExpression )
211 minTime = minTime.isValid() ? std::min( minTime, end ) : end;
267 const QDomElement temporalNode = element.firstChildElement( QStringLiteral(
"temporal" ) );
269 setIsActive( temporalNode.attribute( QStringLiteral(
"enabled" ), QStringLiteral(
"0" ) ).toInt() );
271 mMode =
static_cast< Qgis::VectorTemporalMode >( temporalNode.attribute( QStringLiteral(
"mode" ), QStringLiteral(
"0" ) ). toInt() );
273 mLimitMode =
static_cast< Qgis::VectorTemporalLimitMode >( temporalNode.attribute( QStringLiteral(
"limitMode" ), QStringLiteral(
"0" ) ). toInt() );
274 mStartFieldName = temporalNode.attribute( QStringLiteral(
"startField" ) );
275 mEndFieldName = temporalNode.attribute( QStringLiteral(
"endField" ) );
276 mStartExpression = temporalNode.attribute( QStringLiteral(
"startExpression" ) );
277 mEndExpression = temporalNode.attribute( QStringLiteral(
"endExpression" ) );
278 mDurationFieldName = temporalNode.attribute( QStringLiteral(
"durationField" ) );
280 mFixedDuration = temporalNode.attribute( QStringLiteral(
"fixedDuration" ) ).toDouble();
281 mAccumulateFeatures = temporalNode.attribute( QStringLiteral(
"accumulate" ), QStringLiteral(
"0" ) ).toInt();
283 const QDomNode rangeElement = temporalNode.namedItem( QStringLiteral(
"fixedRange" ) );
285 const QDomNode begin = rangeElement.namedItem( QStringLiteral(
"start" ) );
286 const QDomNode end = rangeElement.namedItem( QStringLiteral(
"end" ) );
288 const QDateTime beginDate = QDateTime::fromString( begin.toElement().text(), Qt::ISODate );
289 const QDateTime endDate = QDateTime::fromString( end.toElement().text(), Qt::ISODate );
300 if ( element.isNull() )
301 return QDomElement();
303 QDomElement temporalElement = document.createElement( QStringLiteral(
"temporal" ) );
304 temporalElement.setAttribute( QStringLiteral(
"enabled" ),
isActive() ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
305 temporalElement.setAttribute( QStringLiteral(
"mode" ), QString::number(
static_cast< int >( mMode ) ) );
307 temporalElement.setAttribute( QStringLiteral(
"limitMode" ), QString::number(
static_cast< int >( mLimitMode ) ) );
308 temporalElement.setAttribute( QStringLiteral(
"startField" ), mStartFieldName );
309 temporalElement.setAttribute( QStringLiteral(
"endField" ), mEndFieldName );
310 temporalElement.setAttribute( QStringLiteral(
"startExpression" ), mStartExpression );
311 temporalElement.setAttribute( QStringLiteral(
"endExpression" ), mEndExpression );
312 temporalElement.setAttribute( QStringLiteral(
"durationField" ), mDurationFieldName );
314 temporalElement.setAttribute( QStringLiteral(
"fixedDuration" ),
qgsDoubleToString( mFixedDuration ) );
315 temporalElement.setAttribute( QStringLiteral(
"accumulate" ), mAccumulateFeatures ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
317 QDomElement rangeElement = document.createElement( QStringLiteral(
"fixedRange" ) );
319 QDomElement startElement = document.createElement( QStringLiteral(
"start" ) );
320 QDomElement endElement = document.createElement( QStringLiteral(
"end" ) );
322 const QDomText startText = document.createTextNode( mFixedRange.begin().toTimeSpec( Qt::OffsetFromUTC ).toString( Qt::ISODate ) );
323 const QDomText endText = document.createTextNode( mFixedRange.end().toTimeSpec( Qt::OffsetFromUTC ).toString( Qt::ISODate ) );
324 startElement.appendChild( startText );
325 endElement.appendChild( endText );
326 rangeElement.appendChild( startElement );
327 rangeElement.appendChild( endElement );
329 temporalElement.appendChild( rangeElement );
331 element.appendChild( temporalElement );
340 setIsActive( vectorCaps->hasTemporalCapabilities() );
344 switch ( vectorCaps->mode() )
361 return mStartExpression;
371 return mEndExpression;
381 return mAccumulateFeatures;
391 return mFixedDuration;
401 return mStartFieldName;
406 mStartFieldName = startFieldName;
411 return mEndFieldName;
416 mEndFieldName = field;
421 return mDurationFieldName;
426 mDurationFieldName = field;
431 return mDurationUnit;
436 mDurationUnit = units;
441 return QStringLiteral(
"make_datetime(%1,%2,%3,%4,%5,%6)" ).arg( datetime.date().year() )
442 .arg( datetime.date().month() )
443 .arg( datetime.date().day() )
444 .arg( datetime.time().hour() )
445 .arg( datetime.time().minute() )
446 .arg( datetime.time().second() + datetime.time().msec() / 1000.0 );
454 auto dateTimefieldCast = [ &context ](
const QString & fieldName ) -> QString
473 if ( mAccumulateFeatures )
475 return QStringLiteral(
"(%1 %2 %3) OR %1 IS NULL" ).arg( dateTimefieldCast( mStartFieldName ),
476 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
481 return QStringLiteral(
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL" ).arg( dateTimefieldCast( mStartFieldName ),
482 filterRange.
includeBeginning() ? QStringLiteral(
">=" ) : QStringLiteral(
">" ),
484 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
490 return QStringLiteral(
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL" ).arg( dateTimefieldCast( mStartFieldName ),
493 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
500 QString intervalExpression;
501 switch ( mDurationUnit )
547 return QStringLiteral(
"(%1 %2 %3 OR %1 IS NULL) AND ((%1 + %4 %5 %6) OR %7 IS NULL)" ).arg( dateTimefieldCast( mStartFieldName ),
548 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
558 if ( !mStartFieldName.isEmpty() && !mEndFieldName.isEmpty() )
560 return QStringLiteral(
"(%1 %2 %3 OR %1 IS NULL) AND (%4 %5 %6 OR %4 IS NULL)" ).arg( dateTimefieldCast( mStartFieldName ),
561 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
563 dateTimefieldCast( mEndFieldName ),
568 else if ( !mStartFieldName.isEmpty() )
570 return QStringLiteral(
"%1 %2 %3 OR %1 IS NULL" ).arg( dateTimefieldCast( mStartFieldName ),
571 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
574 else if ( !mEndFieldName.isEmpty() )
576 return QStringLiteral(
"%1 %2 %3 OR %1 IS NULL" ).arg( dateTimefieldCast( mEndFieldName ),
585 if ( !mStartExpression.isEmpty() && !mEndExpression.isEmpty() )
587 return QStringLiteral(
"((%1) %2 %3) AND ((%4) %5 %6)" ).arg( mStartExpression,
588 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
594 else if ( !mStartExpression.isEmpty() )
596 return QStringLiteral(
"(%1) %2 %3" ).arg( mStartExpression,
597 filterRange.
includeEnd() ? QStringLiteral(
"<=" ) : QStringLiteral(
"<" ),
600 else if ( !mEndExpression.isEmpty() )
602 return QStringLiteral(
"(%1) %2 %3" ).arg( mEndExpression,
622 static const QStringList sStartCandidates{ QStringLiteral(
"start" ),
623 QStringLiteral(
"begin" ),
624 QStringLiteral(
"from" ),
625 QStringLiteral(
"since" ),
627 QStringLiteral(
"anfang" ),
628 QStringLiteral(
"von" ),
629 QStringLiteral(
"ab" ),
630 QStringLiteral(
"seit" ) };
632 static const QStringList sEndCandidates{ QStringLiteral(
"end" ),
633 QStringLiteral(
"last" ),
634 QStringLiteral(
"to" ),
635 QStringLiteral(
"stop" ),
637 QStringLiteral(
"ende" ),
638 QStringLiteral(
"bis" ) };
641 static const QStringList sSingleFieldCandidates{ QStringLiteral(
"event" ) };
644 bool foundStart =
false;
645 bool foundEnd =
false;
647 for (
const QgsField &field : fields )
649 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
654 for (
const QString &candidate : sStartCandidates )
656 const QString fldName = field.name();
657 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
659 mStartFieldName = fldName;
667 for (
const QString &candidate : sEndCandidates )
669 const QString fldName = field.name();
670 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
672 mEndFieldName = fldName;
678 if ( foundStart && foundEnd )
685 for (
const QgsField &field : fields )
687 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
690 for (
const QString &candidate : sSingleFieldCandidates )
692 const QString fldName = field.name();
693 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
695 mStartFieldName = fldName;
705 if ( foundStart && foundEnd )
707 else if ( foundStart )
VectorTemporalMode
Vector layer temporal feature modes.
@ FeatureDateTimeStartAndDurationFromFields
Mode when features have a field for start time and a field for event duration.
@ RedrawLayerOnly
Redraw the layer when temporal range changes, but don't apply any filtering. Useful when symbology or...
@ FeatureDateTimeStartAndEndFromExpressions
Mode when features use expressions for start and end times.
@ FeatureDateTimeInstantFromField
Mode when features have a datetime instant taken from a single field.
@ FixedTemporalRange
Mode when temporal properties have fixed start and end datetimes.
@ FeatureDateTimeStartAndEndFromFields
Mode when features have separate fields for start and end times.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
TemporalUnit
Temporal units.
@ IrregularStep
Special 'irregular step' time unit, used for temporal data which uses irregular, non-real-world unit ...
@ Milliseconds
Milliseconds.
@ Unknown
Unknown time unit.
@ StoresFeatureDateTimeInstantInField
Dataset has feature datetime instants stored in a single field.
@ StoresFeatureDateTimeStartAndEndInSeparateFields
Dataset stores feature start and end datetimes in separate fields.
@ HasFixedTemporalRange
Entire dataset from provider has a fixed start and end datetime.
VectorTemporalLimitMode
Mode for the handling of the limits of the filtering timeframe for vector features.
@ IncludeBeginIncludeEnd
Mode to include both limits of the filtering timeframe.
Base class for handling properties relating to a data provider's temporal capabilities.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes).
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.
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 & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A representation of the interval between two datetime values.
QgsMapLayerTemporalProperties(QObject *parent, bool enabled=false)
Constructor for QgsMapLayerTemporalProperties, with the specified parent object.
Base class for all map layer types.
A container for the context for various read/write operations on objects.
bool isActive() const
Returns true if the temporal property is active.
void setIsActive(bool active)
Sets whether the temporal property is active.
@ FlagDontInvalidateCachedRendersWhenRangeChanges
Any cached rendering will not be invalidated when temporal range context is modified.
T begin() const
Returns the beginning of the range.
T end() const
Returns the upper bound of the range.
bool includeEnd() const
Returns true if the end is inclusive, or false if the end is exclusive.
bool includeBeginning() const
Returns true if the beginning is inclusive, or false if the beginning is exclusive.
bool isInfinite() const
Returns true if the range consists of all possible values.
static Q_INVOKABLE Qgis::TemporalUnit decodeTemporalUnit(const QString &string, bool *ok=nullptr)
Decodes a temporal unit from a string.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
Implementation of data provider temporal properties for QgsVectorDataProviders.
Encapsulates the context in which a QgsVectorLayer's temporal capabilities will be applied.
QgsVectorLayer * layer() const
Returns the associated layer.
void setLayer(QgsVectorLayer *layer)
Sets the associated layer.
void guessDefaultsFromFields(const QgsFields &fields)
Attempts to setup the temporal properties by scanning a set of fields and looking for standard naming...
QString endExpression() const
Returns the expression for the end time for the feature's time spans.
void setDurationField(const QString &field)
Sets the name of the duration field, which contains the duration of the event.
void setMode(Qgis::VectorTemporalMode mode)
Sets the temporal properties mode.
QgsVectorLayerTemporalProperties(QObject *parent=nullptr, bool enabled=false)
Constructor for QgsVectorLayerTemporalProperties, with the specified parent object.
void setStartExpression(const QString &expression)
Sets the expression to use for the start time for the feature's time spans.
bool isVisibleInTemporalRange(const QgsDateTimeRange &range) const override
Returns true if the layer should be visible and rendered for the specified time range.
Qgis::VectorTemporalLimitMode limitMode() const
Returns the temporal limit mode (to include or exclude begin/end limits).
void setLimitMode(Qgis::VectorTemporalLimitMode mode)
Sets the temporal limit mode (to include or exclude begin/end limits).
const QgsDateTimeRange & fixedTemporalRange() const
Returns the fixed temporal range for the layer.
double fixedDuration() const
Returns the fixed duration length, which contains the duration of the event.
bool accumulateFeatures() const
Returns true if features will be accumulated over time (i.e.
QgsTemporalProperty::Flags flags() const override
Returns flags associated to the temporal property.
void setFixedTemporalRange(const QgsDateTimeRange &range)
Sets a temporal range to apply to the whole layer.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context) override
Reads temporal properties from a DOM element previously written by writeXml().
void setEndExpression(const QString &endExpression)
Sets the expression to use for the end time for the feature's time spans.
QString durationField() const
Returns the name of the duration field, which contains the duration of the event.
void setDurationUnits(Qgis::TemporalUnit units)
Sets the units of the event's duration.
QString endField() const
Returns the name of the end datetime field, which contains the end time for the feature's time spans.
QString createFilterString(const QgsVectorLayerTemporalContext &context, const QgsDateTimeRange &range) const
Creates a QGIS expression filter string for filtering features within the specified context to those ...
QDomElement writeXml(QDomElement &element, QDomDocument &doc, const QgsReadWriteContext &context) override
Writes the properties to a DOM element, to be used later with readXml().
Qgis::TemporalUnit durationUnits() const
Returns the units of the event's duration.
void setAccumulateFeatures(bool accumulate)
Sets whether features will be accumulated over time (i.e.
void setFixedDuration(double duration)
Sets the fixed event duration, which contains the duration of the event.
void setEndField(const QString &field)
Sets the name of the end datetime field, which contains the end time for the feature's time spans.
QgsDateTimeRange calculateTemporalExtent(QgsMapLayer *layer) const override
Attempts to calculate the overall temporal extent for the specified layer, using the settings defined...
void setDefaultsFromDataProviderTemporalCapabilities(const QgsDataProviderTemporalCapabilities *capabilities) override
Sets the layers temporal settings to appropriate defaults based on a provider's temporal capabilities...
Qgis::VectorTemporalMode mode() const
Returns the temporal properties mode.
QString startField() const
Returns the name of the start datetime field, which contains the start time for the feature's time sp...
void setStartField(const QString &field)
Sets the name of the start datetime field, which contains the start time for the feature's time spans...
QString startExpression() const
Returns the expression for the start time for the feature's time spans.
Represents a vector layer which manages a vector based dataset.
QVariant minimumValue(int index) const final
Returns the minimum value for an attribute column or an invalid variant in case of error.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
void minimumAndMaximumValue(int index, QVariant &minimum, QVariant &maximum) const
Calculates both the minimum and maximum value for an attribute column.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
QList< int > QgsAttributeList
QgsTemporalRange< QDateTime > QgsDateTimeRange
QgsRange which stores a range of date times.
QString dateTimeExpressionLiteral(const QDateTime &datetime)