29#include "moc_qgsvectorlayertemporalproperties.cpp"
31using namespace Qt::StringLiterals;
46 return range.
isInfinite() || mFixedRange.isInfinite() || mFixedRange.overlaps( range );
60 QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer );
72 if ( fieldIndex >= 0 )
78 const QDateTime min = minVal.toDateTime();
79 const QDateTime maxStartTime = maxVal.toDateTime();
89 const int durationFieldIndex = vectorLayer->
fields().
lookupField( mDurationFieldName );
90 if ( fieldIndex >= 0 && durationFieldIndex >= 0 )
92 const QDateTime minTime = vectorLayer->
minimumValue( fieldIndex ).toDateTime();
100 const QDateTime start = f.
attribute( fieldIndex ).toDateTime();
101 if ( start.isValid() )
103 const QVariant durationValue = f.
attribute( durationFieldIndex );
104 if ( durationValue.isValid() )
106 const double duration = durationValue.toDouble();
107 const QDateTime end = start.addMSecs(
QgsInterval( duration, mDurationUnit ).seconds() * 1000.0 );
109 maxTime = maxTime.isValid() ? std::max( maxTime, end ) : end;
120 const int startFieldIndex = vectorLayer->
fields().
lookupField( mStartFieldName );
122 if ( startFieldIndex >= 0 && endFieldIndex >= 0 )
124 QVariant startMinVal;
125 QVariant startMaxVal;
132 endMinVal.toDateTime() ),
133 std::max( startMaxVal.toDateTime(),
134 endMaxVal.toDateTime() ) );
136 else if ( startFieldIndex >= 0 )
138 QVariant startMinVal;
139 QVariant startMaxVal;
142 startMaxVal.toDateTime() );
144 else if ( endFieldIndex >= 0 )
150 endMaxVal.toDateTime() );
157 const bool hasStartExpression = !mStartExpression.isEmpty();
158 const bool hasEndExpression = !mEndExpression.isEmpty();
159 if ( !hasStartExpression && !hasEndExpression )
170 if ( hasStartExpression )
177 if ( hasEndExpression )
183 QSet< QString > fields;
184 if ( hasStartExpression )
186 if ( hasEndExpression )
202 const QDateTime start = hasStartExpression ?
startExpression.evaluate( &context ).toDateTime() : QDateTime();
203 const QDateTime end = hasEndExpression ?
endExpression.evaluate( &context ).toDateTime() : QDateTime();
205 if ( start.isValid() )
207 minTime = minTime.isValid() ? std::min( minTime, start ) : start;
208 if ( !hasEndExpression )
209 maxTime = maxTime.isValid() ? std::max( maxTime, start ) : start;
213 maxTime = maxTime.isValid() ? std::max( maxTime, end ) : end;
214 if ( !hasStartExpression )
215 minTime = minTime.isValid() ? std::min( minTime, end ) : end;
271 const QDomElement temporalNode = element.firstChildElement( u
"temporal"_s );
273 setIsActive( temporalNode.attribute( u
"enabled"_s, u
"0"_s ).toInt() );
278 mStartFieldName = temporalNode.attribute( u
"startField"_s );
279 mEndFieldName = temporalNode.attribute( u
"endField"_s );
280 mStartExpression = temporalNode.attribute( u
"startExpression"_s );
281 mEndExpression = temporalNode.attribute( u
"endExpression"_s );
282 mDurationFieldName = temporalNode.attribute( u
"durationField"_s );
284 mFixedDuration = temporalNode.attribute( u
"fixedDuration"_s ).toDouble();
285 mAccumulateFeatures = temporalNode.attribute( u
"accumulate"_s, u
"0"_s ).toInt();
287 const QDomNode rangeElement = temporalNode.namedItem( u
"fixedRange"_s );
289 const QDomNode begin = rangeElement.namedItem( u
"start"_s );
290 const QDomNode end = rangeElement.namedItem( u
"end"_s );
292 const QDateTime beginDate = QDateTime::fromString( begin.toElement().text(), Qt::ISODate );
293 const QDateTime endDate = QDateTime::fromString( end.toElement().text(), Qt::ISODate );
304 if ( element.isNull() )
305 return QDomElement();
307 QDomElement temporalElement = document.createElement( u
"temporal"_s );
308 temporalElement.setAttribute( u
"enabled"_s,
isActive() ? u
"1"_s : u
"0"_s );
309 temporalElement.setAttribute( u
"mode"_s, QString::number(
static_cast< int >( mMode ) ) );
311 temporalElement.setAttribute( u
"limitMode"_s, QString::number(
static_cast< int >( mLimitMode ) ) );
312 temporalElement.setAttribute( u
"startField"_s, mStartFieldName );
313 temporalElement.setAttribute( u
"endField"_s, mEndFieldName );
314 temporalElement.setAttribute( u
"startExpression"_s, mStartExpression );
315 temporalElement.setAttribute( u
"endExpression"_s, mEndExpression );
316 temporalElement.setAttribute( u
"durationField"_s, mDurationFieldName );
318 temporalElement.setAttribute( u
"fixedDuration"_s,
qgsDoubleToString( mFixedDuration ) );
319 temporalElement.setAttribute( u
"accumulate"_s, mAccumulateFeatures ? u
"1"_s : u
"0"_s );
321 QDomElement rangeElement = document.createElement( u
"fixedRange"_s );
323 QDomElement startElement = document.createElement( u
"start"_s );
324 QDomElement endElement = document.createElement( u
"end"_s );
326 const QDomText startText = document.createTextNode( mFixedRange.begin().toTimeSpec( Qt::OffsetFromUTC ).toString( Qt::ISODate ) );
327 const QDomText endText = document.createTextNode( mFixedRange.end().toTimeSpec( Qt::OffsetFromUTC ).toString( Qt::ISODate ) );
328 startElement.appendChild( startText );
329 endElement.appendChild( endText );
330 rangeElement.appendChild( startElement );
331 rangeElement.appendChild( endElement );
333 temporalElement.appendChild( rangeElement );
335 element.appendChild( temporalElement );
344 setIsActive( vectorCaps->hasTemporalCapabilities() );
348 switch ( vectorCaps->mode() )
365 return mStartExpression;
375 return mEndExpression;
385 return mAccumulateFeatures;
395 return mFixedDuration;
405 return mStartFieldName;
410 mStartFieldName = startFieldName;
415 return mEndFieldName;
420 mEndFieldName = field;
425 return mDurationFieldName;
430 mDurationFieldName = field;
435 return mDurationUnit;
440 mDurationUnit = units;
445 return u
"make_datetime(%1,%2,%3,%4,%5,%6)"_s.arg( datetime.date().year() )
446 .arg( datetime.date().month() )
447 .arg( datetime.date().day() )
448 .arg( datetime.time().hour() )
449 .arg( datetime.time().minute() )
450 .arg( datetime.time().second() + datetime.time().msec() / 1000.0 );
458 auto dateTimefieldCast = [ &context ](
const QString & fieldName ) -> QString
477 if ( mAccumulateFeatures )
479 return u
"(%1 %2 %3) OR %1 IS NULL"_s.arg( dateTimefieldCast( mStartFieldName ),
485 return u
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL"_s.arg( dateTimefieldCast( mStartFieldName ),
494 return u
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL"_s.arg( dateTimefieldCast( mStartFieldName ),
504 QString intervalExpression;
505 switch ( mDurationUnit )
551 return u
"(%1 %2 %3 OR %1 IS NULL) AND ((%1 + %4 %5 %6) OR %7 IS NULL)"_s.arg( dateTimefieldCast( mStartFieldName ),
562 if ( !mStartFieldName.isEmpty() && !mEndFieldName.isEmpty() )
564 return u
"(%1 %2 %3 OR %1 IS NULL) AND (%4 %5 %6 OR %4 IS NULL)"_s.arg( dateTimefieldCast( mStartFieldName ),
567 dateTimefieldCast( mEndFieldName ),
572 else if ( !mStartFieldName.isEmpty() )
574 return u
"%1 %2 %3 OR %1 IS NULL"_s.arg( dateTimefieldCast( mStartFieldName ),
578 else if ( !mEndFieldName.isEmpty() )
580 return u
"%1 %2 %3 OR %1 IS NULL"_s.arg( dateTimefieldCast( mEndFieldName ),
589 if ( !mStartExpression.isEmpty() && !mEndExpression.isEmpty() )
591 return u
"((%1) %2 %3) AND ((%4) %5 %6)"_s.arg( mStartExpression,
598 else if ( !mStartExpression.isEmpty() )
600 return u
"(%1) %2 %3"_s.arg( mStartExpression,
604 else if ( !mEndExpression.isEmpty() )
606 return u
"(%1) %2 %3"_s.arg( mEndExpression,
626 static const QStringList sStartCandidates{ u
"start"_s,
636 static const QStringList sEndCandidates{ u
"end"_s,
645 static const QStringList sSingleFieldCandidates{ u
"event"_s };
648 bool foundStart =
false;
649 bool foundEnd =
false;
651 for (
const QgsField &field : fields )
653 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
658 for (
const QString &candidate : sStartCandidates )
660 const QString fldName = field.name();
661 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
663 mStartFieldName = fldName;
671 for (
const QString &candidate : sEndCandidates )
673 const QString fldName = field.name();
674 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
676 mEndFieldName = fldName;
682 if ( foundStart && foundEnd )
689 for (
const QgsField &field : fields )
691 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
694 for (
const QString &candidate : sSingleFieldCandidates )
696 const QString fldName = field.name();
697 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
699 mStartFieldName = fldName;
709 if ( foundStart && foundEnd )
711 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)