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
61 changes: 42 additions & 19 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -1281,44 +1281,65 @@ class QtStickyHeader(HeaderPin, QWidget):
`QtHistoryWindow._row_tapped` into `handle_tap` (stacked burst opens, `@sender`/`#target`
links, and `▼`/divider collapse), with live text-color inversion on the tapped span."""

_MAX_LAID_OUT = 32
_MAX_PIXMAPS = 16

def __init__(self, window: QtHistoryWindow) -> None:
super().__init__(window)
self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, True)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
self.history_window = window
self.documents: tuple[QTextDocument, ...] = ()
self.drawn: tuple = ()
self.laid_out: dict[Divider, QTextDocument] = {}
self.laid_out: OrderedDict[Divider, QTextDocument] = OrderedDict()
self.layout_context: tuple = ()
self._pixmap_cache: tuple[tuple, QImage] | None = None
self._pixmap_cache: OrderedDict[tuple, QImage] = OrderedDict()
self.hide()

def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None:
"""Every scroll offset pins; only different headers, column, font, link context or
renderer (a theme) lay anything out again, and then only the headers not already laid out."""
renderer (a theme) lay anything out again, and recently pinned headers stay cached
in `laid_out` and `_pixmap_cache` so scrolling back and forth across message
boundaries avoids re-running `setHtml` / layout / rasterization or no-op geometry calls."""
window = self.history_window
context = (width, window.font().key(), window.rows.links_revision, id(window.rows.renderer))
drawn = (headers, x, context)
if drawn == self.drawn:
return
kept = self.laid_out if context == self.layout_context else {}
laid_out = {header: kept.get(header) or window.rows.header_document(header, window.font(), width)
for header in headers}
if None in laid_out.values():
return
if context != self.layout_context:
self.laid_out.clear()
self._pixmap_cache.clear()
self.layout_context = context
documents: list[QTextDocument] = []
for header in headers:
document = self.laid_out.get(header)
if document is not None:
self.laid_out.move_to_end(header)
else:
document = window.rows.header_document(header, window.font(), width)
if document is None:
return
self.laid_out[header] = document
while len(self.laid_out) > self._MAX_LAID_OUT:
self.laid_out.popitem(last=False)
documents.append(document)
self.drawn = drawn
self.layout_context = context
self.laid_out = laid_out
self.documents = tuple(self.laid_out[header] for header in headers)
self._pixmap_cache = None
self.resize(width, sum(int(document.size().height()) for document in self.documents))
self.move(window.viewport().mapTo(window, QPoint(x, 0)))
self.raise_()
self.documents = tuple(documents)
height = sum(int(document.size().height()) for document in self.documents)
if self.width() != width or self.height() != height:
self.resize(width, height)
origin = window.viewport().mapTo(window, QPoint(x, 0))
if self.pos() != origin:
self.move(origin)
if not self.isVisible():
self.raise_()
self.update()

def show_pin(self, shown: bool) -> None:
if self.isVisible() != shown:
self.setVisible(shown)
if shown:
self.raise_()

def handle_tap(self, local: QPoint) -> bool:
"""Handle a tap at `local` (widget coordinates) on the pinned header:
Expand Down Expand Up @@ -1368,9 +1389,9 @@ def paintEvent(self, event) -> None: # type: ignore[override]
dpr = self.devicePixelRatioF()
img_format = HistoryRowDelegate._backing_image_format(self, painter)
key = (self.drawn, self.width(), self.height(), dpr, bg_hex, img_format)
cached = self._pixmap_cache
if cached is not None and cached[0] == key:
image = cached[1]
image = self._pixmap_cache.get(key)
if image is not None:
self._pixmap_cache.move_to_end(key)
else:
image = QImage(max(1, round(self.width() * dpr)), max(1, round(self.height() * dpr)), img_format)
image.setDevicePixelRatio(dpr)
Expand All @@ -1382,7 +1403,9 @@ def paintEvent(self, event) -> None: # type: ignore[override]
document.documentLayout().draw(drawing, context)
drawing.translate(0, document.size().height())
drawing.end()
self._pixmap_cache = (key, image)
self._pixmap_cache[key] = image
while len(self._pixmap_cache) > self._MAX_PIXMAPS:
self._pixmap_cache.popitem(last=False)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source)
painter.drawImage(0, 0, image)
painter.end()
Expand Down
37 changes: 28 additions & 9 deletions src/toad/qt/virtual_scroll.py
Original file line number Diff line number Diff line change
Expand Up @@ -1195,15 +1195,30 @@ def rows_changed(self) -> None:
def rows_repainted(self) -> None:
self.viewport().update()

def floating_over(self) -> list[QRect]:
def floating_covers(self) -> tuple[list[QRect], list[QRect]]:
"""Return `(all_covers, opaque_covers)` for visible child widgets overlapping
the viewport. Opaque covers (`WA_OpaquePaintEvent`) completely occlude the
viewport pixels underneath them so `scrollContentsBy` does not invalidate
hidden strips on every scroll frame."""
viewport = self.viewport()
area = viewport.geometry()
return [
child.geometry().intersected(area).translated(-area.topLeft())
for child in self.children()
if isinstance(child, QWidget) and child is not viewport and child.isVisible()
and child.geometry().intersects(area)
]
covers: list[QRect] = []
opaque: list[QRect] = []
for child in self.children():
if (
isinstance(child, QWidget)
and child is not viewport
and child.isVisible()
and child.geometry().intersects(area)
):
rect = child.geometry().intersected(area).translated(-area.topLeft())
covers.append(rect)
if child.testAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent):
opaque.append(rect)
return covers, opaque

def floating_over(self) -> list[QRect]:
return self.floating_covers()[0]

@staticmethod
def uncovered(rect: QRect, covers: list[QRect]) -> QRect:
Expand All @@ -1224,13 +1239,17 @@ def uncovered(rect: QRect, covers: list[QRect]) -> QRect:

def scrollContentsBy(self, dx: int, dy: int) -> None: # noqa: N802 - Qt virtual method name
viewport = self.viewport()
covers = self.floating_over()
covers, opaque = self.floating_covers()
clear = self.uncovered(viewport.rect(), covers) if covers and not dx else QRect()
if clear.isEmpty():
viewport.scroll(dx, dy)
return
viewport.scroll(dx, dy, clear)
viewport.update(QRegion(viewport.rect()).subtracted(QRegion(clear)))
dirty = QRegion(viewport.rect()).subtracted(QRegion(clear))
for rect in opaque:
dirty = dirty.subtracted(QRegion(rect))
if not dirty.isEmpty():
viewport.update(dirty)

def paintEvent(self, event) -> None: # type: ignore[override]
if self._layout_pending:
Expand Down
114 changes: 114 additions & 0 deletions tests/model/test_android_perf_ux_arrivals.py
Original file line number Diff line number Diff line change
Expand Up @@ -2591,3 +2591,117 @@ def test_line_block_triggers_header_collapse_and_channel_row_tones():
assert issubclass(ChannelAlternateRowToneColour, ChannelRowTone)
assert not issubclass(SidebarToggleToneColour, ChannelRowTone)
assert ChannelRowFace.row_tones == (ChannelRowToneColour, ChannelAlternateRowToneColour)


def test_sticky_header_lru_caches_headers_and_opaque_scroll_clip_skips_occluded_strip(monkeypatch):
"""QtStickyHeader keeps recently pinned QTextDocuments and rasterized QImages in bounded
LRUs across header switches and skips no-op resize/move calls; VirtualRowCanvas.scrollContentsBy
subtracts WA_OpaquePaintEvent covers from viewport.update(dirty)."""
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
_app = QApplication.instance() or QApplication([])
from collections import OrderedDict
from PySide6.QtCore import QPoint, QRect, Qt
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
from PySide6.QtWidgets import QWidget
from toad.client.line_blocks import Divider, MutedRole, Span
from toad.qt.history import QtStickyHeader
from toad.qt.virtual_scroll import VirtualRowCanvas

# 1. QtStickyHeader LRU + no-op geometry guard.
class _FakeHistoryWindow(QWidget):
def __init__(self) -> None:
super().__init__()
self.resize(412, 600)
self._vp = QWidget(self)
self._vp.setGeometry(0, 0, 412, 600)
self.rows = MagicMock()
self.rows.links_revision = 1
self.rows.renderer = object()
self.rows._theme_colours.return_value = ("#111111", QColor("#111111"), QColor("#eeeeee"))
self.tap_highlight = MagicMock()
self.tap_highlight.is_pinned.return_value = False

def viewport(self) -> QWidget:
return self._vp

host = _FakeHistoryWindow()
build_calls: list[Divider] = []

def make_doc(header: Divider, _font, width: int) -> QTextDocument:
build_calls.append(header)
doc = QTextDocument()
doc.setDocumentMargin(0)
doc.setTextWidth(width)
doc.setPlainText(header.spans[0].text)
return doc

host.rows.header_document.side_effect = make_doc
sticky = QtStickyHeader(host)

h1 = Divider((Span("Header A"),), MutedRole)
h2 = Divider((Span("Header B"),), MutedRole)
resize_calls = 0
move_calls = 0
orig_resize, orig_move = sticky.resize, sticky.move

def counted_resize(*args):
nonlocal resize_calls
resize_calls += 1
return orig_resize(*args)

def counted_move(*args):
nonlocal move_calls
move_calls += 1
return orig_move(*args)

sticky.resize = counted_resize
sticky.move = counted_move

sticky.draw_pinned((h1,), 0, 412)
sticky.show()
# Paint h1 so its QImage lands in _pixmap_cache.
sticky.grab()
sticky.draw_pinned((h2,), 0, 412)
sticky.grab()
# Switch back to h1: must hit both laid_out and _pixmap_cache with 0 new builds and 0 resizes/moves.
sticky.draw_pinned((h1,), 0, 412)
sticky.grab()
assert build_calls == [h1, h2]
assert len(sticky.laid_out) == 2
assert len(sticky._pixmap_cache) == 2
assert resize_calls == 1
assert move_calls == 0
sticky.draw_pinned((h1,), 4, 412)
assert move_calls == 1

# 2. VirtualRowCanvas.scrollContentsBy excludes full-width WA_OpaquePaintEvent cover from dirty update.
canvas = VirtualRowCanvas(MagicMock())
canvas.resize(412, 600)
canvas.show()
vp_geo = canvas.viewport().geometry()
opaque_top = QWidget(canvas)
opaque_top.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, True)
opaque_top.setGeometry(vp_geo.left(), vp_geo.top(), vp_geo.width(), 24)
opaque_top.show()

updates: list[QRect] = []
orig_update = canvas.viewport().update

def capture_update(region):
updates.append(region.boundingRect() if hasattr(region, "boundingRect") else region)
return orig_update(region)

canvas.viewport().update = capture_update
canvas.scrollContentsBy(0, -40)
assert updates == [], f"opaque full-width header must not trigger extra viewport.update, got {updates}"

# Adding a translucent cover still updates the non-occluded band around it.
translucent_bottom = QWidget(canvas)
translucent_bottom.setGeometry(vp_geo.left() + 140, vp_geo.top() + vp_geo.height() - 40, 120, 32)
translucent_bottom.show()
canvas.scrollContentsBy(0, -40)
assert len(updates) == 1
assert updates[0].top() == vp_geo.height() - 40
assert updates[0].top() > 24, "opaque top band must stay excluded from dirty region"
host.close()
canvas.close()
Loading