From ed52c3998f64b45d256db17b01a5d7aff13985d8 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 23 Nov 2026 18:36:02 -0500 Subject: [PATCH] virtual rows: bound per-key row metrics with eviction and reschedule multi-slice measurement 1. Consolidate RowDocumentDelegate's three parallel per-width dicts (_size_hints, _extents, _cached_widths) into one LRU-bounded OrderedDict of per-key width->RowMetrics (_metrics, bounded by MAX_PREPARED_ROWS). - Evicting an old key from _prepared now also drops its kept metrics and documents instead of leaking them forever. - Keys measured directly via measured_height without entering _prepared (e.g. pinned sub-block measurements) stay LRU-bounded to MAX_PREPARED_ROWS. - Expose measured_size_for(key, width) and measured_count() instead of probing _size_hints directly. 2. Fix _measure_slice() stopping mid-thread when unmeasured rows span multiple 8ms slices: `if measured: view.rows_changed()` previously skipped `elif self._unmeasured: self._measure_timer.start()`, and because estimated rows already hold a kept_row entry, sizeHint() never re-armed the timer. Change `elif self._unmeasured:` to `if self._unmeasured:` so multi-slice measurement always drains to completion. --- src/pyqt_reactive/widgets/virtual_rows.py | 107 ++++++++++++++++------ tests/test_virtual_rows.py | 48 +++++++++- tests/test_virtual_rows_band.py | 24 ++++- 3 files changed, 145 insertions(+), 34 deletions(-) diff --git a/src/pyqt_reactive/widgets/virtual_rows.py b/src/pyqt_reactive/widgets/virtual_rows.py index b4a549e..085f131 100644 --- a/src/pyqt_reactive/widgets/virtual_rows.py +++ b/src/pyqt_reactive/widgets/virtual_rows.py @@ -240,6 +240,16 @@ def __init__(self, key: Hashable, size: QSize | None, font: QFont, estimated: bo 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. @@ -262,12 +272,10 @@ def __init__(self, parent: QWidget | None = None) -> None: 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) @@ -360,6 +368,46 @@ def final_document(self, index: QModelIndex, font: QFont, width: int) -> QTextDo 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) + def laid_out( self, key: Hashable, font: QFont, width: int, formatting: RowFormatting ) -> QTextDocument: @@ -376,10 +424,13 @@ def laid_out( 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 @@ -389,7 +440,11 @@ def row_extent(self, key: Hashable, width: int) -> int: 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 @@ -417,15 +472,15 @@ def measured_height(self, key: Hashable, font: QFont, width: int, formatting: Ro 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: @@ -448,11 +503,9 @@ def _row_prepared(self, key: Hashable, prepared: RowFormatting) -> None: 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(): @@ -509,9 +562,7 @@ def release_documents(self) -> None: 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 @@ -669,7 +720,7 @@ def sizeHint(self, option, index) -> QSize: # type: ignore[override] 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) @@ -688,16 +739,16 @@ def measured_size(self, index: QModelIndex, font: QFont, width: int) -> QSize: 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: @@ -705,7 +756,7 @@ def estimated_size(self, index: QModelIndex, font: QFont, width: int) -> QSize: 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 @@ -730,7 +781,7 @@ def _measure_slice(self) -> None: self._unmeasured[persistent] = None if measured: view.rows_changed() - elif self._unmeasured: + if self._unmeasured: self._measure_timer.start() diff --git a/tests/test_virtual_rows.py b/tests/test_virtual_rows.py index 0759f56..2c7b19c 100644 --- a/tests/test_virtual_rows.py +++ b/tests/test_virtual_rows.py @@ -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) @@ -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() @@ -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() diff --git a/tests/test_virtual_rows_band.py b/tests/test_virtual_rows_band.py index 5109036..6076a98 100644 --- a/tests/test_virtual_rows_band.py +++ b/tests/test_virtual_rows_band.py @@ -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 @@ -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()