Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 79 additions & 28 deletions src/pyqt_reactive/widgets/virtual_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,16 @@
self.key, self.size, self.font, self.estimated = key, size, QFont(font), estimated


class RowMetrics:
"""A row key's laid-out size and horizontal extent at one width."""

__slots__ = ("size", "extent")

def __init__(self, size: QSize | None = None, extent: int | None = None) -> None:
self.size = size
self.extent = extent


class RowDocumentDelegate(QStyledItemDelegate):
"""Paints each row as a QTextDocument at the view's width.

Expand All @@ -262,12 +272,10 @@
self._prepared: OrderedDict[Hashable, RowFormatting] = OrderedDict()
self._pending: set[Hashable] = set()
self._documents: OrderedDict[tuple[Hashable, int], QTextDocument] = OrderedDict()
self._size_hints: dict[tuple[Hashable, int], QSize] = {}
# A laid-out row wider than its layout width (unwrapped content): how wide, by the
# same key the height is kept under.
self._extents: dict[tuple[Hashable, int], int] = {}
# The widths each key has a document or height cached at, so an arrival drops them.
self._cached_widths: dict[Hashable, set[int]] = {}
# Per-key laid-out metrics keyed by width (measured size and horizontal extent for
# unwrapped content), LRU-bounded to MAX_PREPARED_ROWS so evicted or direct-measured
# keys cannot accumulate without bound.
self._metrics: OrderedDict[Hashable, dict[int, RowMetrics]] = OrderedDict()
# A batch of finished preparations lays the view out once, in the next frame.
self._viewport_update_timer = QTimer(self)
self._viewport_update_timer.setSingleShot(True)
Expand Down Expand Up @@ -360,6 +368,46 @@
return None
return self.laid_out(key[0], font, width, formatting)

def _key_metrics(self, key: Hashable) -> dict[int, RowMetrics]:
"""The per-width metrics kept under `key`, LRU-bounded to `MAX_PREPARED_ROWS`."""
widths = self._metrics.get(key)
if widths is not None:
self._metrics.move_to_end(key)
return widths
widths = {}
self._metrics[key] = widths
if len(self._metrics) > self.MAX_PREPARED_ROWS:
evicted, evicted_widths = self._metrics.popitem(last=False)
for width in evicted_widths:
self._documents.pop((evicted, width), None)
return widths

def _record_measured_size(self, key: Hashable, width: int, size: QSize) -> None:
widths = self._key_metrics(key)
entry = widths.get(width)
if entry is None:
widths[width] = RowMetrics(size=size)
else:
entry.size = size

def _drop_key_metrics(self, key: Hashable) -> None:
widths = self._metrics.pop(key, None)
if widths is not None:
for width in widths:
self._documents.pop((key, width), None)

def measured_size_for(self, key: Hashable, width: int) -> QSize | None:
"""The kept size for `key` at `width`, or None if not measured yet."""
widths = self._metrics.get(key)
if widths is None:
return None
entry = widths.get(width)
return None if entry is None else entry.size

def measured_count(self) -> int:
"""How many `(key, width)` measurements are currently kept."""
return sum(1 for widths in self._metrics.values() for entry in widths.values() if entry.size is not None)

Check failure on line 409 in src/pyqt_reactive/widgets/virtual_rows.py

View workflow job for this annotation

GitHub Actions / code-quality

Ruff E501

Line too long (113 > 100)

def laid_out(
self, key: Hashable, font: QFont, width: int, formatting: RowFormatting
) -> QTextDocument:
Expand All @@ -376,10 +424,13 @@
document = self.new_document(font, width)
formatting.fill(document)
self._documents[cache_key] = document
self._cached_widths.setdefault(key, set()).add(width)
widths = self._key_metrics(key)
entry = widths.get(width)
if entry is None:
entry = widths[width] = RowMetrics()
extent = max(math.ceil(document.idealWidth()), math.ceil(document.size().width()))
if extent > width:
self._extents[cache_key] = extent
entry.extent = extent
if len(self._documents) > self.MAX_DOCUMENTS:
self._documents.popitem(last=False)
return document
Expand All @@ -389,7 +440,11 @@
wraps, more where it holds content that does not (a `pre` block). Recorded when the
row is laid out and kept with its height, so asking it lays nothing out; a row not
laid out yet answers `width`."""
return self._extents.get((key, width), width)
widths = self._metrics.get(key)
if widths is None:
return width
entry = widths.get(width)
return width if entry is None or entry.extent is None else entry.extent

def row_document(self, index: QModelIndex, font: QFont, width: int) -> QTextDocument:
"""The row's document; a pending row's is its plain text, laid out for this one ask
Expand Down Expand Up @@ -417,15 +472,15 @@
width however many times its height is asked for, and a row whose prepared
formatting arrives drops its cached height the same frame its documents do.
"""
cache_key = (key, width)
size = self._size_hints.get(cache_key)
size = self.measured_size_for(key, width)
if size is not None:
return size.height()
formatting = formatting.resolved()
if not formatting.final:
return formatting.estimated_height(font, self.text_width(width)) + self.ROW_PADDING
document = self.laid_out(key, font, width, formatting)
size = self._size_hints[cache_key] = QSize(width, int(document.size().height()) + self.ROW_PADDING)
size = QSize(width, int(document.size().height()) + self.ROW_PADDING)
self._record_measured_size(key, width, size)
return size.height()

def _rows_prepared(self, batch: list[tuple[Hashable, RowFormatting]]) -> None:
Expand All @@ -448,11 +503,9 @@
self._pending.discard(key)
self._prepared[key] = prepared
if len(self._prepared) > self.MAX_PREPARED_ROWS:
self._prepared.popitem(last=False)
for width in self._cached_widths.pop(key, ()):
self._documents.pop((key, width), None)
self._size_hints.pop((key, width), None)
self._extents.pop((key, width), None)
evicted, _ = self._prepared.popitem(last=False)
self._drop_key_metrics(evicted)
self._drop_key_metrics(key)
if self._moves_rows(key, prepared, awaited):
self._arrivals_moved_rows = True
if not self._viewport_update_timer.isActive():
Expand Down Expand Up @@ -509,9 +562,7 @@
def width_changed(self) -> None:
"""Documents and heights hold one width; prepared formatting may hold any."""
self.release_documents()
self._size_hints.clear()
self._extents.clear()
self._cached_widths.clear()
self._metrics.clear()
self.forget_row_sizes()

# Row sizes kept aligned with the model's rows
Expand Down Expand Up @@ -669,7 +720,7 @@
self.initStyleOption(opt, index)
width = self.available_width(opt)
key = self.preparation_key(index, opt.font, width)
size = self._size_hints.get((key, width))
size = self.measured_size_for(key, width)
if size is not None:
self.keep_row_size(index.row(), key, size, opt.font)
return self.hinted(key, size)
Expand All @@ -688,24 +739,24 @@
its arrival lays it out once."""
if (kept := self.kept_size(index.row(), measured=True)) is not None:
return kept
key = (self.preparation_key(index, font, width), width)
size = self._size_hints.get(key)
key = self.preparation_key(index, font, width)
size = self.measured_size_for(key, width)
if size is None:
document = self.final_document(index, font, width)
if document is None:
return self.estimated_size(index, font, width)
height = int(document.size().height()) + self.ROW_PADDING
size = self._size_hints[key] = QSize(width, height)
self._cached_widths.setdefault(key[0], set()).add(width)
self.keep_row_size(index.row(), key[0], size, font)
size = QSize(width, height)
self._record_measured_size(key, width, size)
self.keep_row_size(index.row(), key, size, font)
return size

def estimated_size(self, index: QModelIndex, font: QFont, width: int) -> QSize:
estimate = PendingRow(self.row_text(index)).estimated_height(font, self.text_width(width))
return QSize(width, estimate + self.ROW_PADDING)

def is_measured(self, index: QModelIndex, font: QFont, width: int) -> bool:
return (self.preparation_key(index, font, width), width) in self._size_hints
return self.measured_size_for(self.preparation_key(index, font, width), width) is not None

def _measure_slice(self) -> None:
"""Lay out the estimated rows nearest the reader, for one slice, then the view once
Expand All @@ -730,7 +781,7 @@
self._unmeasured[persistent] = None
if measured:
view.rows_changed()
elif self._unmeasured:
if self._unmeasured:
self._measure_timer.start()


Expand Down
48 changes: 43 additions & 5 deletions tests/test_virtual_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_rows_paint_plain_until_their_formatting_is_prepared(qtbot) -> None:
# A pending row is not laid out: no document is kept for it, and its height is an
# estimate from its text's lines.
assert view.rows.final_document(index, font, 300) is None
assert not view.rows._documents and not view.rows._size_hints
assert not view.rows._documents and view.rows.measured_count() == 0
qtbot.waitUntil(lambda: view.rows.formatting(index, font, 300) == BoldRow("row 3"))
# The prepared row lays out taller than its plain line.
assert view.rows.row_document(index, font, 300).size().height() > plain_line_height(font)
Expand Down Expand Up @@ -108,18 +108,18 @@ def test_measured_height_is_kept_only_for_final_formatting(qtbot) -> None:
try:
estimate = delegate.measured_height(key, font, 300, PendingRow("row 3"))
assert estimate > 0
assert (key, 300) not in delegate._size_hints
assert delegate.measured_size_for(key, 300) is None
laid_out = delegate.measured_height(key, font, 300, BoldRow("row 3"))
assert (key, 300) in delegate._size_hints
assert delegate.measured_size_for(key, 300) is not None
# Kept: the formatting handed on a later call is not laid out again.
assert delegate.measured_height(key, font, 300, PendingRow("row 3")) == laid_out
# A different width is a different measurement.
assert (key, 150) not in delegate._size_hints
assert delegate.measured_size_for(key, 150) is None
# A member can draw a row under its key with another final look while the new one is
# prepared (the look it last showed): the arrival drops what was laid out from it, so
# the row lays out from what arrived.
delegate._row_prepared(key, BoldRow("row 3"))
assert (key, 300) not in delegate._size_hints
assert delegate.measured_size_for(key, 300) is None
finally:
delegate.cleanup()

Expand Down Expand Up @@ -401,3 +401,41 @@ def kept_under_keys() -> int:
finally:
rows.end_layout()
rows.cleanup()


def test_row_metrics_evict_with_prepared_and_stay_bounded(qtbot) -> None:
"""Evicting a prepared row drops its kept measurements, extents and documents too,
and keys measured directly without entering `_prepared` stay LRU-bounded to
`MAX_PREPARED_ROWS`."""

class SmallCacheRows(BoldRows):
MAX_PREPARED_ROWS = 4

delegate = SmallCacheRows()
qtbot.addWidget(VirtualRowView(delegate))
font = QFont()
try:
for i in range(6):
key = ("prepared", i)
row = UnwrappedRow("x" * 200)
delegate._row_prepared(key, row)
delegate.measured_height(key, font, 200, row)

# Keys 0 and 1 were evicted from _prepared and must also leave metrics and documents.
assert len(delegate._prepared) == 4
assert len(delegate._metrics) <= 4
for evicted in (("prepared", 0), ("prepared", 1)):
assert delegate.measured_size_for(evicted, 200) is None
assert delegate.row_extent(evicted, 200) == 200
assert (evicted, 200) not in delegate._documents
assert delegate.row_extent(("prepared", 5), 200) > 200

# Direct measured_height keys (never in _prepared, e.g. pinned sub-blocks) stay bounded.
for i in range(10):
direct = ("direct", i)
delegate.measured_height(direct, font, 200, UnwrappedRow("y" * 200))
assert len(delegate._metrics) == 4
assert delegate.measured_size_for(("direct", 0), 200) is None
assert delegate.measured_size_for(("direct", 9), 200) is not None
finally:
delegate.cleanup()
24 changes: 23 additions & 1 deletion tests/test_virtual_rows_band.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_a_layout_lays_out_only_the_rows_near_the_reader(qtbot) -> None:
try:
view.follow_end()
view.executeDelayedItemsLayout()
measured = len(view.rows._size_hints)
measured = view.rows.measured_count()
assert 0 < measured < 100
qtbot.waitUntil(lambda: all_measured(view), timeout=10_000)
assert view.at_end
Expand All @@ -64,3 +64,25 @@ def test_measuring_rows_above_keeps_the_reader_on_the_same_row(qtbot) -> None:
assert view.indexAt(view.viewport().rect().topLeft()).row() == top
finally:
view.rows.cleanup()


def test_multi_slice_measurement_reschedules_until_all_rows_are_measured(qtbot) -> None:
"""When unmeasured rows exceed one slice budget, `_measure_slice` must reschedule
the timer even after `rows_changed()` lays out the rows measured so far."""

class SmallSliceRows(FinalRows):
MEASURE_SLICE_SECONDS = 0.0005

model = QStringListModel([f"row {number}" for number in range(80)])
view = VirtualRowView(SmallSliceRows())
qtbot.addWidget(view)
view.resize(300, 200)
view.setModel(model)
view.show()
try:
view.follow_end()
view.executeDelayedItemsLayout()
assert view.rows._unmeasured
qtbot.waitUntil(lambda: all_measured(view), timeout=5_000)
finally:
view.rows.cleanup()
Loading