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
82 changes: 67 additions & 15 deletions src/pyqt_reactive/widgets/virtual_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@

from __future__ import annotations

from abc import abstractmethod
from abc import ABC, abstractmethod
import math
import threading
import time
from collections import OrderedDict, deque
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,
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion tests/test_log_viewer_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()


Expand Down
53 changes: 51 additions & 2 deletions tests/test_virtual_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Loading