From 1df58c85146f826a5ca4fa6f0c0dff3afadcaf2c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 21 Nov 2026 21:59:31 -0500 Subject: [PATCH] virtual rows: a delegate's rows are prepared by its own preparer Every RowDocumentDelegate owned a one-thread QThreadPool and called each row's preparation on it. For a member whose preparation is Python (Toad's history: blocks to rich text), that thread takes turns with the GUI thread for the interpreter, and a member that already has worker processes had a second route beside them that any row not handed over ready-made fell into, silently. Where rows are prepared is now a family, `RowPreparer` (prepare, clear, stop; batches arrive through one callback on the GUI thread). `ThreadRowPreparer` is the worker thread there was, and the default (`row_preparer`); a member that prepares elsewhere answers its own, and then has no thread at all. Tests: tests/test_virtual_rows.py and tests/test_log_viewer_lifecycle.py, 22 passed, with the new test_a_member_prepares_its_rows_where_it_says. The two tests in tests/test_virtual_rows_band.py fail the same way on origin/main. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016gZLdx92gKjvnNKianjAXG --- src/pyqt_reactive/widgets/virtual_rows.py | 82 ++++++++++++++++++----- tests/test_log_viewer_lifecycle.py | 2 +- tests/test_virtual_rows.py | 53 ++++++++++++++- 3 files changed, 119 insertions(+), 18 deletions(-) diff --git a/src/pyqt_reactive/widgets/virtual_rows.py b/src/pyqt_reactive/widgets/virtual_rows.py index 36e246d3..baa5812f 100644 --- a/src/pyqt_reactive/widgets/virtual_rows.py +++ b/src/pyqt_reactive/widgets/virtual_rows.py @@ -15,7 +15,7 @@ from __future__ import annotations -from abc import abstractmethod +from abc import ABC, abstractmethod import math import threading import time @@ -23,6 +23,7 @@ from collections.abc import Callable, Hashable, Iterator from contextlib import contextmanager from dataclasses import dataclass +from functools import cached_property from PySide6.QtCore import ( QModelIndex, @@ -160,6 +161,56 @@ def run(self) -> None: self.signals.finished.emit(batch) +class RowPreparer(ABC): + """Where rows' formatting is worked out, away from the GUI thread. A delegate queues each + row's work here and is told, on the GUI thread, of the batches that finish (`arrived`). + + Which member a delegate uses is its own (`RowDocumentDelegate.row_preparer`). The work + is the member's too: `ThreadRowPreparer` calls it on a thread of this process, so Python + work there takes turns with the GUI thread for the interpreter; a member that hands the + work to another process needs it to be something that process can receive.""" + + def __init__(self, arrived: Callable[[list[tuple[Hashable, RowFormatting]]], None]) -> None: + self.arrived = arrived + + @abstractmethod + def prepare(self, key: Hashable, work: Callable[[], RowFormatting]) -> None: + """Work out the row's formatting; it arrives in a batch, under `key`.""" + + @abstractmethod + def clear(self) -> None: + """Drop the rows queued and not started.""" + + @abstractmethod + def stop(self) -> None: + """Join what is running: nothing arrives after this returns.""" + + +class ThreadRowPreparer(RowPreparer): + """One worker thread of this process, draining the queue in order.""" + + def __init__(self, arrived: Callable[[list[tuple[Hashable, RowFormatting]]], None], + parent: QObject) -> None: + super().__init__(arrived) + # The thread and its signals share the delegate's lifetime. + self.pool = QThreadPool(parent) + self.pool.setMaxThreadCount(1) + self.signals = PreparedRowSignals(self.pool) + self.signals.finished.connect(arrived) + self.queue = PreparationQueue() + + def prepare(self, key: Hashable, work: Callable[[], RowFormatting]) -> None: + if self.queue.add(key, work): + self.pool.start(RowPreparations(self.queue, self.signals)) + + def clear(self) -> None: + self.queue.clear() + self.pool.clear() + + def stop(self) -> None: + self.pool.waitForDone() + + class DetachedRows: """Rows no view draws yet: nothing to lay out again or repaint, and no viewport width.""" @@ -206,12 +257,6 @@ class RowDocumentDelegate(QStyledItemDelegate): def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.view: DetachedRows | VirtualRowView = DetachedRows() - # One worker thread and its signals share this delegate's lifetime. - self._thread_pool = QThreadPool(self) - self._thread_pool.setMaxThreadCount(1) - self._prepared_signals = PreparedRowSignals(self._thread_pool) - self._prepared_signals.finished.connect(self._rows_prepared) - self._queue = PreparationQueue() self.preparing = True self._stopped = False self._prepared: OrderedDict[Hashable, RowFormatting] = OrderedDict() @@ -273,7 +318,16 @@ def paint_background(self, painter, option: QStyleOptionViewItem, row: int) -> N """Rows draw no background of their own.""" def stop_preparation(self) -> None: - """Close whatever the preparations run through; the pool itself is joined after.""" + """Close whatever the preparations run through; the preparer itself is joined after.""" + + @cached_property + def preparer(self) -> RowPreparer: + """Where this delegate's rows are prepared, made when the first row asks.""" + return self.row_preparer() + + def row_preparer(self) -> RowPreparer: + """A worker thread of this process, unless a member prepares its rows elsewhere.""" + return ThreadRowPreparer(self._rows_prepared, self) # Caches @@ -283,15 +337,14 @@ def formatting(self, index: QModelIndex, font: QFont, width: int) -> RowFormatti self.preparation(index, font, width)) def keyed_formatting(self, key: Hashable, text: str, prepare: Callable[[], RowFormatting]) -> RowFormatting: - """The formatting prepared under `key`, queueing `prepare` on the pool the first time; - a `PendingRow` stands in until it arrives.""" + """The formatting prepared under `key`, queueing `prepare` with the delegate's + preparer the first time; a `PendingRow` stands in until it arrives.""" if key in self._prepared: self._prepared.move_to_end(key) return self._prepared[key] if self.preparing and key not in self._pending: self._pending.add(key) - if self._queue.add(key, prepare): - self._thread_pool.start(RowPreparations(self._queue, self._prepared_signals)) + self.preparer.prepare(key, prepare) return PendingRow(text) def final_document(self, index: QModelIndex, font: QFont, width: int) -> QTextDocument | None: @@ -548,10 +601,9 @@ def cleanup(self) -> None: self._stopped = True self.preparing = False self._viewport_update_timer.stop() - self._queue.clear() - self._thread_pool.clear() + self.preparer.clear() self.stop_preparation() - self._thread_pool.waitForDone() + self.preparer.stop() self._pending.clear() # Qt's delegate calls diff --git a/tests/test_log_viewer_lifecycle.py b/tests/test_log_viewer_lifecycle.py index f50be7e5..afb962c7 100644 --- a/tests/test_log_viewer_lifecycle.py +++ b/tests/test_log_viewer_lifecycle.py @@ -74,7 +74,7 @@ def wait_until_closed(client, _text): delegate.cleanup() assert not delegate.preparing - assert delegate._thread_pool.activeThreadCount() == 0 + assert delegate.preparer.pool.activeThreadCount() == 0 assert delegate._pending == set() diff --git a/tests/test_virtual_rows.py b/tests/test_virtual_rows.py index b10e6df6..ed12620b 100644 --- a/tests/test_virtual_rows.py +++ b/tests/test_virtual_rows.py @@ -9,7 +9,9 @@ from PySide6.QtCore import QSize, QStringListModel, Qt from PySide6.QtGui import QFont, QGuiApplication, QTextDocument -from pyqt_reactive.widgets.virtual_rows import PendingRow, RowDocumentDelegate, RowFormatting, VirtualRowView +from pyqt_reactive.widgets.virtual_rows import ( + PendingRow, RowDocumentDelegate, RowFormatting, RowPreparer, VirtualRowView, +) @dataclass(frozen=True) @@ -229,7 +231,7 @@ def test_a_page_of_rows_arrives_as_one_batch(qtbot) -> None: view.setModel(model) view.resize(300, 2000) batches: list[int] = [] - view.rows._prepared_signals.finished.connect(lambda batch: batches.append(len(batch))) + view.rows.preparer.signals.finished.connect(lambda batch: batches.append(len(batch))) font = QFont() try: for row in range(40): @@ -317,3 +319,50 @@ def test_a_look_that_arrives_at_the_rows_height_is_repainted_and_moves_no_row(qt assert (view.laid_out, view.repainted) == (2, 2) finally: rows.cleanup() + + +class HeldPreparer(RowPreparer): + """Rows' work kept until the test hands a batch back: a preparer that is not a thread.""" + + def __init__(self, arrived) -> None: + super().__init__(arrived) + self.held: dict = {} + self.stopped = False + + def prepare(self, key, work) -> None: + self.held[key] = work + + def land(self) -> None: + held, self.held = self.held, {} + self.arrived([(key, work()) for key, work in held.items()]) + + def clear(self) -> None: + self.held.clear() + + def stop(self) -> None: + self.stopped = True + + +class HeldRows(BoldRows): + def row_preparer(self) -> HeldPreparer: + return HeldPreparer(self._rows_prepared) + + +def test_a_member_prepares_its_rows_where_it_says(qtbot) -> None: + """A delegate's rows are prepared by its own preparer and nowhere else: the row's work + goes to it once, the row stands in plain until the preparer hands it back, and closing + the delegate drops what it had not started and joins it.""" + model = QStringListModel([f"row {number}" for number in range(5)]) + view = VirtualRowView(HeldRows()) + qtbot.addWidget(view) + view.setModel(model) + view.resize(300, 200) + rows, font = view.rows, QFont() + for _ in range(2): + assert rows.formatting(model.index(3, 0), font, 300) == PendingRow("row 3") + assert len(rows.preparer.held) == 1 + rows.preparer.land() + assert rows.formatting(model.index(3, 0), font, 300) == BoldRow("row 3") + rows.formatting(model.index(4, 0), font, 300) + rows.cleanup() + assert rows.preparer.stopped and not rows.preparer.held