29#include "moc_qgsvectorlayertemporalproperties.cpp"
31using namespace Qt::StringLiterals;
45 return range.
isInfinite() || mFixedRange.isInfinite() || mFixedRange.overlaps( range );
59 QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer );
71 if ( fieldIndex >= 0 )
77 const QDateTime min = minVal.toDateTime();
78 const QDateTime maxStartTime = maxVal.toDateTime();
88 const int durationFieldIndex = vectorLayer->
fields().
lookupField( mDurationFieldName );
89 if ( fieldIndex >= 0 && durationFieldIndex >= 0 )
91 const QDateTime minTime = vectorLayer->
minimumValue( fieldIndex ).toDateTime();
101 const QDateTime start = f.
attribute( fieldIndex ).toDateTime();
102 if ( start.isValid() )
104 const QVariant durationValue = f.
attribute( durationFieldIndex );
105 if ( durationValue.isValid() )
107 const double duration = durationValue.toDouble();
108 const QDateTime end = start.addMSecs(
QgsInterval( duration, mDurationUnit ).seconds() * 1000.0 );
110 maxTime = maxTime.isValid() ? std::max( maxTime, end ) : end;
121 const int startFieldIndex = vectorLayer->
fields().
lookupField( mStartFieldName );
123 if ( startFieldIndex >= 0 && endFieldIndex >= 0 )
125 QVariant startMinVal;
126 QVariant startMaxVal;
132 return QgsDateTimeRange( std::min( startMinVal.toDateTime(), endMinVal.toDateTime() ), std::max( startMaxVal.toDateTime(), endMaxVal.toDateTime() ) );
134 else if ( startFieldIndex >= 0 )
136 QVariant startMinVal;
137 QVariant startMaxVal;
139 return QgsDateTimeRange( startMinVal.toDateTime(), startMaxVal.toDateTime() );
141 else if ( endFieldIndex >= 0 )
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( u
"temporal"_s );
269 setIsActive( temporalNode.attribute( u
"enabled"_s, u
"0"_s ).toInt() );
274 mStartFieldName = temporalNode.attribute( u
"startField"_s );
275 mEndFieldName = temporalNode.attribute( u
"endField"_s );
276 mStartExpression = temporalNode.attribute( u
"startExpression"_s );
277 mEndExpression = temporalNode.attribute( u
"endExpression"_s );
278 mDurationFieldName = temporalNode.attribute( u
"durationField"_s );
280 mFixedDuration = temporalNode.attribute( u
"fixedDuration"_s ).toDouble();
281 mAccumulateFeatures = temporalNode.attribute( u
"accumulate"_s, u
"0"_s ).toInt();
283 const QDomNode rangeElement = temporalNode.namedItem( u
"fixedRange"_s );
285 const QDomNode begin = rangeElement.namedItem( u
"start"_s );
286 const QDomNode end = rangeElement.namedItem( u
"end"_s );
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( u
"temporal"_s );
304 temporalElement.setAttribute( u
"enabled"_s,
isActive() ? u
"1"_s : u
"0"_s );
305 temporalElement.setAttribute( u
"mode"_s, QString::number(
static_cast< int >( mMode ) ) );
307 temporalElement.setAttribute( u
"limitMode"_s, QString::number(
static_cast< int >( mLimitMode ) ) );
308 temporalElement.setAttribute( u
"startField"_s, mStartFieldName );
309 temporalElement.setAttribute( u
"endField"_s, mEndFieldName );
310 temporalElement.setAttribute( u
"startExpression"_s, mStartExpression );
311 temporalElement.setAttribute( u
"endExpression"_s, mEndExpression );
312 temporalElement.setAttribute( u
"durationField"_s, mDurationFieldName );
314 temporalElement.setAttribute( u
"fixedDuration"_s,
qgsDoubleToString( mFixedDuration ) );
315 temporalElement.setAttribute( u
"accumulate"_s, mAccumulateFeatures ? u
"1"_s : u
"0"_s );
317 QDomElement rangeElement = document.createElement( u
"fixedRange"_s );
319 QDomElement startElement = document.createElement( u
"start"_s );
320 QDomElement endElement = document.createElement( u
"end"_s );
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 u
"make_datetime(%1,%2,%3,%4,%5,%6)"_s.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 {
472 if ( mAccumulateFeatures )
478 return u
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL"_s.arg(
479 dateTimefieldCast( mStartFieldName ),
489 return u
"(%1 %2 %3 AND %1 %4 %5) OR %1 IS NULL"_s.arg(
490 dateTimefieldCast( mStartFieldName ),
501 QString intervalExpression;
502 switch ( mDurationUnit )
548 return u
"(%1 %2 %3 OR %1 IS NULL) AND ((%1 + %4 %5 %6) OR %7 IS NULL)"_s.arg(
549 dateTimefieldCast( mStartFieldName ),
561 if ( !mStartFieldName.isEmpty() && !mEndFieldName.isEmpty() )
563 return u
"(%1 %2 %3 OR %1 IS NULL) AND (%4 %5 %6 OR %4 IS NULL)"_s.arg(
564 dateTimefieldCast( mStartFieldName ),
567 dateTimefieldCast( mEndFieldName ),
572 else if ( !mStartFieldName.isEmpty() )
576 else if ( !mEndFieldName.isEmpty() )
578 return u
"%1 %2 %3 OR %1 IS NULL"_s
586 if ( !mStartExpression.isEmpty() && !mEndExpression.isEmpty() )
588 return u
"((%1) %2 %3) AND ((%4) %5 %6)"_s.arg(
597 else if ( !mStartExpression.isEmpty() )
601 else if ( !mEndExpression.isEmpty() )
620 static const QStringList sStartCandidates {
632 static const QStringList sEndCandidates {
643 static const QStringList sSingleFieldCandidates { u
"event"_s };
646 bool foundStart =
false;
647 bool foundEnd =
false;
649 for (
const QgsField &field : fields )
651 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
656 for (
const QString &candidate : sStartCandidates )
658 const QString fldName = field.name();
659 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
661 mStartFieldName = fldName;
669 for (
const QString &candidate : sEndCandidates )
671 const QString fldName = field.name();
672 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
674 mEndFieldName = fldName;
680 if ( foundStart && foundEnd )
687 for (
const QgsField &field : fields )
689 if ( field.type() != QMetaType::Type::QDate && field.type() != QMetaType::Type::QDateTime )
692 for (
const QString &candidate : sSingleFieldCandidates )
694 const QString fldName = field.name();
695 if ( fldName.indexOf( candidate, 0, Qt::CaseInsensitive ) > -1 )
697 mStartFieldName = fldName;
707 if ( foundStart && foundEnd )
709 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)