QmlMaterial 0.1.0
Loading...
Searching...
No Matches
item_demand.hpp
1#pragma once
2
3#include <QtQml/qqmlregistration.h>
4#include "qml_material/model/item_snapshot.hpp"
5#include <algorithm>
6#include <limits>
7
8namespace qml_material
9{
10class QML_MATERIAL_API ItemDemand {
11 Q_GADGET
12 QML_VALUE_TYPE(itemDemand)
13 Q_PROPERTY(bool valid READ valid)
14 Q_PROPERTY(int first READ first CONSTANT)
15 Q_PROPERTY(int count READ count CONSTANT)
16 Q_PROPERTY(QVector<int> indices READ indices CONSTANT)
17 Q_PROPERTY(quint64 revision READ revision CONSTANT)
18 Q_PROPERTY(bool reachesEnd READ reachesEnd CONSTANT)
19public:
20 ItemDemand() = default;
21 ItemDemand(ItemSnapshotPtr snapshot, int first, int count, bool reachesEnd = false)
22 : m_snapshot(std::move(snapshot)), m_first(first), m_count(count), m_end(reachesEnd) {}
23 ItemDemand(ItemSnapshotPtr snapshot, QVector<int> indices, bool reachesEnd = false)
24 : m_snapshot(std::move(snapshot)), m_indices(std::move(indices)), m_end(reachesEnd) {
25 std::sort(m_indices.begin(), m_indices.end());
26 m_indices.erase(std::unique(m_indices.begin(), m_indices.end()), m_indices.end());
27 if (! m_indices.isEmpty()) {
28 m_first = m_indices.first();
29 const auto length = qint64(m_indices.last()) - m_first + 1;
30 m_count = length <= std::numeric_limits<int>::max() ? int(length) : -1;
31 }
32 }
33 ItemSnapshotPtr snapshot() const { return m_snapshot; }
34 int first() const { return m_first; }
35 int count() const { return m_count; }
36 QVector<int> indices() const {
37 QVector<int> result;
38 if (! valid()) return result;
39 if (! m_indices.isEmpty()) return m_indices;
40 result.reserve(m_count);
41 for (int i = 0; i < m_count; ++i) result.append(m_first + i);
42 return result;
43 }
44 quint64 revision() const { return m_snapshot ? m_snapshot->revision : 0; }
45 bool reachesEnd() const { return m_end; }
46 bool valid() const {
47 return m_snapshot && m_first >= 0 && m_count >= 0 &&
48 qint64(m_first) + m_count <= m_snapshot->count() &&
49 (! m_tracked || ! m_lifetime.expired());
50 }
51
52private:
53 friend class LazyView;
54 ItemSnapshotPtr m_snapshot;
55 int m_first = 0;
56 int m_count = 0;
57 QVector<int> m_indices;
58 bool m_end = false;
59 bool m_tracked = false;
60 std::weak_ptr<const bool> m_lifetime;
61};
62} // namespace qml_material
63Q_DECLARE_METATYPE(qml_material::ItemDemand)