Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qrangemodeladapter.h
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#ifndef QRANGEMODELADAPTER_H
6#define QRANGEMODELADAPTER_H
7
8#include <QtCore/qrangemodeladapter_impl.h>
9
10#include <QtCore/q26numeric.h>
11#include <QtCore/qttypetraits.h>
12
13QT_BEGIN_NAMESPACE
14
15template <typename Range, typename Protocol = void, typename Model = QRangeModel>
16class QT_TECH_PREVIEW_API QRangeModelAdapter
17{
18 using Impl = QRangeModelDetails::RangeImplementation<Range, Protocol>;
19 using Storage = QRangeModelDetails::AdapterStorage<Model, Impl>;
20
21 Storage storage;
22
23#ifdef Q_QDOC
24 using range_type = Range;
25#else
26 using range_type = QRangeModelDetails::wrapped_t<Range>;
27#endif
28 using const_row_reference = typename Impl::const_row_reference;
29 using row_reference = typename Impl::row_reference;
30 using range_features = typename QRangeModelDetails::range_traits<range_type>;
31 using row_type = std::remove_reference_t<row_reference>;
32 using row_features = QRangeModelDetails::range_traits<typename Impl::wrapped_row_type>;
33 using row_ptr = typename Impl::wrapped_row_type *;
34 using row_traits = typename Impl::row_traits;
35 using item_type = std::remove_reference_t<typename row_traits::item_type>;
36 using data_type = typename QRangeModelDetails::data_type<item_type>::type;
37 using const_data_type = QRangeModelDetails::asConst_t<data_type>;
38 using protocol_traits = typename Impl::protocol_traits;
39
40 template <typename I> static constexpr bool is_list = I::protocol_traits::is_list;
41 template <typename I> static constexpr bool is_table = I::protocol_traits::is_table;
42 template <typename I> static constexpr bool is_tree = I::protocol_traits::is_tree;
43 template <typename I> static constexpr bool canInsertColumns = I::dynamicColumns()
44 && I::isMutable()
45 && row_features::has_insert;
46 template <typename I> static constexpr bool canRemoveColumns = I::dynamicColumns()
47 && I::isMutable()
48 && row_features::has_erase;
49
50 template <typename I> using if_writable = std::enable_if_t<I::isMutable(), bool>;
51 template <typename I> static constexpr bool canSort = I::isMutable()
52 && std::is_swappable_v<row_type>;
53 template <typename I> using if_canSort = std::enable_if_t<canSort<I>, bool>;
54 template <typename I> using if_list = std::enable_if_t<is_list<I>, bool>;
55 template <typename I> using unless_list = std::enable_if_t<!is_list<I>, bool>;
56 template <typename I> using if_table = std::enable_if_t<is_table<I>, bool>;
57 template <typename I> using if_tree = std::enable_if_t<is_tree<I>, bool>;
58 template <typename I> using unless_tree = std::enable_if_t<!is_tree<I>, bool>;
59 template <typename I> using if_flat = std::enable_if_t<is_list<I> || is_table<I>, bool>;
60
61 template <typename I>
62 using if_canInsertRows = std::enable_if_t<I::canInsertRows(), bool>;
63 template <typename I> static constexpr bool canRemoveRows = I::canRemoveRows();
64 template <typename I>
65 using if_canRemoveRows = std::enable_if_t<canRemoveRows<I>, bool>;
66 template <typename F>
67 using if_canMoveItems = std::enable_if_t<F::has_rotate || F::has_splice, bool>;
68
69 template <typename I>
70 using if_canInsertColumns = std::enable_if_t<canInsertColumns<I>, bool>;
71 template <typename I>
72 using if_canRemoveColumns = std::enable_if_t<canRemoveColumns<I>, bool>;
73
74 template <typename Row>
75 static constexpr bool is_compatible_row = std::is_convertible_v<Row, const_row_reference>;
76 template <typename Row>
77 using if_compatible_row = std::enable_if_t<is_compatible_row<Row>, bool>;
78
79 template <typename C>
80 static constexpr bool is_compatible_row_range = is_compatible_row<
81 decltype(*std::begin(std::declval<C&>()))
82 >;
83 template <typename C>
84 using if_compatible_row_range = std::enable_if_t<is_compatible_row_range<C>, bool>;
85 template <typename Data>
86 static constexpr bool is_compatible_data = std::is_convertible_v<Data, data_type>;
87 template <typename Data>
88 using if_compatible_data = std::enable_if_t<is_compatible_data<Data>, bool>;
89 template <typename C>
90 static constexpr bool is_compatible_data_range = is_compatible_data<
91 typename QRangeModelDetails::data_type<
92 typename QRangeModelDetails::row_traits<
93 decltype(*std::begin(std::declval<C&>()))
94 >::item_type
95 >::type
96 >;
97 template <typename C>
98 using if_compatible_column_data = std::enable_if_t<is_compatible_data<C>
99 || is_compatible_data_range<C>, bool>;
100 template <typename C>
101 using if_compatible_column_range = std::enable_if_t<is_compatible_data_range<C>, bool>;
102
103 template <typename R>
104 using if_assignable_range = std::enable_if_t<std::is_assignable_v<range_type, R>, bool>;
105
106 // Without arguments, the model creates the row, respecting the protocol
107 // and the number of columns.
108 template <typename ...Args>
109 static constexpr bool is_emplaceable = sizeof...(Args) == 0
110 || std::is_constructible_v<std::remove_cv_t<row_type>, Args...>;
111 template <typename ...Args>
112 using if_emplaceable = std::enable_if_t<is_emplaceable<Args...>, bool>;
113
114 template <typename It>
115 static constexpr bool is_compatible_row_iterator
116 = QRangeModelDetails::is_compatible_forward_iterator<It, const_row_reference>::value;
117 template <typename It>
118 using if_compatible_row_iterator = std::enable_if_t<is_compatible_row_iterator<It>, bool>;
119
120 // Inserting count copies of a raw pointer row would leave the model with
121 // multiple owning pointers to the same row.
122 template <typename I> static constexpr bool canInsertCopies = I::canInsertRows()
123 && range_features::has_insert
124 && std::is_copy_constructible_v<row_type>
125 && !std::is_pointer_v<row_type>;
126 template <typename I>
127 using if_canInsertCopies = std::enable_if_t<canInsertCopies<I>, bool>;
128 // If the range has no assign(count, value), then we erase all rows and
129 // insert the copies.
130 template <typename I> static constexpr bool canAssignCopies = I::isMutable()
131 && (QRangeModelDetails::has_assign_count<range_type>::value
132 || (range_features::has_insert
133 && range_features::has_erase))
134 && std::is_copy_constructible_v<row_type>
135 && !std::is_pointer_v<row_type>;
136 template <typename I>
137 using if_canAssignCopies = std::enable_if_t<canAssignCopies<I>, bool>;
138
139 friend class QRangeModel;
140 template <typename T>
141 static constexpr bool is_adapter = QRangeModelDetails::is_any_of<q20::remove_cvref_t<T>,
142 QRangeModelAdapter>::value;
143 template <typename T>
144 using unless_adapter = std::enable_if_t<!is_adapter<T>, bool>;
145
146 template <typename R, typename P>
147 using if_compatible_model_params =
148 std::enable_if_t<
149 std::conjunction_v<
150 std::disjunction<
151 std::is_convertible<R &&, Range>,
152 std::is_convertible<R &&, Range &&> // for C-arrays
153 >,
154 std::is_convertible<P, Protocol> // note, only void is expected to be convertible to void
155 >, bool>;
156
157#if !defined(Q_OS_VXWORKS) && !defined(Q_OS_INTEGRITY)
158 // An adapter on a mutable range can make itself an adapter on a const
159 // version of that same range. To make the constructor for a sub-range
160 // accessible, befriend the mutable version. We can use more
161 // generic pattern matching here, as we only use as input what asConst
162 // might produce as output.
163 template <typename T> static constexpr T asMutable(const T &);
164 template <typename T> static constexpr T *asMutable(const T *);
165 template <template <typename, typename...> typename U, typename T, typename ...Args>
166 static constexpr U<T, Args...> asMutable(const U<const T, Args...> &);
167
168 template <typename T>
169 using asMutable_t = decltype(asMutable(std::declval<T>()));
170 friend class QRangeModelAdapter<asMutable_t<Range>, Protocol, Model>;
171#else
172 template <typename R, typename P, typename M>
173 friend class QRangeModelAdapter;
174#endif
175
176 explicit QRangeModelAdapter(const std::shared_ptr<QRangeModel> &model, const QModelIndex &root,
177 std::in_place_t) // disambiguate from range/protocol c'tor
178 : storage{model, root}
179 {}
180
181 explicit QRangeModelAdapter(QRangeModel *model)
182 : storage(model)
183 {}
184
185public:
186 struct DataReference
187 {
188#ifdef Q_QDOC
189 using value_type = int;
190 using const_value_type = const int;
191 using pointer = void *;
192#else
193 using value_type = data_type;
194 using const_value_type = const_data_type;
195 using pointer = QRangeModelDetails::data_pointer_t<const_value_type>;
196#endif
197
198 explicit DataReference(const QModelIndex &index) noexcept
199 : m_index(index)
200 {}
201
202 DataReference(const DataReference &other) = default;
203 DataReference(DataReference &&other) = default;
204
205 // reference (not std::reference_wrapper) semantics
206 DataReference &operator=(const DataReference &other)
207 {
208 *this = other.get();
209 return *this;
210 }
211
212 ~DataReference() = default;
213
214 DataReference &operator=(const value_type &value)
215 {
216 assign(value);
217 return *this;
218 }
219
220 DataReference &operator=(value_type &&value)
221 {
222 assign(std::move(value));
223 return *this;
224 }
225
226 const_value_type get() const
227 {
228 Q_ASSERT_X(m_index.isValid(), "QRangeModelAdapter::at", "Index at position is invalid");
229 return QRangeModelDetails::dataAtIndex<q20::remove_cvref_t<value_type>>(m_index);
230 }
231
232 operator const_value_type() const
233 {
234 return get();
235 }
236
237 pointer operator->() const
238 {
239 return {get()};
240 }
241
242 bool isValid() const { return m_index.isValid(); }
243
244 private:
245 QModelIndex m_index;
246
247 template <typename Value>
248 void assign(Value &&value)
249 {
250 constexpr Qt::ItemDataRole dataRole = Qt::RangeModelAdapterRole;
251
252 if (m_index.isValid()) {
253 auto model = const_cast<QAbstractItemModel *>(m_index.model());
254 [[maybe_unused]] bool couldWrite = false;
255 if constexpr (std::is_same_v<q20::remove_cvref_t<Value>, QVariant>) {
256 couldWrite = model->setData(m_index, value, dataRole);
257 } else {
258 couldWrite = model->setData(m_index,
259 QVariant::fromValue(std::forward<Value>(value)),
260 dataRole);
261 }
262#ifndef QT_NO_DEBUG
263 if (!couldWrite) {
264 qWarning() << "Writing value of type"
265 << QMetaType::fromType<q20::remove_cvref_t<Value>>().name()
266 << "to role" << dataRole << "at index" << m_index << "failed";
267 }
268 } else {
269 qCritical("Data reference for invalid index, can't write to model");
270#endif
271 }
272 }
273
274 friend inline bool comparesEqual(const DataReference &lhs, const DataReference &rhs)
275 {
276 return lhs.m_index == rhs.m_index
277 || lhs.get() == rhs.get();
278 }
279 Q_DECLARE_EQUALITY_COMPARABLE_NON_NOEXCEPT(DataReference)
280
281 friend inline bool comparesEqual(const DataReference &lhs, const value_type &rhs)
282 {
283 return lhs.get() == rhs;
284 }
285 Q_DECLARE_EQUALITY_COMPARABLE_NON_NOEXCEPT(DataReference, value_type)
286
287#ifndef Q_QDOC
288 // relational operators, if the value type provides operator<
289#define QRMA_DATAREFERENCE_RELATIONAL_OPERATOR(op, expression)
290 template <typename U = value_type>
291 friend QTypeTraits::compare_lt_result<U>
292 operator op(const DataReference &lhs, const DataReference &rhs)
293 { const value_type &a = lhs.get(); const value_type &b = rhs.get(); return expression; }
294 template <typename U = value_type>
295 friend QTypeTraits::compare_lt_result<U>
296 operator op(const DataReference &lhs, const value_type &b)
297 { const value_type &a = lhs.get(); return expression; }
298 template <typename U = value_type>
299 friend QTypeTraits::compare_lt_result<U>
300 operator op(const value_type &a, const DataReference &rhs)
301 { const value_type &b = rhs.get(); return expression; }
302
307#undef QRMA_DATAREFERENCE_RELATIONAL_OPERATOR
308#endif // Q_QDOC
309
310 // Swapping would make standard algorithms reorder the items by
311 // writing data, which doesn't update persistent indexes.
312 friend void swap(DataReference lhs, DataReference rhs) = delete;
313
314#ifndef QT_NO_DEBUG_STREAM
315 friend inline QDebug operator<<(QDebug dbg, const DataReference &ref)
316 {
317 return dbg << ref.get();
318 }
319#endif
320#ifndef QT_NO_DATASTREAM
321 friend inline QDataStream &operator<<(QDataStream &ds, const DataReference &ref)
322 {
323 return ds << ref.get();
324 }
325 friend inline QDataStream &operator>>(QDataStream &ds, DataReference &ref)
326 {
327 value_type value;
328 ds >> value;
329 ref = std::move(value);
330 return ds;
331 }
332#endif
333 };
334 template <typename Iterator, typename Adapter>
335 struct ColumnIteratorBase
336 {
337 using iterator_category = std::random_access_iterator_tag;
338 using difference_type = int;
339
340 ColumnIteratorBase() = default;
341 ColumnIteratorBase(const ColumnIteratorBase &other) = default;
342 ColumnIteratorBase(ColumnIteratorBase &&other) = default;
343 ColumnIteratorBase &operator=(const ColumnIteratorBase &other) = default;
344 ColumnIteratorBase &operator=(ColumnIteratorBase &&other) = default;
345
346 ColumnIteratorBase(const QModelIndex &rowIndex, int column, Adapter *adapter) noexcept
347 : m_rowIndex(rowIndex), m_column(column), m_adapter(adapter)
348 {
349 }
350
351 void swap(ColumnIteratorBase &other) noexcept
352 {
353 std::swap(m_rowIndex, other.m_rowIndex);
354 std::swap(m_column, other.m_column);
355 q_ptr_swap(m_adapter, other.m_adapter);
356 }
357
358 friend Iterator &operator++(Iterator &that)
359 {
360 ++that.m_column;
361 return that;
362 }
363 friend Iterator operator++(Iterator &that, int)
364 {
365 auto copy = that;
366 ++that;
367 return copy;
368 }
369 friend Iterator operator+(const Iterator &that, difference_type n)
370 {
371 return {that.m_rowIndex, that.m_column + n, that.m_adapter};
372 }
373 friend Iterator operator+(difference_type n, const Iterator &that)
374 {
375 return that + n;
376 }
377 friend Iterator &operator+=(Iterator &that, difference_type n)
378 {
379 that.m_column += n;
380 return that;
381 }
382
383 friend Iterator &operator--(Iterator &that)
384 {
385 --that.m_column;
386 return that;
387 }
388 friend Iterator operator--(Iterator &that, int)
389 {
390 auto copy = that;
391 --that;
392 return copy;
393 }
394 friend Iterator operator-(const Iterator &that, difference_type n)
395 {
396 return {that.m_rowIndex, that.m_column - n, that.m_adapter};
397 }
398 friend Iterator operator-(difference_type n, const Iterator &that)
399 {
400 return that - n;
401 }
402 friend Iterator &operator-=(Iterator &that, difference_type n)
403 {
404 that.m_column -= n;
405 return that;
406 }
407
408 friend difference_type operator-(const Iterator &lhs, const Iterator &rhs)
409 {
410 Q_PRE(lhs.m_rowIndex == rhs.m_rowIndex);
411 Q_PRE(lhs.m_adapter == rhs.m_adapter);
412 return lhs.m_column - rhs.m_column;
413 }
414
415 protected:
416 ~ColumnIteratorBase() = default;
417 QModelIndex m_rowIndex;
418 int m_column = -1;
419 Adapter *m_adapter = nullptr;
420
421 private:
422 friend bool comparesEqual(const Iterator &lhs, const Iterator &rhs)
423 {
424 Q_ASSERT(lhs.m_rowIndex == rhs.m_rowIndex);
425 return lhs.m_column == rhs.m_column;
426 }
427 friend Qt::strong_ordering compareThreeWay(const Iterator &lhs, const Iterator &rhs)
428 {
429 Q_ASSERT(lhs.m_rowIndex == rhs.m_rowIndex);
430 return qCompareThreeWay(lhs.m_column, rhs.m_column);
431 }
432
433 Q_DECLARE_STRONGLY_ORDERED_NON_NOEXCEPT(Iterator)
434
435#ifndef QT_NO_DEBUG_STREAM
436 friend inline QDebug operator<<(QDebug dbg, const Iterator &it)
437 {
438 QDebugStateSaver saver(dbg);
439 dbg.nospace();
440 return dbg << "ColumnIterator(" << it.m_rowIndex.siblingAtColumn(it.m_column) << ")";
441 }
442#endif
443 };
444
445 struct ConstColumnIterator : ColumnIteratorBase<ConstColumnIterator, const QRangeModelAdapter>
446 {
447 private:
448 using Base = ColumnIteratorBase<ConstColumnIterator, const QRangeModelAdapter>;
449 public:
450 using difference_type = typename Base::difference_type;
451 using value_type = data_type;
452 using reference = const_data_type;
453 using pointer = QRangeModelDetails::data_pointer_t<value_type>;
454
455 using Base::Base;
456 ~ConstColumnIterator() = default;
457
458 pointer operator->() const
459 {
460 return pointer{operator*()};
461 }
462
463 reference operator*() const
464 {
465 return std::as_const(this->m_adapter)->at(this->m_rowIndex.row(), this->m_column);
466 }
467
468 reference operator[](difference_type n) const
469 {
470 return *(*this + n);
471 }
472 };
473
474 struct ColumnIterator : ColumnIteratorBase<ColumnIterator, QRangeModelAdapter>
475 {
476 private:
477 using Base = ColumnIteratorBase<ColumnIterator, QRangeModelAdapter>;
478 public:
479 using difference_type = typename Base::difference_type;
480 // not the proxy, see RowIterator::value_type
481 using value_type = data_type;
482 using reference = DataReference;
483 using pointer = reference;
484
485 using Base::Base;
486 ~ColumnIterator() = default;
487
488 operator ConstColumnIterator() const
489 {
490 return ConstColumnIterator{this->m_rowIndex, this->m_column, this->m_adapter};
491 }
492
493 pointer operator->() const
494 {
495 return operator*();
496 }
497
498 reference operator*() const
499 {
500 return reference{this->m_rowIndex.siblingAtColumn(this->m_column)};
501 }
502
503 reference operator[](difference_type n) const
504 {
505 return *(*this + n);
506 }
507 };
508
509 template <typename Reference, typename const_row_type,
510 bool = std::is_reference_v<const_row_type>,
511 bool = std::is_pointer_v<const_row_type>>
512 struct RowGetter
513 {
514 const_row_type get() const
515 {
516 const Reference *that = static_cast<const Reference *>(this);
517 const auto *impl = that->m_adapter->storage.implementation();
518 auto *childRange = impl->childRange(that->m_index.parent());
519 if constexpr (std::is_convertible_v<const row_type &, const_row_type>) {
520 return *std::next(QRangeModelDetails::adl_begin(childRange), that->m_index.row());
521 } else {
522 const auto &row = *std::next(QRangeModelDetails::adl_begin(childRange),
523 that->m_index.row());
524 return const_row_type{QRangeModelDetails::adl_begin(row),
525 QRangeModelDetails::adl_end(row)};
526 }
527 }
528
529 const_row_type operator->() const
530 {
531 return {get()};
532 }
533
534 operator const_row_type() const
535 {
536 return get();
537 }
538 };
539
540 template <typename Reference, typename const_row_type>
541 struct RowGetter<Reference, const_row_type, true, false>
542 {
543 const_row_type get() const
544 {
545 const Reference *that = static_cast<const Reference *>(this);
546 const auto *impl = that->m_adapter->storage.implementation();
547 return *std::next(QRangeModelDetails::begin(
548 QRangeModelDetails::refTo(impl->childRange(that->m_index.parent()))),
549 that->m_index.row());
550 }
551
552 auto operator->() const
553 {
554 return std::addressof(get());
555 }
556
557 operator const_row_type() const
558 {
559 return get();
560 }
561 };
562
563 template <typename Reference, typename const_row_type>
564 struct RowGetter<Reference, const_row_type, false, true>
565 {
566 const_row_type get() const
567 {
568 const Reference *that = static_cast<const Reference *>(this);
569 const auto *impl = that->m_adapter->storage.implementation();
570 return *std::next(QRangeModelDetails::begin(
571 QRangeModelDetails::refTo(impl->childRange(that->m_index.parent()))),
572 that->m_index.row());
573 }
574
575 const_row_type operator->() const
576 {
577 return get();
578 }
579
580 operator const_row_type() const
581 {
582 return get();
583 }
584 };
585
586 template <typename Reference, typename Adapter>
587 struct RowReferenceBase : RowGetter<Reference, QRangeModelDetails::asConstRow_t<row_type>>
588 {
589 using const_iterator = ConstColumnIterator;
590 using size_type = int;
591 using difference_type = int;
592 using const_row_type = QRangeModelDetails::asConstRow_t<row_type>;
593
594 RowReferenceBase(const QModelIndex &index, Adapter *adapter) noexcept
595 : m_index(index), m_adapter(adapter)
596 {}
597
598 template <typename I = Impl, if_tree<I> = true>
599 bool hasChildren() const
600 {
601 return m_adapter->model()->hasChildren(m_index);
602 }
603
604 template <typename I = Impl, if_tree<I> = true>
605 auto children() const
606 {
607 using ConstRange = QRangeModelDetails::asConst_t<Range>;
608 return QRangeModelAdapter<ConstRange, Protocol, Model>(m_adapter->storage.m_model,
609 m_index, std::in_place);
610 }
611
612 ConstColumnIterator cbegin() const
613 {
614 return ConstColumnIterator{m_index, 0, m_adapter};
615 }
616 ConstColumnIterator cend() const
617 {
618 return ConstColumnIterator{m_index, m_adapter->columnCount(), m_adapter};
619 }
620
621 ConstColumnIterator begin() const { return cbegin(); }
622 ConstColumnIterator end() const { return cend(); }
623
624 size_type size() const
625 {
626 return m_adapter->columnCount();
627 }
628
629 auto at(int column) const
630 {
631 Q_ASSERT(column >= 0 && column < m_adapter->columnCount());
632 return *ConstColumnIterator{m_index, column, m_adapter};
633 }
634
635 auto operator[](int column) const
636 {
637 return at(column);
638 }
639
640 protected:
641 friend struct RowGetter<Reference, const_row_type>;
642 ~RowReferenceBase() = default;
643 QModelIndex m_index;
644 Adapter *m_adapter;
645
646 private:
647 // A member, as MSVC doesn't give the hidden friends access to the
648 // private row_type of the enclosing adapter.
649 template <typename Other>
650 static bool rowsEqual(const Reference &lhs, const Other &rhs)
651 {
652 if constexpr (QTypeTraits::has_operator_equal_v<std::remove_cv_t<row_type>>)
653 return lhs.get() == rhs.get();
654 else
655 return false;
656 }
657
658 // reference semantics: two references are equal if they refer to the
659 // same row, or if the rows they refer to are equal
660 friend bool comparesEqual(const Reference &lhs, const Reference &rhs)
661 {
662 return lhs.m_index == rhs.m_index || rowsEqual(lhs, rhs);
663 }
664 Q_DECLARE_EQUALITY_COMPARABLE_NON_NOEXCEPT(Reference)
665
666#ifndef Q_QDOC
667 // for comparing with row references of other types
668 friend const QModelIndex &rowReferenceIndex(const Reference &ref) noexcept
669 {
670 return ref.m_index;
671 }
672
673 // Row references of other types: RowReference and ConstRowReference, and
674 // row references of other adapters for the same row type. As an exact
675 // match, this is preferred over the comparison with the row type, which
676 // would otherwise be ambiguous as both row references convert to that.
677 template <typename Other>
678 using if_comparable_row_reference = std::enable_if_t<
679 !std::is_same_v<Other, Reference>
680 && std::is_same_v<q20::remove_cvref_t<decltype(rowReferenceIndex(std::declval<const Other &>()))>,
681 QModelIndex>
682 && std::is_same_v<q20::remove_cvref_t<decltype(std::declval<const Other &>().get())>,
683 q20::remove_cvref_t<const_row_type>>, bool>;
684
685 template <typename Other, if_comparable_row_reference<Other> = true>
686 friend bool operator==(const Reference &lhs, const Other &rhs)
687 {
688 return lhs.m_index == rowReferenceIndex(rhs) || rowsEqual(lhs, rhs);
689 }
690#if !defined(__cpp_impl_three_way_comparison)
691 template <typename Other, if_comparable_row_reference<Other> = true>
692 friend bool operator!=(const Reference &lhs, const Other &rhs)
693 {
694 return !(lhs == rhs);
695 }
696#endif
697#endif // Q_QDOC
698
699 friend bool comparesEqual(const Reference &lhs, const row_type &rhs)
700 {
701 return lhs.get() == rhs;
702 }
703 Q_DECLARE_EQUALITY_COMPARABLE_NON_NOEXCEPT(Reference, row_type)
704
705#ifndef QT_NO_DEBUG_STREAM
706 friend inline QDebug operator<<(QDebug dbg, const Reference &ref)
707 {
708 QDebugStateSaver saver(dbg);
709 dbg.nospace();
710 return dbg << "RowReference(" << ref.m_index << ")";
711 }
712#endif
713#ifndef QT_NO_DATASTREAM
714 friend inline QDataStream &operator<<(QDataStream &ds, const Reference &ref)
715 {
716 return ds << ref.get();
717 }
718#endif
719 };
720
721 struct ConstRowReference : RowReferenceBase<ConstRowReference, const QRangeModelAdapter>
722 {
723 private:
724 using Base = RowReferenceBase<ConstRowReference, const QRangeModelAdapter>;
725 public:
726 using Base::Base;
727
728 ConstRowReference() = default;
729 ConstRowReference(const ConstRowReference &) = default;
730 ConstRowReference(ConstRowReference &&) = default;
731 ConstRowReference &operator=(const ConstRowReference &) = default;
732 ConstRowReference &operator=(ConstRowReference &&) = default;
733 ~ConstRowReference() = default;
734 };
735
736 struct RowReference : RowReferenceBase<RowReference, QRangeModelAdapter>
737 {
738 private:
739 using Base = RowReferenceBase<RowReference, QRangeModelAdapter>;
740 public:
741 using iterator = ColumnIterator;
742 using const_iterator = typename Base::const_iterator;
743 using size_type = typename Base::size_type;
744 using difference_type = typename Base::difference_type;
745#ifdef Q_QDOC
746 using row_type = int;
747#endif
748 using const_row_type = typename Base::const_row_type;
749
750 using Base::Base;
751 RowReference() = delete;
752 ~RowReference() = default;
753 RowReference(const RowReference &other) = default;
754 RowReference(RowReference &&other) = default;
755
756 // assignment has reference (std::reference_wrapper) semantics
757 RowReference &operator=(const ConstRowReference &other)
758 {
759 *this = other.get();
760 return *this;
761 }
762
763 RowReference &operator=(const RowReference &other)
764 {
765 *this = other.get();
766 return *this;
767 }
768
769 RowReference &operator=(const row_type &other)
770 {
771 assign(other);
772 return *this;
773 }
774
775 RowReference &operator=(row_type &&other)
776 {
777 assign(std::move(other));
778 return *this;
779 }
780
781 operator ConstRowReference() const
782 {
783 return ConstRowReference{this->m_index, this->m_adapter};
784 }
785
786 template <typename ConstRowType = const_row_type,
787 std::enable_if_t<!std::is_same_v<ConstRowType, const row_type &>, bool> = true>
788 RowReference &operator=(const ConstRowType &other)
789 {
790 assign(other);
791 return *this;
792 }
793
794 template <typename T, typename It, typename Sentinel>
795 RowReference &operator=(const QRangeModelDetails::RowView<T, It, Sentinel> &other)
796 {
797 *this = row_type{other.begin(), other.end()};
798 return *this;
799 }
800
801 // Swapping would make standard algorithms reorder the rows by
802 // writing data, which doesn't update persistent indexes.
803 friend void swap(RowReference lhs, RowReference rhs) = delete;
804
805 template <typename I = Impl, if_tree<I> = true>
806 auto children()
807 {
808 return QRangeModelAdapter(this->m_adapter->storage.m_model, this->m_index,
809 std::in_place);
810 }
811
812 using Base::begin;
813 ColumnIterator begin()
814 {
815 return ColumnIterator{this->m_index, 0, this->m_adapter};
816 }
817
818 using Base::end;
819 ColumnIterator end()
820 {
821 return ColumnIterator{this->m_index, this->m_adapter->columnCount(), this->m_adapter};
822 }
823
824 using Base::at;
825 auto at(int column)
826 {
827 Q_ASSERT(column >= 0 && column < this->m_adapter->columnCount());
828 return *ColumnIterator{this->m_index, column, this->m_adapter};
829 }
830
831 using Base::operator[];
832 auto operator[](int column)
833 {
834 return at(column);
835 }
836
837 private:
838 template <typename RHS>
839 void verifyRows(const row_type &oldRow, const RHS &newRow)
840 {
841 if constexpr (QRangeModelDetails::test_size<row_type>::value) {
842 // prevent that tables get populated with wrongly sized rows
843 Q_ASSERT_X(Impl::size(newRow) == Impl::size(oldRow),
844 "RowReference::operator=()",
845 "The new row has the wrong size!");
846 }
847
848 if constexpr (is_tree<Impl>) {
849 // we cannot hook invalid rows up to the tree hierarchy
850 Q_ASSERT_X(QRangeModelDetails::isValid(newRow),
851 "RowReference::operator=()",
852 "An invalid row can not inserted into a tree!");
853 }
854 }
855
856 template <typename R>
857 void assign(R &&other)
858 {
859 auto *impl = this->m_adapter->storage.implementation();
860 decltype(auto) oldRow = impl->rowData(this->m_index);
861
862 verifyRows(oldRow, other);
863
864 if constexpr (is_tree<Impl>) {
865 auto &protocol = impl->protocol();
866 auto *oldParent = protocol.parentRow(QRangeModelDetails::refTo(oldRow));
867
868 // the old children will be removed; we don't try to overwrite
869 // them with the new children, we replace them completely
870 if (decltype(auto) oldChildren = protocol.childRows(QRangeModelDetails::refTo(oldRow));
871 QRangeModelDetails::isValid(oldChildren)) {
872 if (int oldChildCount = this->m_adapter->model()->rowCount(this->m_index)) {
873 impl->beginRemoveRows(this->m_index, 0, oldChildCount - 1);
874 impl->deleteRemovedRows(QRangeModelDetails::refTo(oldChildren));
875 // make sure the list is empty before we emit rowsRemoved
876 QRangeModelDetails::refTo(oldChildren) = range_type{};
877 impl->endRemoveRows();
878 }
879 }
880
881 if constexpr (protocol_traits::has_deleteRow)
882 protocol.deleteRow(oldRow);
883 oldRow = std::forward<R>(other);
884 if constexpr (protocol_traits::has_setParentRow) {
885 protocol.setParentRow(QRangeModelDetails::refTo(oldRow),
886 QRangeModelDetails::pointerTo(oldParent));
887 if (decltype(auto) newChildren = protocol.childRows(QRangeModelDetails::refTo(oldRow));
888 QRangeModelDetails::isValid(newChildren)) {
889 impl->beginInsertRows(this->m_index, 0,
890 Impl::size(QRangeModelDetails::refTo(newChildren)) - 1);
891 impl->setParentRow(QRangeModelDetails::refTo(newChildren),
892 QRangeModelDetails::pointerTo(oldRow));
893 impl->endInsertRows();
894 }
895 }
896 } else {
897 oldRow = std::forward<R>(other);
898 }
899 this->m_adapter->emitDataChanged(this->m_index,
900 this->m_index.siblingAtColumn(this->m_adapter->columnCount() - 1));
901 if constexpr (Impl::itemsAreQObjects) {
902 if (this->m_adapter->model()->autoConnectPolicy() == QRangeModel::AutoConnectPolicy::Full) {
903 impl->autoConnectPropertiesInRow(oldRow, this->m_index.row(), this->m_index.parent());
904 if constexpr (is_tree<Impl>)
905 impl->autoConnectProperties(this->m_index);
906 }
907
908 }
909 }
910
911#ifndef QT_NO_DATASTREAM
912 friend inline QDataStream &operator>>(QDataStream &ds, RowReference &ref)
913 {
914 row_type value;
915 ds >> value;
916 ref = value;
917 return ds;
918 }
919#endif
920 };
921
922 template <typename Iterator, typename Adapter>
923 struct RowIteratorBase : QRangeModelDetails::ParentIndex<is_tree<Impl>>
924 {
925 using iterator_category = std::random_access_iterator_tag;
926 using difference_type = int;
927
928 RowIteratorBase() = default;
929 RowIteratorBase(const RowIteratorBase &) = default;
930 RowIteratorBase(RowIteratorBase &&) = default;
931 RowIteratorBase &operator=(const RowIteratorBase &) = default;
932 RowIteratorBase &operator=(RowIteratorBase &&) = default;
933
934 RowIteratorBase(int row, const QModelIndex &parent, Adapter *adapter)
935 : QRangeModelDetails::ParentIndex<is_tree<Impl>>{parent}
936 , m_row(row), m_adapter(adapter)
937 {}
938
939 void swap(RowIteratorBase &other) noexcept
940 {
941 qSwap(m_row, other.m_row);
942 qSwap(this->m_rootIndex, other.m_rootIndex);
943 q_ptr_swap(m_adapter, other.m_adapter);
944 }
945
946 friend Iterator &operator++(Iterator &that)
947 {
948 ++that.m_row;
949 return that;
950 }
951 friend Iterator operator++(Iterator &that, int)
952 {
953 auto copy = that;
954 ++that;
955 return copy;
956 }
957 friend Iterator operator+(const Iterator &that, difference_type n)
958 {
959 return {that.m_row + n, that.root(), that.m_adapter};
960 }
961 friend Iterator operator+(difference_type n, const Iterator &that)
962 {
963 return that + n;
964 }
965 friend Iterator &operator+=(Iterator &that, difference_type n)
966 {
967 that.m_row += n;
968 return that;
969 }
970
971 friend Iterator &operator--(Iterator &that)
972 {
973 --that.m_row;
974 return that;
975 }
976 friend Iterator operator--(Iterator &that, int)
977 {
978 auto copy = that;
979 --that;
980 return copy;
981 }
982 friend Iterator operator-(const Iterator &that, difference_type n)
983 {
984 return {that.m_row - n, that.root(), that.m_adapter};
985 }
986 friend Iterator operator-(difference_type n, const Iterator &that)
987 {
988 return that - n;
989 }
990 friend Iterator &operator-=(Iterator &that, difference_type n)
991 {
992 that.m_row -= n;
993 return that;
994 }
995
996 friend difference_type operator-(const Iterator &lhs, const Iterator &rhs)
997 {
998 return lhs.m_row - rhs.m_row;
999 }
1000
1001 protected:
1002 friend class QRangeModelAdapter;
1003 ~RowIteratorBase() = default;
1004 int m_row = -1;
1005 Adapter *m_adapter = nullptr;
1006
1007 private:
1008 friend bool comparesEqual(const Iterator &lhs, const Iterator &rhs) noexcept
1009 {
1010 return lhs.m_row == rhs.m_row && lhs.root() == rhs.root();
1011 }
1012 friend Qt::strong_ordering compareThreeWay(const Iterator &lhs, const Iterator &rhs) noexcept
1013 {
1014 if (lhs.root() == rhs.root())
1015 return qCompareThreeWay(lhs.m_row, rhs.m_row);
1016 return qCompareThreeWay(lhs.root(), rhs.root());
1017 }
1018
1019 Q_DECLARE_STRONGLY_ORDERED(Iterator)
1020
1021#ifndef QT_NO_DEBUG_STREAM
1022 friend inline QDebug operator<<(QDebug dbg, const Iterator &it)
1023 {
1024 QDebugStateSaver saver(dbg);
1025 dbg.nospace();
1026 return dbg << "RowIterator(" << it.m_row << it.root() << ")";
1027 }
1028#endif
1029 };
1030
1031public:
1032 struct ConstRowIterator : public RowIteratorBase<ConstRowIterator, const QRangeModelAdapter>
1033 {
1034 private:
1035 using Base = RowIteratorBase<ConstRowIterator, const QRangeModelAdapter>;
1036 public:
1037 using Base::Base;
1038
1039 using difference_type = typename Base::difference_type;
1040 using value_type = std::conditional_t<is_list<Impl>,
1041 const_data_type,
1042 ConstRowReference>;
1043 using reference = std::conditional_t<is_list<Impl>,
1044 const_data_type,
1045 ConstRowReference>;
1046 using pointer = std::conditional_t<is_list<Impl>,
1047 QRangeModelDetails::data_pointer_t<const_data_type>,
1048 ConstRowReference>;
1049
1050 ConstRowIterator(const ConstRowIterator &other) = default;
1051 ConstRowIterator(ConstRowIterator &&other) = default;
1052 ConstRowIterator &operator=(const ConstRowIterator &other) = default;
1053 ConstRowIterator &operator=(ConstRowIterator &&other) = default;
1054 ~ConstRowIterator() = default;
1055
1056 pointer operator->() const
1057 {
1058 return pointer{operator*()};
1059 }
1060
1061 reference operator*() const
1062 {
1063 if constexpr (is_list<Impl>) {
1064 return this->m_adapter->at(this->m_row);
1065 } else {
1066 const QModelIndex index = this->m_adapter->model()->index(this->m_row, 0,
1067 this->root());
1068 return ConstRowReference{index, this->m_adapter};
1069 }
1070 }
1071
1072 reference operator[](difference_type n) const
1073 {
1074 return *(*this + n);
1075 }
1076 };
1077
1078 struct RowIterator : public RowIteratorBase<RowIterator, QRangeModelAdapter>
1079 {
1080 private:
1081 using Base = RowIteratorBase<RowIterator, QRangeModelAdapter>;
1082 public:
1083 using Base::Base;
1084
1085 using difference_type = typename Base::difference_type;
1086 // The value_type must not be the proxy type returned when
1087 // dereferencing the iterator, otherwise algorithms that make copies of
1088 // values (e.g. std::ranges::max) would write into the model through
1089 // the proxy.
1090 using value_type = std::conditional_t<is_list<Impl>,
1091 data_type,
1092 std::remove_cv_t<row_type>>;
1093 using reference = std::conditional_t<is_list<Impl>,
1094 DataReference,
1095 RowReference>;
1096 using pointer = std::conditional_t<is_list<Impl>,
1097 DataReference,
1098 RowReference>;
1099
1100 RowIterator(const RowIterator &other) = default;
1101 RowIterator(RowIterator &&other) = default;
1102 RowIterator &operator=(const RowIterator &other) = default;
1103 RowIterator &operator=(RowIterator &&other) = default;
1104 ~RowIterator() = default;
1105
1106 operator ConstRowIterator() const
1107 {
1108 return ConstRowIterator{this->m_row, this->root(), this->m_adapter};
1109 }
1110
1111 pointer operator->() const
1112 {
1113 return pointer{operator*()};
1114 }
1115
1116 reference operator*() const
1117 {
1118 const QModelIndex index = this->m_adapter->model()->index(this->m_row, 0, this->root());
1119 if constexpr (is_list<Impl>) {
1120 return reference{index};
1121 } else {
1122 return reference{index, this->m_adapter};
1123 }
1124 }
1125
1126 reference operator[](difference_type n) const
1127 {
1128 return *(*this + n);
1129 }
1130 };
1131
1132 using const_iterator = ConstRowIterator;
1133 using iterator = RowIterator;
1134 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
1135 using reverse_iterator = std::reverse_iterator<iterator>;
1136#ifdef Q_QDOC
1137 using value_type = typename Range::value_type;
1138 using reference = RowReference;
1139 using const_reference = ConstRowReference;
1140#else
1141 using value_type = std::remove_cv_t<row_type>;
1142 using reference = typename iterator::reference;
1143 using const_reference = typename const_iterator::reference;
1144#endif
1145 using size_type = int;
1146 using difference_type = int;
1147
1148 template <typename R,
1149 typename P,
1150 if_compatible_model_params<R, P> = true>
1151 explicit QRangeModelAdapter(R &&range, P &&protocol)
1152 : QRangeModelAdapter(new Model(QRangeModelDetails::forwardOrConvert<Range>(std::forward<R>(range)),
1153 QRangeModelDetails::forwardOrConvert<Protocol>(std::forward<P>(protocol))))
1154 {}
1155
1156 template <typename R,
1157 typename P = void, // to enable the ctr for void protocols only
1158 if_compatible_model_params<R, P> = true,
1159 unless_adapter<R> = true>
1160 explicit QRangeModelAdapter(R &&range)
1161 : QRangeModelAdapter(new Model(QRangeModelDetails::forwardOrConvert<Range>(std::forward<R>(range))))
1162 {}
1163
1164 // compiler-generated copy/move SMF are fine!
1165
1166 Model *model() const
1167 {
1168 return storage.m_model.get();
1169 }
1170
1171 const range_type &range() const
1172 {
1173 return QRangeModelDetails::refTo(storage.implementation()->childRange(storage.root()));
1174 }
1175
1176 template <typename NewRange = range_type, if_assignable_range<NewRange> = true>
1177 void assign(NewRange &&newRange)
1178 {
1179 assignImpl(qsizetype(Impl::size(QRangeModelDetails::refTo(newRange))),
1180 [&newRange](auto &oldRange) {
1181 oldRange = std::forward<NewRange>(newRange);
1182 });
1183 }
1184
1185 template <typename NewRange = range_type, if_assignable_range<NewRange> = true,
1186 unless_adapter<NewRange> = true>
1187 QRangeModelAdapter &operator=(NewRange &&newRange)
1188 {
1189 assign(std::forward<NewRange>(newRange));
1190 return *this;
1191 }
1192
1193 template <typename Row, if_assignable_range<std::initializer_list<Row>> = true>
1194 void assign(std::initializer_list<Row> newRange)
1195 {
1196 assignImpl(newRange.size(), [&newRange](auto &oldRange) {
1197 oldRange = newRange;
1198 });
1199 }
1200
1201 template <typename Row, if_assignable_range<std::initializer_list<Row>> = true>
1202 QRangeModelAdapter &operator=(std::initializer_list<Row> newRange)
1203 {
1204 assign(newRange);
1205 return *this;
1206 }
1207
1208 template <typename I = Impl, if_canAssignCopies<I> = true>
1209 void assign(size_type count, const value_type &value)
1210 {
1211 Q_PRE(count >= 0);
1212 assignImpl(size_t(count), [count, &value](auto &oldRange) {
1213 if constexpr (QRangeModelDetails::has_assign_count<range_type>::value) {
1214 oldRange.assign(count, value);
1215 } else {
1216 oldRange.erase(QRangeModelDetails::adl_begin(oldRange),
1217 QRangeModelDetails::adl_end(oldRange));
1218 oldRange.insert(QRangeModelDetails::adl_end(oldRange), count, value);
1219 }
1220 });
1221 }
1222
1223 template <typename InputIterator, typename Sentinel, typename I = Impl, if_writable<I> = true,
1224 if_compatible_row_iterator<InputIterator> = true>
1225 void assign(InputIterator first, Sentinel last)
1226 {
1227 assignImpl(size_t(std::distance(first, last)), [first, last](auto &oldRange) {
1228 oldRange.assign(first, last);
1229 });
1230 }
1231
1232 template <typename I = Impl, if_canSort<I> = true>
1233 void sort(int column = 0, Qt::SortOrder order = Qt::AscendingOrder)
1234 {
1235 storage->sort(column, order);
1236 }
1237
1238 // iterator API
1239 ConstRowIterator cbegin() const
1240 {
1241 return ConstRowIterator{ 0, storage.root(), this };
1242 }
1243 ConstRowIterator begin() const { return cbegin(); }
1244
1245 ConstRowIterator cend() const
1246 {
1247 return ConstRowIterator{ rowCount(), storage.root(), this };
1248 }
1249 ConstRowIterator end() const { return cend(); }
1250
1251 template <typename I = Impl, if_writable<I> = true>
1252 RowIterator begin()
1253 {
1254 return RowIterator{ 0, storage.root(), this };
1255 }
1256
1257 template <typename I = Impl, if_writable<I> = true>
1258 RowIterator end()
1259 {
1260 return RowIterator{ rowCount(), storage.root(), this };
1261 }
1262
1263 const_reverse_iterator crbegin() const { return const_reverse_iterator(cend()); }
1264 const_reverse_iterator rbegin() const { return crbegin(); }
1265 const_reverse_iterator crend() const { return const_reverse_iterator(cbegin()); }
1266 const_reverse_iterator rend() const { return crend(); }
1267
1268 template <typename I = Impl, if_writable<I> = true>
1269 reverse_iterator rbegin() { return reverse_iterator(end()); }
1270 template <typename I = Impl, if_writable<I> = true>
1271 reverse_iterator rend() { return reverse_iterator(begin()); }
1272
1273 int size() const
1274 {
1275 return rowCount();
1276 }
1277
1278 bool isEmpty() const
1279 {
1280 return rowCount() == 0;
1281 }
1282
1283 bool empty() const
1284 {
1285 return isEmpty();
1286 }
1287
1288 decltype(auto) front() const
1289 {
1290 Q_PRE(!empty());
1291 return at(0);
1292 }
1293
1294 template <typename I = Impl, if_writable<I> = true>
1295 auto front()
1296 {
1297 Q_PRE(!empty());
1298 return at(0);
1299 }
1300
1301 decltype(auto) back() const
1302 {
1303 Q_PRE(!empty());
1304 return at(size() - 1);
1305 }
1306
1307 template <typename I = Impl, if_writable<I> = true>
1308 auto back()
1309 {
1310 Q_PRE(!empty());
1311 return at(size() - 1);
1312 }
1313
1314 template <typename I = Impl, if_list<I> = true>
1315 QModelIndex index(int row) const
1316 {
1317 return storage->index(row, 0, storage.root());
1318 }
1319
1320 template <typename I = Impl, unless_list<I> = true>
1321 QModelIndex index(int row, int column) const
1322 {
1323 return storage->index(row, column, storage.root());
1324 }
1325
1326 template <typename I = Impl, if_tree<I> = true>
1327 QModelIndex index(QSpan<const int> path, int col) const
1328 {
1329 QModelIndex result = storage.root();
1330 auto count = path.size();
1331 for (const int r : path) {
1332 if (--count)
1333 result = storage->index(r, 0, result);
1334 else
1335 result = storage->index(r, col, result);
1336 }
1337 return result;
1338 }
1339
1340 int columnCount() const
1341 {
1342 // all rows and tree branches have the same column count
1343 return storage->columnCount({});
1344 }
1345
1346 int rowCount() const
1347 {
1348 return storage->rowCount(storage.root());
1349 }
1350
1351 template <typename I = Impl, if_tree<I> = true>
1352 int rowCount(int row) const
1353 {
1354 return rowCount(index(row, 0));
1355 }
1356
1357 template <typename I = Impl, if_tree<I> = true>
1358 int rowCount(QSpan<const int> path) const
1359 {
1360 return rowCount(index(path, 0));
1361 }
1362
1363 template <typename I = Impl, if_tree<I> = true>
1364 int rowCount(const QModelIndex &index) const
1365 {
1366 return storage->rowCount(index);
1367 }
1368
1369 template <typename I = Impl, if_tree<I> = true>
1370 constexpr bool hasChildren(int row) const
1371 {
1372 return hasChildren(index(row, 0));
1373 }
1374
1375 template <typename I = Impl, if_tree<I> = true>
1376 constexpr bool hasChildren(QSpan<const int> path) const
1377 {
1378 return hasChildren(index(path, 0));
1379 }
1380
1381 template <typename I = Impl, if_tree<I> = true>
1382 constexpr bool hasChildren(const QModelIndex &index) const
1383 {
1384 return storage.m_model->hasChildren(index);
1385 }
1386
1387 template <typename I = Impl, if_list<I> = true>
1388 QVariant data(int row) const
1389 {
1390 return data(index(row));
1391 }
1392
1393 template <typename I = Impl, if_list<I> = true>
1394 QVariant data(int row, int role) const
1395 {
1396 return data(index(row), role);
1397 }
1398
1399 template <typename I = Impl, if_list<I> = true, if_writable<I> = true>
1400 bool setData(int row, const QVariant &value, int role = Qt::EditRole)
1401 {
1402 return setData(index(row), value, role);
1403 }
1404
1405 template <typename I = Impl, unless_list<I> = true>
1406 QVariant data(int row, int column) const
1407 {
1408 return data(index(row, column));
1409 }
1410
1411 template <typename I = Impl, unless_list<I> = true>
1412 QVariant data(int row, int column, int role) const
1413 {
1414 return data(index(row, column), role);
1415 }
1416
1417 template <typename I = Impl, unless_list<I> = true, if_writable<I> = true>
1418 bool setData(int row, int column, const QVariant &value, int role = Qt::EditRole)
1419 {
1420 return setData(index(row, column), value, role);
1421 }
1422
1423 template <typename I = Impl, if_tree<I> = true>
1424 QVariant data(QSpan<const int> path, int column) const
1425 {
1426 return data(index(path, column));
1427 }
1428
1429 template <typename I = Impl, if_tree<I> = true>
1430 QVariant data(QSpan<const int> path, int column, int role) const
1431 {
1432 return data(index(path, column), role);
1433 }
1434
1435 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1436 bool setData(QSpan<const int> path, int column, const QVariant &value, int role = Qt::EditRole)
1437 {
1438 return setData(index(path, column), value, role);
1439 }
1440
1441 QVariant data(const QModelIndex &index) const
1442 {
1443 return QRangeModelDetails::dataAtIndex<QVariant>(index);
1444 }
1445
1446 QVariant data(const QModelIndex &index, int role) const
1447 {
1448 return QRangeModelDetails::dataAtIndex<QVariant>(index, role);
1449 }
1450
1451 template <typename I = Impl, if_writable<I> = true>
1452 bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)
1453 {
1454 return storage->setData(index, value, role);
1455 }
1456
1457 // at/operator[int] for list: returns value at row
1458 // if multi-role value: return the entire object
1459 template <typename I= Impl, if_list<I> = true>
1460 const_data_type at(int row) const
1461 {
1462 return QRangeModelDetails::dataAtIndex<data_type>(index(row));
1463 }
1464 template <typename I = Impl, if_list<I> = true>
1465 const_data_type operator[](int row) const { return at(row); }
1466
1467 template <typename I= Impl, if_list<I> = true, if_writable<I> = true>
1468 auto at(int row) {
1469 const QModelIndex idx = this->index(row);
1470 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::at", "Index at row is invalid");
1471 return DataReference{idx};
1472 }
1473 template <typename I = Impl, if_list<I> = true, if_writable<I> = true>
1474 auto operator[](int row) {
1475 const QModelIndex idx = this->index(row);
1476 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::operator[]", "Index at row is invalid");
1477 return DataReference{idx};
1478 }
1479
1480 // at/operator[int] for table or tree: a reference or view of the row
1481 template <typename I = Impl, unless_list<I> = true>
1482 decltype(auto) at(int row) const
1483 {
1484 return ConstRowReference{index(row, 0), this}.get();
1485 }
1486 template <typename I = Impl, unless_list<I> = true>
1487 decltype(auto) operator[](int row) const { return at(row); }
1488
1489 template <typename I = Impl, if_table<I> = true, if_writable<I> = true>
1490 auto at(int row)
1491 {
1492 return RowReference{index(row, 0), this};
1493 }
1494 template <typename I = Impl, if_table<I> = true, if_writable<I> = true>
1495 auto operator[](int row) { return at(row); }
1496
1497 // at/operator[int, int] for table: returns value at row/column
1498 template <typename I = Impl, unless_list<I> = true>
1499 const_data_type at(int row, int column) const
1500 {
1501 return QRangeModelDetails::dataAtIndex<data_type>(index(row, column));
1502 }
1503
1504#ifdef __cpp_multidimensional_subscript
1505 template <typename I = Impl, unless_list<I> = true>
1506 const_data_type operator[](int row, int column) const { return at(row, column); }
1507#endif
1508
1509 template <typename I = Impl, unless_list<I> = true, if_writable<I> = true>
1510 auto at(int row, int column)
1511 {
1512 const QModelIndex idx = this->index(row, column);
1513 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::at", "Index at cell is invalid");
1514 return DataReference{idx};
1515 }
1516#ifdef __cpp_multidimensional_subscript
1517 template <typename I = Impl, unless_list<I> = true, if_writable<I> = true>
1518 auto operator[](int row, int column)
1519 {
1520 const QModelIndex idx = this->index(row, column);
1521 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::operator[]", "Index at cell is invalid");
1522 return DataReference{idx};
1523 }
1524#endif
1525
1526 // at/operator[int] for tree: return a wrapper that maintains reference to
1527 // parent.
1528 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1529 auto at(int row)
1530 {
1531 return RowReference{index(row, 0), this};
1532 }
1533 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1534 auto operator[](int row) { return at(row); }
1535
1536 // at/operator[path] for tree: a reference or view of the row
1537 template <typename I = Impl, if_tree<I> = true>
1538 decltype(auto) at(QSpan<const int> path) const
1539 {
1540 return ConstRowReference{index(path, 0), this}.get();
1541 }
1542 template <typename I = Impl, if_tree<I> = true>
1543 decltype(auto) operator[](QSpan<const int> path) const { return at(path); }
1544
1545 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1546 auto at(QSpan<const int> path)
1547 {
1548 return RowReference{index(path, 0), this};
1549 }
1550 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1551 auto operator[](QSpan<const int> path) { return at(path); }
1552
1553 // at/operator[path, column] for tree: return value
1554 template <typename I = Impl, if_tree<I> = true>
1555 const_data_type at(QSpan<const int> path, int column) const
1556 {
1557 Q_PRE(path.size());
1558 return QRangeModelDetails::dataAtIndex<data_type>(index(path, column));
1559 }
1560
1561#ifdef __cpp_multidimensional_subscript
1562 template <typename I = Impl, if_tree<I> = true>
1563 const_data_type operator[](QSpan<const int> path, int column) const { return at(path, column); }
1564#endif
1565
1566 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1567 auto at(QSpan<const int> path, int column)
1568 {
1569 Q_PRE(path.size());
1570 const QModelIndex idx = this->index(path, column);
1571 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::at", "Index at path is invalid");
1572 return DataReference{idx};
1573 }
1574#ifdef __cpp_multidimensional_subscript
1575 template <typename I = Impl, if_tree<I> = true, if_writable<I> = true>
1576 auto operator[](QSpan<const int> path, int column)
1577 {
1578 const QModelIndex idx = this->index(path, column);
1579 Q_ASSERT_X(idx.isValid(), "QRangeModelAdapter::operator[]", "Index at path is invalid");
1580 return DataReference{idx};
1581 }
1582#endif
1583
1584 const_data_type at(const QModelIndex &index) const
1585 {
1586 Q_ASSERT_X(index.isValid(), "QRangeModelAdapter::at", "Index is invalid");
1587 return QRangeModelDetails::dataAtIndex<data_type>(index);
1588 }
1589
1590 template <typename I = Impl, if_writable<I> = true>
1591 auto at(const QModelIndex &index)
1592 {
1593 Q_ASSERT_X(index.isValid(), "QRangeModelAdapter::at", "Index is invalid");
1594 return DataReference{index};
1595 }
1596
1597 template <typename I = Impl, if_canInsertRows<I> = true>
1598 bool insertRow(int before)
1599 {
1600 return storage.m_model->insertRow(before);
1601 }
1602
1603 template <typename I = Impl, if_canInsertRows<I> = true, if_tree<I> = true>
1604 bool insertRow(QSpan<const int> before)
1605 {
1606 Q_PRE(before.size());
1607 return insertRow(before.back(), this->index(before.first(before.size() - 1), 0));
1608 }
1609
1610 template <typename I = Impl, if_canInsertRows<I> = true, if_tree<I> = true>
1611 bool insertRow(int before, const QModelIndex &parent)
1612 {
1613 return storage.m_model->insertRow(before, parent);
1614 }
1615
1616 template <typename D = row_type, typename I = Impl,
1617 if_canInsertRows<I> = true, if_compatible_row<D> = true>
1618 bool insertRow(int before, D &&data)
1619 {
1620 return insertRowImpl(before, storage.root(), std::forward<D>(data));
1621 }
1622
1623 template <typename D = row_type, typename I = Impl,
1624 if_canInsertRows<I> = true, if_compatible_row<D> = true, if_tree<I> = true>
1625 bool insertRow(QSpan<const int> before, D &&data)
1626 {
1627 return insertRow(before.back(), this->index(before.sliced(0, before.size() - 1), 0),
1628 std::forward<D>(data));
1629 }
1630
1631 template <typename D = row_type, typename I = Impl,
1632 if_canInsertRows<I> = true, if_compatible_row<D> = true, if_tree<I> = true>
1633 bool insertRow(int before, const QModelIndex &parent, D &&data)
1634 {
1635 return insertRowImpl(before, parent, std::forward<D>(data));
1636 }
1637
1638 template <typename C, typename I = Impl,
1639 if_canInsertRows<I> = true, if_compatible_row_range<C> = true>
1640 bool insertRows(int before, C &&data)
1641 {
1642 return insertRowsImpl(before, storage.root(), std::forward<C>(data));
1643 }
1644
1645 template <typename C, typename I = Impl,
1646 if_canInsertRows<I> = true, if_compatible_row_range<C> = true, if_tree<I> = true>
1647 bool insertRows(QSpan<const int> before, C &&data)
1648 {
1649 return insertRows(before.back(), this->index(before.sliced(0, before.size() - 1), 0),
1650 std::forward<C>(data));
1651 }
1652
1653 template <typename C, typename I = Impl,
1654 if_canInsertRows<I> = true, if_compatible_row_range<C> = true, if_tree<I> = true>
1655 bool insertRows(int before, const QModelIndex &parent, C &&data)
1656 {
1657 return insertRowsImpl(before, parent, std::forward<C>(data));
1658 }
1659
1660 template <typename I = Impl, if_canInsertRows<I> = true>
1661 iterator insert(const_iterator pos, const value_type &value)
1662 {
1663 return insertAt(pos, 1, [this, &value](int row) {
1664 return insertRowImpl(row, storage.root(), value);
1665 });
1666 }
1667
1668 template <typename I = Impl, if_canInsertRows<I> = true>
1669 iterator insert(const_iterator pos, value_type &&value)
1670 {
1671 return insertAt(pos, 1, [this, &value](int row) {
1672 return insertRowImpl(row, storage.root(), std::move(value));
1673 });
1674 }
1675
1676 template <typename I = Impl, if_canInsertCopies<I> = true>
1677 iterator insert(const_iterator pos, size_type count, const value_type &value)
1678 {
1679 return insertAt(pos, count, [this, count, &value](int row) {
1680 return insertCopiesImpl(row, count, storage.root(), value);
1681 });
1682 }
1683
1684 template <typename InputIterator, typename I = Impl, if_canInsertRows<I> = true,
1685 if_compatible_row_iterator<InputIterator> = true>
1686 iterator insert(const_iterator pos, InputIterator first, InputIterator last)
1687 {
1688 const QRangeModelDetails::IteratorRange<InputIterator> range{first, last};
1689 return insertAt(pos, q26::saturating_cast<int>(range.size()), [this, &range](int row) {
1690 return insertRowsImpl(row, storage.root(), range);
1691 });
1692 }
1693
1694 template <typename I = Impl, if_canInsertRows<I> = true>
1695 iterator insert(const_iterator pos, std::initializer_list<value_type> values)
1696 {
1697 return insertAt(pos, int(values.size()), [this, &values](int row) {
1698 return insertRowsImpl(row, storage.root(), values);
1699 });
1700 }
1701
1702 template <typename ...Args, typename I = Impl, if_canInsertRows<I> = true,
1703 if_emplaceable<Args...> = true>
1704 iterator emplace(const_iterator pos, Args &&...args)
1705 {
1706 return insertAt(pos, 1, [this, &args...](int row) {
1707 if constexpr (sizeof...(Args) == 0)
1708 return storage->insertRows(row, 1, storage.root());
1709 else
1710 return insertRowImpl(row, storage.root(), std::forward<Args>(args)...);
1711 });
1712 }
1713
1714 template <typename I = Impl, if_canInsertRows<I> = true>
1715 void push_back(const value_type &value)
1716 {
1717 insert(cend(), value);
1718 }
1719
1720 template <typename I = Impl, if_canInsertRows<I> = true>
1721 void push_back(value_type &&value)
1722 {
1723 insert(cend(), std::move(value));
1724 }
1725
1726 template <typename I = Impl, if_canInsertRows<I> = true>
1727 void push_front(const value_type &value)
1728 {
1729 insert(cbegin(), value);
1730 }
1731
1732 template <typename I = Impl, if_canInsertRows<I> = true>
1733 void push_front(value_type &&value)
1734 {
1735 insert(cbegin(), std::move(value));
1736 }
1737
1738 template <typename ...Args, typename I = Impl, if_canInsertRows<I> = true,
1739 if_emplaceable<Args...> = true>
1740 reference emplace_back(Args &&...args)
1741 {
1742 return *emplace(cend(), std::forward<Args>(args)...);
1743 }
1744
1745 template <typename ...Args, typename I = Impl, if_canInsertRows<I> = true,
1746 if_emplaceable<Args...> = true>
1747 reference emplace_front(Args &&...args)
1748 {
1749 return *emplace(cbegin(), std::forward<Args>(args)...);
1750 }
1751
1752 template <typename I = Impl, if_canRemoveRows<I> = true>
1753 iterator erase(const_iterator pos)
1754 {
1755 Q_PRE(pos != cend());
1756 return erase(pos, std::next(pos));
1757 }
1758
1759 template <typename I = Impl, if_canRemoveRows<I> = true>
1760 iterator erase(const_iterator first, const_iterator last)
1761 {
1762 const int row = rowOf(first);
1763 const int count = rowOf(last) - row;
1764 Q_PRE(count >= 0);
1765 if (count > 0 && !storage->removeRows(row, count, storage.root()))
1766 return end();
1767 return iterator{row, storage.root(), this};
1768 }
1769
1770 template <typename I = Impl, if_canRemoveRows<I> = true>
1771 void pop_back()
1772 {
1773 Q_PRE(!empty());
1774 erase(cend() - 1);
1775 }
1776
1777 template <typename I = Impl, if_canRemoveRows<I> = true>
1778 void pop_front()
1779 {
1780 Q_PRE(!empty());
1781 erase(cbegin());
1782 }
1783
1784 template <typename I = Impl, if_canRemoveRows<I> = true>
1785 void clear()
1786 {
1787 erase(cbegin(), cend());
1788 }
1789
1790 template <typename I = Impl, if_canInsertRows<I> = true, if_canRemoveRows<I> = true>
1791 void resize(size_type newSize)
1792 {
1793 Q_PRE(newSize >= 0);
1794 const int oldSize = size();
1795 if (newSize < oldSize)
1796 erase(cbegin() + newSize, cend());
1797 else if (newSize > oldSize)
1798 storage->insertRows(oldSize, newSize - oldSize, storage.root());
1799 }
1800
1801 template <typename I = Impl, if_canInsertCopies<I> = true, if_canRemoveRows<I> = true>
1802 void resize(size_type newSize, const value_type &value)
1803 {
1804 Q_PRE(newSize >= 0);
1805 const int oldSize = size();
1806 if (newSize < oldSize)
1807 erase(cbegin() + newSize, cend());
1808 else if (newSize > oldSize)
1809 insert(cend(), newSize - oldSize, value);
1810 }
1811
1812 template <typename Predicate, typename I = Impl, if_canRemoveRows<I> = true>
1813 size_type removeIf(Predicate pred)
1814 {
1815 // The row of a tree might not have a range of children at all.
1816 if (empty())
1817 return 0;
1818
1819 // Evaluate the predicate once for each row, in order, before modifying
1820 // the range.
1821 std::vector<bool> matches;
1822 matches.reserve(size_t(size()));
1823 const range_type &rows = range();
1824 for (auto it = QRangeModelDetails::adl_begin(rows);
1825 it != QRangeModelDetails::adl_end(rows); ++it) {
1826 matches.push_back(bool(pred(*it)));
1827 }
1828
1829 // Remove each contiguous run of matching rows with a single call,
1830 // starting at the end so that the indices of the remaining runs stay
1831 // valid.
1832 size_type removed = 0;
1833 int last = int(matches.size());
1834 while (last > 0) {
1835 while (last > 0 && !matches[last - 1])
1836 --last;
1837 int first = last;
1838 while (first > 0 && matches[first - 1])
1839 --first;
1840 if (first < last) {
1841 if (!storage->removeRows(first, last - first, storage.root()))
1842 break;
1843 removed += last - first;
1844 }
1845 last = first;
1846 }
1847 return removed;
1848 }
1849
1850 template <typename AT = value_type, typename I = Impl, if_canRemoveRows<I> = true>
1851 size_type removeAll(const AT &value)
1852 {
1853 return removeIf([&value](const auto &row) { return row == value; });
1854 }
1855
1856 template <typename I = Impl, if_canRemoveRows<I> = true>
1857 bool removeRow(int row)
1858 {
1859 return removeRows(row, 1);
1860 }
1861
1862 template <typename I = Impl, if_canRemoveRows<I> = true, if_tree<I> = true>
1863 bool removeRow(QSpan<const int> path)
1864 {
1865 return removeRows(path, 1);
1866 }
1867
1868 template <typename I = Impl, if_canRemoveRows<I> = true, if_tree<I> = true>
1869 bool removeRow(int row, const QModelIndex &parent)
1870 {
1871 return removeRows(row, 1, parent);
1872 }
1873
1874 template <typename I = Impl, if_canRemoveRows<I> = true>
1875 bool removeRows(int row, int count)
1876 {
1877 return storage->removeRows(row, count, storage.root());
1878 }
1879
1880 template <typename I = Impl, if_canRemoveRows<I> = true, if_tree<I> = true>
1881 bool removeRows(QSpan<const int> path, int count)
1882 {
1883 return removeRows(path.back(), count, this->index(path.first(path.size() - 1), 0));
1884 }
1885
1886 template <typename I = Impl, if_canRemoveRows<I> = true, if_tree<I> = true>
1887 bool removeRows(int row, int count, const QModelIndex &parent)
1888 {
1889 return storage->removeRows(row, count, parent);
1890 }
1891
1892 template <typename F = range_features, if_canMoveItems<F> = true>
1893 bool moveRow(int source, int destination)
1894 {
1895 return moveRows(source, 1, destination);
1896 }
1897
1898 template <typename F = range_features, if_canMoveItems<F> = true>
1899 bool moveRows(int source, int count, int destination)
1900 {
1901 return storage->moveRows(storage.root(), source, count, storage.root(), destination);
1902 }
1903
1904 template <typename I = Impl, typename F = range_features,
1905 if_canMoveItems<F> = true, if_tree<I> = true>
1906 bool moveRow(QSpan<const int> source, QSpan<const int> destination)
1907 {
1908 return moveRows(source, 1, destination);
1909 }
1910
1911 template <typename I = Impl, typename F = range_features,
1912 if_canMoveItems<F> = true, if_tree<I> = true>
1913 bool moveRow(const QModelIndex &sourceParent, int sourceRow,
1914 const QModelIndex &destinationParent, int destinationChild)
1915 {
1916 return moveRows(sourceParent, sourceRow, 1, destinationParent, destinationChild);
1917 }
1918
1919 template <typename I = Impl, typename F = range_features,
1920 if_canMoveItems<F> = true, if_tree<I> = true>
1921 bool moveRows(QSpan<const int> source, int count, QSpan<const int> destination)
1922 {
1923 return moveRows(this->index(source.first(source.size() - 1), 0),
1924 source.back(),
1925 count,
1926 this->index(destination.first(destination.size() - 1), 0),
1927 destination.back());
1928 }
1929
1930 template <typename I = Impl, typename F = range_features,
1931 if_canMoveItems<F> = true, if_tree<I> = true>
1932 bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count,
1933 const QModelIndex &destinationParent, int destinationChild)
1934 {
1935 return storage->moveRows(sourceParent, sourceRow, count,
1936 destinationParent, destinationChild);
1937 }
1938
1939 template <typename I = Impl, if_canInsertColumns<I> = true>
1940 bool insertColumn(int before)
1941 {
1942 return storage.m_model->insertColumn(before);
1943 }
1944
1945 template <typename D, typename I = Impl,
1946 if_canInsertColumns<I> = true, if_compatible_column_data<D> = true>
1947 bool insertColumn(int before, D &&data)
1948 {
1949 return insertColumnImpl(before, storage.root(), std::forward<D>(data));
1950 }
1951
1952 template <typename C, typename I = Impl,
1953 if_canInsertColumns<I> = true, if_compatible_column_range<C> = true>
1954 bool insertColumns(int before, C &&data)
1955 {
1956 return insertColumnsImpl(before, storage.root(), std::forward<C>(data));
1957 }
1958
1959 template <typename I = Impl, if_canRemoveColumns<I> = true>
1960 bool removeColumn(int column)
1961 {
1962 return storage.m_model->removeColumn(column);
1963 }
1964
1965 template <typename I = Impl, if_canRemoveColumns<I> = true>
1966 bool removeColumns(int column, int count)
1967 {
1968 return storage->removeColumns(column, count, {});
1969 }
1970
1971 template <typename F = row_features, if_canMoveItems<F> = true>
1972 bool moveColumn(int from, int to)
1973 {
1974 return moveColumns(from, 1, to);
1975 }
1976
1977 template <typename F = row_features, if_canMoveItems<F> = true>
1978 bool moveColumns(int from, int count, int to)
1979 {
1980 return storage->moveColumns(storage.root(), from, count, storage.root(), to);
1981 }
1982
1983 template <typename I = Impl, typename F = row_features,
1984 if_canMoveItems<F> = true, if_tree<I> = true>
1985 bool moveColumn(QSpan<const int> source, int to)
1986 {
1987 const QModelIndex parent = this->index(source.first(source.size() - 1), 0);
1988 return storage->moveColumns(parent, source.back(), 1, parent, to);
1989 }
1990
1991 template <typename I = Impl, typename F = row_features,
1992 if_canMoveItems<F> = true, if_tree<I> = true>
1993 bool moveColumns(QSpan<const int> source, int count, int destination)
1994 {
1995 const QModelIndex parent = this->index(source.first(source.size() - 1), 0);
1996 return storage->moveColumns(parent, source.back(), count, parent, destination);
1997 }
1998
1999private:
2000 template <typename AT = value_type, typename I = Impl, if_canRemoveRows<I> = true>
2001 friend size_type erase(QRangeModelAdapter &adapter, const AT &value)
2002 {
2003 return adapter.removeAll(value);
2004 }
2005
2006 template <typename Predicate, typename I = Impl, if_canRemoveRows<I> = true>
2007 friend size_type erase_if(QRangeModelAdapter &adapter, Predicate pred)
2008 {
2009 return adapter.removeIf(std::move(pred));
2010 }
2011
2012 friend inline
2013 bool comparesEqual(const QRangeModelAdapter &lhs, const QRangeModelAdapter &rhs) noexcept
2014 {
2015 return lhs.storage.m_model == rhs.storage.m_model;
2016 }
2017 Q_DECLARE_EQUALITY_COMPARABLE(QRangeModelAdapter)
2018
2019 friend inline
2020 bool comparesEqual(const QRangeModelAdapter &lhs, const range_type &rhs)
2021 {
2022 return lhs.range() == rhs;
2023 }
2024 Q_DECLARE_EQUALITY_COMPARABLE_NON_NOEXCEPT(QRangeModelAdapter, range_type)
2025
2026
2027 void emitDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
2028 {
2029 Q_EMIT storage.implementation()->dataChanged(topLeft, bottomRight, {});
2030 }
2031
2032 void beginAssignImpl(Impl *impl, range_type *oldRange, int newLastRow)
2033 {
2034 const QModelIndex root = storage.root();
2035 const qsizetype oldLastRow = qsizetype(Impl::size(oldRange)) - 1;
2036
2037 if (!root.isValid()) {
2038 impl->beginResetModel();
2039 impl->deleteOwnedRows();
2040 } else if constexpr (is_tree<Impl>) {
2041 if (oldLastRow >= 0) {
2042 impl->beginRemoveRows(root, 0, model()->rowCount(root) - 1);
2043 impl->deleteRemovedRows(QRangeModelDetails::refTo(oldRange));
2044 impl->endRemoveRows();
2045 }
2046 if (newLastRow >= 0)
2047 impl->beginInsertRows(root, 0, newLastRow);
2048 } else {
2049 Q_ASSERT_X(false, "QRangeModelAdapter::assign",
2050 "Internal error: The root index in a table or list must be invalid.");
2051 }
2052 }
2053
2054 void endAssignImpl(Impl *impl, int newLastRow)
2055 {
2056 const QModelIndex root = storage.root();
2057 if (!root.isValid()) {
2058 if constexpr (is_tree<Impl> && protocol_traits::has_setParentRow) {
2059 // Rows that were copied or moved into the range still refer
2060 // to their old parent, and their children to the old rows.
2061 impl->setParentRow(QRangeModelDetails::refTo(impl->childRange(root)), nullptr);
2062 }
2063 impl->endResetModel();
2064 } else if constexpr (is_tree<Impl>) {
2065 if (newLastRow >= 0) {
2066 Q_ASSERT(model()->hasChildren(root));
2067 // if it was moved, then newRange is now likely to be empty. Get
2068 // the inserted row.
2069 impl->setParentRow(QRangeModelDetails::refTo(impl->childRange(root)),
2070 QRangeModelDetails::pointerTo(impl->rowData(root)));
2071 impl->endInsertRows();
2072 }
2073 }
2074 }
2075
2076 template <typename Assigner>
2077 void assignImpl(std::size_t newSize, Assigner &&assigner)
2078 {
2079 const auto sz = q26::saturating_cast<int>(newSize);
2080 Q_ASSERT_X(q20::cmp_equal(sz, newSize),
2081 "QRangeModelAdapter::assign", "New range is too large");
2082 const int newLastRow = sz - 1;
2083
2084 auto *impl = storage.implementation();
2085 auto *oldRange = impl->childRange(storage.root());
2086 beginAssignImpl(impl, oldRange, newLastRow);
2087 assigner(QRangeModelDetails::refTo(oldRange));
2088 endAssignImpl(impl, newLastRow);
2089
2090 if constexpr (Impl::itemsAreQObjects) {
2091 if (model()->autoConnectPolicy() == QRangeModel::AutoConnectPolicy::Full) {
2092 const auto begin = QRangeModelDetails::begin(QRangeModelDetails::refTo(oldRange));
2093 const auto end = QRangeModelDetails::end(QRangeModelDetails::refTo(oldRange));
2094 int rowIndex = 0;
2095 for (auto it = begin; it != end; ++it, ++rowIndex)
2096 impl->autoConnectPropertiesInRow(*it, rowIndex, storage.root());
2097 }
2098 }
2099 }
2100
2101
2102 template <typename P, typename Row>
2103 static auto setParentRow(P &protocol, Row &newRow, row_ptr parentRow)
2104 -> decltype(protocol.setParentRow(newRow, parentRow))
2105 {
2106 return protocol.setParentRow(newRow, parentRow);
2107 }
2108 template <typename ...Args> static constexpr void setParentRow(Args &&...)
2109 {
2110 static_assert(!protocol_traits::has_setParentRow,
2111 "Internal error, wrong setParentRow overload called");
2112 }
2113
2114 // Verifies that the iterator belongs to this adapter's level of the model,
2115 // and returns the row it points to.
2116 int rowOf(const const_iterator &it) const
2117 {
2118 Q_PRE(it.m_adapter && it.m_adapter->model() == model());
2119 Q_PRE(it.root() == storage.root());
2120 Q_PRE(it.m_row >= 0 && it.m_row <= rowCount());
2121 return it.m_row;
2122 }
2123
2124 template <typename Inserter>
2125 iterator insertAt(const_iterator pos, int count, Inserter &&inserter)
2126 {
2127 const int row = rowOf(pos);
2128 if (count > 0 && !std::forward<Inserter>(inserter)(row))
2129 return end();
2130 return iterator{row, storage.root(), this};
2131 }
2132
2133 bool insertCopiesImpl(int before, int count, const QModelIndex &parent,
2134 const row_type &value)
2135 {
2136 return storage->doInsertRows(before, count, parent, [&value, this]
2137 (range_type &range, auto *parentRow, int row, int n) {
2138 Q_UNUSED(parentRow);
2139 Q_UNUSED(this);
2140 const auto oldSize = range.size();
2141 auto newRow = range.insert(QRangeModelDetails::pos(range, row), n, value);
2142 if constexpr (protocol_traits::has_setParentRow) {
2143 for (int i = 0; i < n; ++i, ++newRow) {
2144 setParentRow(storage->protocol(), QRangeModelDetails::refTo(*newRow),
2145 QRangeModelDetails::pointerTo(parentRow));
2146 }
2147 } else {
2148 Q_UNUSED(newRow);
2149 }
2150 return range.size() == oldSize + n;
2151 });
2152 }
2153
2154 template <typename ...Args>
2155 bool insertRowImpl(int before, const QModelIndex &parent, Args &&...args)
2156 {
2157 return storage.implementation()->doInsertRows(before, 1, parent, [&args..., this]
2158 (range_type &range, auto *parentRow, int row, int count) {
2159 Q_UNUSED(this);
2160 const auto oldSize = range.size();
2161 auto newRow = range.emplace(QRangeModelDetails::pos(range, row),
2162 std::forward<Args>(args)...);
2163 setParentRow(storage->protocol(), QRangeModelDetails::refTo(*newRow),
2164 QRangeModelDetails::pointerTo(parentRow));
2165 return range.size() == oldSize + count;
2166 });
2167 }
2168
2169 template <typename LHS>
2170 static auto selfInsertion(LHS *lhs, LHS *rhs) -> decltype(lhs == rhs)
2171 {
2172 if (lhs == rhs) {
2173#ifndef QT_NO_DEBUG
2174 qCritical("Inserting data into itself is not supported");
2175#endif
2176 return true;
2177 }
2178 return false;
2179 }
2180 template <typename LHS, typename RHS>
2181 static constexpr bool selfInsertion(LHS *, RHS *) { return false; }
2182
2183 template <typename C>
2184 bool insertRowsImpl(int before, const QModelIndex &parent, C &&data)
2185 {
2186 bool result = false;
2187 result = storage->doInsertRows(before, int(std::size(data)), parent, [&data, this]
2188 (range_type &range, auto *parentRow, int row, int count){
2189 Q_UNUSED(parentRow);
2190 Q_UNUSED(this);
2191 const auto pos = QRangeModelDetails::pos(range, row);
2192 const auto oldSize = range.size();
2193
2194 auto dataRange = [&data]{
2195 if constexpr (std::is_rvalue_reference_v<C&&>) {
2196 return std::make_pair(
2197 std::move_iterator(std::begin(data)),
2198 std::move_iterator(std::end(data))
2199 );
2200 } else {
2201 return std::make_pair(std::begin(data), std::end(data));
2202 }
2203 }();
2204
2205 if constexpr (range_features::has_insert_range) {
2206 if (selfInsertion(&range, &data))
2207 return false;
2208 auto start = range.insert(pos, dataRange.first, dataRange.second);
2209 if constexpr (protocol_traits::has_setParentRow) {
2210 while (count) {
2211 setParentRow(storage->protocol(), QRangeModelDetails::refTo(*start),
2212 QRangeModelDetails::pointerTo(parentRow));
2213 ++start;
2214 --count;
2215 }
2216 } else {
2217 Q_UNUSED(start);
2218 }
2219 } else {
2220 auto newRow = range.insert(pos, count, row_type{});
2221 while (dataRange.first != dataRange.second) {
2222 *newRow = *dataRange.first;
2223 setParentRow(storage->protocol(), QRangeModelDetails::refTo(*newRow),
2224 QRangeModelDetails::pointerTo(parentRow));
2225 ++dataRange.first;
2226 ++newRow;
2227 }
2228 }
2229 return range.size() == oldSize + count;
2230 });
2231 return result;
2232 }
2233
2234 template <typename D, typename = void>
2235 struct DataFromList {
2236 static constexpr auto first(D &data) { return &data; }
2237 static constexpr auto next(D &, D *entry) { return entry; }
2238 };
2239
2240 template <typename D>
2241 struct DataFromList<D, std::enable_if_t<QRangeModelDetails::range_traits<D>::value>>
2242 {
2243 static constexpr auto first(D &data) { return std::begin(data); }
2244 static constexpr auto next(D &data, typename D::iterator entry)
2245 {
2246 ++entry;
2247 if (entry == std::end(data))
2248 entry = first(data);
2249 return entry;
2250 }
2251 };
2252
2253 template <typename D, typename = void> struct RowFromTable
2254 {
2255 static constexpr auto first(D &data) { return &data; }
2256 static constexpr auto next(D &, D *entry) { return entry; }
2257 };
2258
2259 template <typename D>
2260 struct RowFromTable<D, std::enable_if_t<std::conjunction_v<
2261 QRangeModelDetails::range_traits<D>,
2262 QRangeModelDetails::range_traits<typename D::value_type>
2263 >>
2264 > : DataFromList<D>
2265 {};
2266
2267 template <typename D>
2268 bool insertColumnImpl(int before, const QModelIndex &parent, D data)
2269 {
2270 auto entry = DataFromList<D>::first(data);
2271
2272 return storage->doInsertColumns(before, 1, parent, [&entry, &data]
2273 (auto &range, auto pos, int count) {
2274 const auto oldSize = range.size();
2275 range.insert(pos, *entry);
2276 entry = DataFromList<D>::next(data, entry);
2277 return range.size() == oldSize + count;
2278 });
2279 }
2280
2281 template <typename C>
2282 bool insertColumnsImpl(int before, const QModelIndex &parent, C data)
2283 {
2284 bool result = false;
2285 auto entries = RowFromTable<C>::first(data);
2286 auto begin = std::begin(*entries);
2287 auto end = std::end(*entries);
2288 result = storage->doInsertColumns(before, int(std::size(*entries)), parent,
2289 [&begin, &end, &entries, &data](auto &range, auto pos, int count) {
2290 const auto oldSize = range.size();
2291 if constexpr (row_features::has_insert_range) {
2292 range.insert(pos, begin, end);
2293 } else {
2294 auto start = range.insert(pos, count, {});
2295 std::copy(begin, end, start);
2296 }
2297 entries = RowFromTable<C>::next(data, entries);
2298 begin = std::begin(*entries);
2299 end = std::end(*entries);
2300 return range.size() == oldSize + count;
2301 });
2302 return result;
2303 }
2304};
2305
2306// Deduction guides are needed to correctly map single-parameter construction
2307// to the void-protocol case, and to disable construction from incompatible
2308// ranges.
2309template <typename Range, typename Protocol,
2310 QRangeModelDetails::if_can_construct<Range, Protocol> = true>
2312
2313template <typename Range,
2314 QRangeModelDetails::if_can_construct<Range> = true>
2315QRangeModelAdapter(Range &&) -> QRangeModelAdapter<Range, void>;
2316
2317#if defined(__cpp_lib_concepts) && !defined(Q_QDOC)
2318namespace QRangeModelDetails {
2319// The reference types returned when dereferencing QRangeModelAdapter's
2320// iterators are proxies that convert to a const version of the stored item
2321// (const_value_type) or row (const_row_type).
2322template <typename Proxy>
2323struct proxy_const_type {};
2324template <typename Proxy>
2325 requires requires { typename Proxy::const_value_type; }
2326struct proxy_const_type<Proxy>
2327{ using type = typename Proxy::const_value_type; };
2328template <typename Proxy>
2329 requires requires { typename Proxy::const_row_type; }
2330struct proxy_const_type<Proxy>
2331{ using type = typename Proxy::const_row_type; };
2332
2333// If the stored type also converts to that const type, then that is the
2334// common reference of proxy and stored type.
2335template <typename Proxy, typename Value>
2336concept proxy_for = !std::is_same_v<Proxy, Value>
2337 && requires { typename proxy_const_type<Proxy>::type; }
2338 && std::is_convertible_v<Proxy, typename proxy_const_type<Proxy>::type>
2339 && std::is_convertible_v<Value &, typename proxy_const_type<Proxy>::type>
2340 && std::is_convertible_v<const Value &, typename proxy_const_type<Proxy>::type>;
2341}
2342#endif
2343
2344QT_END_NAMESPACE
2345
2346#if defined(__cpp_lib_concepts) && !defined(Q_QDOC)
2347// Make the const version of the item or row the common reference of the proxy
2348// and the stored type, so that the iterators of QRangeModelAdapter model the
2349// C++20 iterator concepts, even if the stored type can't be copied.
2350namespace std {
2351template <typename Proxy, typename Value,
2352 template <typename> class ProxyQual, template <typename> class ValueQual>
2353 requires QT_PREPEND_NAMESPACE(QRangeModelDetails)::proxy_for<Proxy, Value>
2354struct basic_common_reference<Proxy, Value, ProxyQual, ValueQual>
2355{
2356 using type = typename QT_PREPEND_NAMESPACE(QRangeModelDetails)::proxy_const_type<Proxy>::type;
2357};
2358
2359template <typename Value, typename Proxy,
2360 template <typename> class ValueQual, template <typename> class ProxyQual>
2361 requires QT_PREPEND_NAMESPACE(QRangeModelDetails)::proxy_for<Proxy, Value>
2362struct basic_common_reference<Value, Proxy, ValueQual, ProxyQual>
2363{
2364 using type = typename QT_PREPEND_NAMESPACE(QRangeModelDetails)::proxy_const_type<Proxy>::type;
2365};
2366} // namespace std
2367#endif
2368
2369#endif // QRANGEMODELADAPTER_H
QRangeModelAdapter(Range &&, Protocol &&) -> QRangeModelAdapter< Range, Protocol >
#define QRMA_DATAREFERENCE_RELATIONAL_OPERATOR(op, expression)