diff --git a/src/toad/client/line_blocks.py b/src/toad/client/line_blocks.py index 99eae20b5..f9c4e75f1 100644 --- a/src/toad/client/line_blocks.py +++ b/src/toad/client/line_blocks.py @@ -356,13 +356,25 @@ def retained_bytes(self) -> int: def prepared_rows[RowsT](self, width: int, draw: Callable[[LineBlock], RowsT]) -> RowsT: return draw(self) + def standalone_cache_key(self, row_key, index: int, shared_key: Callable[[LineBlock], object]): + """Cache key when measuring this leading block on its own: `(row_key, index)` unless + a subclass declares value-keyed sharing across rows and pinned headers.""" + return (row_key, index) + @property def selection_text(self) -> str: return "" +class SharedStandaloneBlock(LineBlock): + """A value-keyed leading block whose standalone layout is shared across rows and pinned headers.""" + + def standalone_cache_key(self, row_key, index: int, shared_key: Callable[[LineBlock], object]): + return shared_key(self) + + @dataclass(frozen=True) -class Divider(LineBlock): +class Divider(SharedStandaloneBlock): """A rule carrying a title: who speaks, or who sent a message to whom. Title text without a link is drawn in the rule's role; a linked span keeps @@ -485,7 +497,7 @@ def text(self) -> str: @dataclass(frozen=True) -class Gap(LineBlock): +class Gap(SharedStandaloneBlock): """One blank line between messages.""" renders_inline: ClassVar[bool] = True diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 7f0f3c3ae..68f362737 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -65,7 +65,7 @@ ReaderPlacement, Runway, ) -from toad.client.line_blocks import BlockPreparation, Divider, LineLink +from toad.client.line_blocks import BlockPreparation, Divider, LineBlock, LineLink from toad.client.history_changes import FragmentRowUnderTop, HeaderPin, PinnedHeader, PinsMessageHeader, TopPage from toad.client.history_preparation import HistorySourceSnapshot from toad.client.history_state import LiveTranscript @@ -279,13 +279,13 @@ def fragment_key(self, fragment: HistoryFragment, font: QFont, width: int): fill the width. A draft or live row grows, so its revision is part of the key.""" return self.drawn_key((fragment.key, fragment.shown, fragment.revision), font, width) - def header_key(self, header: Divider, font: QFont, width: int): - """A pinned header on its own: prepared, kept and laid out as a row is.""" + def header_key(self, header: LineBlock, font: QFont, width: int): + """A standalone block (pinned header or gap) on its own: prepared, kept and laid out as a row is.""" return self.drawn_key(self.header_shown(header), font, width) @staticmethod - def header_shown(header: Divider) -> tuple: - """A header's place in a key, where a row's has its fragment, look and revision.""" + def header_shown(header: LineBlock) -> tuple: + """A standalone block's place in a key, where a row's has its fragment, look and revision.""" return header, None, 0 def _font_spec(self, font: QFont) -> tuple[str, float]: @@ -397,18 +397,26 @@ def block_row(self, fragment: HistoryFragment, font: QFont, width: int, y: int) for index, html in enumerate(prepared.leading): if index == decided and index < len(blocks) - 1: return index, 0 - height = self.measured_height((key, index), font, width, HtmlRow(html)) + block_key = blocks[index].standalone_cache_key( + key, index, lambda header: self.header_key(header, font, width) + ) + height = self.measured_height(block_key, font, width, HtmlRow(html)) if y < top + height or index == len(blocks) - 1: return index, max(0, int((y - top) // line)) top += height return 0, 0 def header_document(self, header: Divider, font: QFont, width: int) -> QTextDocument | None: - """A pinned header laid out as its row lays it out at this width, or none while it is - prepared. Its rich text came with its row (`RenderedRow.pinned`); a header no row brought - in this look (the width or the links just changed) is prepared as a row is, in a - render process, and the pin is drawn again when it lands.""" + """A pinned header laid out as its row lays it out at this width. Reuses the same + cache key as `block_row` so crossing a message during scroll lays its header out once, + and prepares a lightweight `Divider` (`renders_inline=True`) inline on the warm + renderer if its cache entry is cold (e.g. immediately after resize or theme switch).""" key = self.header_key(header, font, width) + if key not in self._prepared and width > 0 and header.renders_inline: + cell, _line = self._font_metrics(font) + cols = max(1, int((width - 8) / cell)) + html = self.renderer.at_width(cols).html((header,)) + self._row_prepared(key, RenderedRow(html, (), ())) formatting = self.keyed_formatting(key, "", self.block_preparation((header,), font, width)) return self.laid_out(key, font, width, formatting) if formatting.final else None diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 98d7320dd..b2dd138e0 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2155,3 +2155,82 @@ def _counting_format(widget, painter): assert "background:" in flash.styleSheet() finally: flash.deleteLater() + + +def test_block_row_and_pinned_header_share_one_cached_document_and_prepare_inline(monkeypatch): + """`HistoryRowDelegate.block_row` and `header_document` share one cache key via + `Divider.standalone_cache_key` so crossing a message during scroll lays its header out + once instead of twice, and `header_document` prepares a cold `Divider` inline without a + worker-pool round-trip.""" + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + _app = QApplication.instance() or QApplication([]) + import inspect + from agent_comms.messaging.messages import InfoKind, Message + from agent_comms.transcript.transcript_events import IncomingTranscript + from PySide6.QtGui import QFont + from toad.client.message_file_links import NO_PAGE_FILES + from toad.client.transcript_fragments import transcript_fragments + from toad.markdown_links import LinkContext, ReferenceContext + from toad.qt.history import HistoryRowDelegate + from toad.qt.transcript_fragments import QT_FRAGMENT_CLASSES + from toad.qt.window import RowPictures + + scheme = current_scheme(os.environ) + concrete = [c for c in ReferenceContext.__subclasses__() if not inspect.isabstract(c)][0] + renderer = QtLineRenderer(scheme, LinkContext(Path("."), concrete()), DiffSettings()) + + class _ExplodingPool: + def submit(self, *_a, **_kw): + raise AssertionError("header_document should prepare inline Divider without worker pool") + + delegate = HistoryRowDelegate(renderer, RowPictures(4 * 1024 * 1024), _ExplodingPool()) + font = QFont("monospace", 10) + try: + msg = Message(sender="toad-qt", target="#comms", body="Body line 1\nBody line 2", type=InfoKind) + frag = transcript_fragments( + (IncomingTranscript.of(msg, reader="user"),), + resolve_sent=lambda _r: {}, + classes=QT_FRAGMENT_CLASSES, + files=NO_PAGE_FILES, + )[0] + header = frag.pinned_dividers[0] + # 1. Cold header_document prepares inline without touching RenderProcessPool. + cold_doc = delegate.header_document(header, font, 360) + assert cold_doc is not None + + # 2. Prepared rows: block_row measures leading Gap + Divider and shares both: + # - header_document reuses the exact cached Divider doc (0 extra layouts), + # - a second message's block_row reuses the cached Gap doc (only 1 layout for its Divider). + delegate._documents.clear() + delegate._metrics.clear() + msg2 = Message(sender="other", target="#comms", body="Second body", type=InfoKind) + frag2 = transcript_fragments( + (IncomingTranscript.of(msg2, reader="user"),), + resolve_sent=lambda _r: {}, + classes=QT_FRAGMENT_CLASSES, + files=NO_PAGE_FILES, + )[0] + for f in (frag, frag2): + prep = delegate.row_preparation(f, font, 360) + delegate._row_prepared(delegate.fragment_key(f, font, 360), prep.render()) + + new_doc_calls = 0 + orig_new_document = delegate.new_document + + def _counting_new_doc(f, w): + nonlocal new_doc_calls + new_doc_calls += 1 + return orig_new_document(f, w) + + delegate.new_document = _counting_new_doc + delegate.block_row(frag, font, 360, 40) + assert new_doc_calls == 2 # Gap once + Divider 1 once + pinned_doc = delegate.header_document(header, font, 360) + assert pinned_doc is not None + assert new_doc_calls == 2 # header_document hits the exact Divider doc from block_row + delegate.block_row(frag2, font, 360, 40) + assert new_doc_calls == 3 # Gap reused; only Divider 2 laid out + assert delegate.header_document(frag2.pinned_dividers[0], font, 360) is not None + assert new_doc_calls == 3 + finally: + delegate.cleanup()