diff --git a/src/pyqt_reactive/widgets/shared/list_item_delegate.py b/src/pyqt_reactive/widgets/shared/list_item_delegate.py index 4988d499..02b65e9c 100644 --- a/src/pyqt_reactive/widgets/shared/list_item_delegate.py +++ b/src/pyqt_reactive/widgets/shared/list_item_delegate.py @@ -6,7 +6,8 @@ """ import logging -from dataclasses import dataclass +from collections.abc import Sequence +from dataclasses import dataclass, field from enum import Enum from typing import cast @@ -17,7 +18,7 @@ QAbstractItemView, QListView, ) -from PySide6.QtGui import QPainter, QColor, QFont, QPen, QPolygon +from PySide6.QtGui import QPainter, QColor, QFont, QPen, QPolygon, QTextLayout from PySide6.QtCore import ( Qt, QRect, @@ -127,6 +128,27 @@ class ListItemLeadingMarker: color: QColor | None = None +@dataclass(slots=True) +class PreparedRow: + """What a row is drawn from, read from its model once and kept until the model says its + rows changed (`MultilinePreviewItemDelegate.prepared_row`). + + A paint draws; it does not ask the model what the row is. Reading a row's roles, building + its fonts and the key of its text for every paint is the same work on a desktop and a + phone, and only the phone is slow enough to show it: a sidebar row that repainted for a + colour moving along its name entered 99 Python functions a paint (Toad's frame-work + count, 2026-11-22). What stays read at paint is what can change without the model + saying so: the view's own wrap default, a flash's colour, the option's state.""" + + scheme: object + object_state_path: object + leading_marker: "ListItemLeadingMarker | None" + wrap_mode: "PreviewWrapMode | None" + disclosure: bool + texts: dict[tuple[bool, int | None], PreparedTextLayout] = field(default_factory=dict) + """The row's laid-out text, by whether it is selected and the width it wraps to.""" + + class MultilinePreviewItemDelegate(QStyledItemDelegate): """Custom delegate to render multiline items with grey preview text. @@ -145,6 +167,14 @@ class MultilinePreviewItemDelegate(QStyledItemDelegate): TEXT_INSET_Y = 3 MINIMUM_ROW_HEIGHT = 29 DISCLOSURE_WIDTH = 16 + SELECTED = QStyle.StateFlag.State_Selected.value + KEPT_ROWS = 4096 + """How many rows' prepared state is kept; past it every row is dropped and read again.""" + # What changes how every row is drawn without the model saying so: the rows are read again. + REDRAWN_BY = frozenset({ + QEvent.Type.FontChange, QEvent.Type.PaletteChange, QEvent.Type.StyleChange, + QEvent.Type.EnabledChange, QEvent.Type.ApplicationFontChange, + }) def __init__( self, @@ -164,30 +194,120 @@ def __init__( manager: Flash-color provider that owns delegate paint acknowledgements """ super().__init__(parent) - self.name_color = name_color - self.preview_color = preview_color - self.selected_text_color = selected_text_color + self._rows: dict[tuple[int, int, int], PreparedRow] = {} + self._rows_model: object = None + # The index a row was last asked for by and that row: one paint or measure asks for + # its row several times with the same index object, which then costs a comparison. + self._asked: tuple[object, PreparedRow | None] = (None, None) + # The option a paint is drawing with and whether it is selected, while it paints. + self._painting: tuple[object, bool] = (None, False) + self._name_color = name_color + self._preview_color = preview_color + self._selected_text_color = selected_text_color self._manager = manager self._text_metric_cache = TextMetricCache() self._text_renderer = StyledTextRenderer(self._text_metric_cache) self._pressed_disclosure = QPersistentModelIndex() parent.viewport().installEventFilter(self) + # The view's own font, palette, style and enabled changes drop the kept rows + # (`REDRAWN_BY`). Under an application stylesheet a new font on the view is not + # passed on to its viewport as a change of the viewport's, so the view is watched. + parent.installEventFilter(self) # NOTE: Flash rendering moved to WindowFlashOverlay for O(1) performance + # The text colours are part of every row's laid-out text: a new colour reads the rows again. + + @property + def name_color(self) -> QColor: + return self._name_color + + @name_color.setter + def name_color(self, color: QColor) -> None: + self._name_color = color + self.forget_rows() + + @property + def preview_color(self) -> QColor: + return self._preview_color + + @preview_color.setter + def preview_color(self, color: QColor) -> None: + self._preview_color = color + self.forget_rows() + + @property + def selected_text_color(self) -> QColor: + return self._selected_text_color + + @selected_text_color.setter + def selected_text_color(self, color: QColor) -> None: + self._selected_text_color = color + self.forget_rows() + + def prepared_row(self, index) -> PreparedRow: + """The row at ``index``, as last read from its model.""" + asked, kept = self._asked + if asked is index: + return kept + model = index.model() + if model is not self._rows_model: + self._follow(model) + key = (index.row(), index.column(), index.internalId()) + row = self._rows.get(key) + if row is None: + if len(self._rows) >= self.KEPT_ROWS: + self._rows.clear() + row = self._rows[key] = self.prepare_row(index) + self._asked = (index, row) + return row + + def prepare_row(self, index) -> PreparedRow: + """Read from the model what a row is drawn from.""" + marker = index.data(LEADING_MARKER_ROLE) + return PreparedRow( + scheme=index.data(SCOPE_SCHEME_ROLE), + object_state_path=index.data(OBJECT_STATE_PATH_ROLE), + leading_marker=marker if isinstance(marker, ListItemLeadingMarker) else None, + wrap_mode=index.data(PREVIEW_WRAP_ROLE), + disclosure=PreviewWrapMode.available(self.parent(), index), + ) + + def forget_rows(self, *_changed) -> None: + """Every row is read from its model again at its next paint or measure. The model's + own change signals call this; so does anything else a row's drawing depends on.""" + self._rows.clear() + self._asked = (None, None) + + def _follow(self, model) -> None: + """Drop the kept rows whenever ``model`` says its rows or their data changed.""" + self.forget_rows() + self._rows_model = model + for changed in ( + model.dataChanged, model.rowsInserted, model.rowsRemoved, model.rowsMoved, + model.columnsInserted, model.columnsRemoved, model.layoutChanged, model.modelReset, + ): + changed.connect(self.forget_rows) + def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: """Paint the item with multiline support and flash behind text.""" + row = self.prepared_row(index) # Prepare a copy to let style draw backgrounds, hover, selection, borders, etc. opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) # A wrapped row owns one viewport-anchored paint frame for native style, # flash/background, marker and text, independent of other rows' overflow. - opt.rect = self._row_rect(option, index) + view = self.parent() + if view.wordWrap() if row.wrap_mode is None else row.wrap_mode.wrapped: + frame = QRect(option.rect) + frame.setLeft(0) + frame.setWidth(view.viewport().width()) + opt.rect = frame # Capture text and prevent default text draw opt.text = "" # Calculate border inset (used for background and flash) - scheme = index.data(SCOPE_SCHEME_ROLE) + scheme = row.scheme border_inset = 0 layers = None if isinstance(scheme, ScopeColorScheme): @@ -197,12 +317,13 @@ def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: content_rect = opt.rect.adjusted(border_inset, border_inset, -border_inset, -border_inset) # Scope-based background: match border colors (only when not selected) - is_selected = bool(option.state & QStyle.StateFlag.State_Selected) - if not is_selected: + is_selected = bool(option.state.value & self.SELECTED) + self._painting = (opt, is_selected) + if not is_selected and scheme is not None: self._paint_scope_background(painter, content_rect, scheme, layers) # Flash effect - drawn BEHIND text but inside borders - object_state_path = index.data(OBJECT_STATE_PATH_ROLE) + object_state_path = row.object_state_path painted_flash_alpha = None if object_state_path and self._manager is not None: flash_color = self._manager.get_flash_color_for_object_state_path(object_state_path) @@ -230,9 +351,9 @@ def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: # Now draw text manually with custom colors painter.save() - leading_marker = index.data(LEADING_MARKER_ROLE) + leading_marker = row.leading_marker text_rect = opt.rect - if isinstance(leading_marker, ListItemLeadingMarker): + if leading_marker is not None: self._paint_leading_marker( painter, text_rect, @@ -241,7 +362,7 @@ def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: ) try: painter.setClipRect(text_rect) - if self._has_disclosure(index): + if row.disclosure: disclosure = QStyleOptionViewItem(opt) disclosure.rect = self.disclosure_rect(opt, index) disclosure.state = QStyle.StateFlag.State_Children @@ -252,14 +373,19 @@ def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: self.parent().style().drawPrimitive( QStyle.PrimitiveElement.PE_IndicatorBranch, disclosure, painter, self.parent() ) + gutter = self.DISCLOSURE_WIDTH if row.disclosure else 0 + if leading_marker is not None: + gutter += get_scope_visual_config().LIST_ITEM_LEADING_MARKER_GUTTER_WIDTH_PX self._prepared_text(opt, index).paint( painter, QPointF( - text_rect.left() + self.TEXT_INSET_X + self._text_gutter(index), + text_rect.left() + self.TEXT_INSET_X + gutter, text_rect.top() + self.TEXT_INSET_Y, ), + self.text_inks(index), ) finally: + self._painting = (None, False) painter.restore() if scheme is not None: @@ -438,12 +564,12 @@ def _paint_border_layers(self, painter: QPainter, rect: QRect, scheme) -> None: painter.restore() def _marker_gutter(self, index) -> int: - if isinstance(index.data(LEADING_MARKER_ROLE), ListItemLeadingMarker): + if self.prepared_row(index).leading_marker is not None: return get_scope_visual_config().LIST_ITEM_LEADING_MARKER_GUTTER_WIDTH_PX return 0 def _has_disclosure(self, index: QModelIndex) -> bool: - return PreviewWrapMode.available(self.parent(), index) + return self.prepared_row(index).disclosure def _text_gutter(self, index: QModelIndex) -> int: return self._marker_gutter(index) + ( @@ -451,7 +577,10 @@ def _text_gutter(self, index: QModelIndex) -> int: ) def _row_wraps(self, index: QModelIndex) -> bool: - return PreviewWrapMode.for_index(self.parent(), index).wrapped + """`PreviewWrapMode.for_index`, from the kept row: its own choice, or the view's + default, which the view can change without its model saying so and is read now.""" + mode = self.prepared_row(index).wrap_mode + return self.parent().wordWrap() if mode is None else mode.wrapped def _row_rect(self, option: QStyleOptionViewItem, index: QModelIndex) -> QRect: """One row frame for native decoration, flash, content and disclosure hits.""" @@ -476,7 +605,12 @@ def disclosure_rect(self, option: QStyleOptionViewItem, index: QModelIndex) -> Q ) def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - """Consume disclosure clicks before QListView selection/drag/activation.""" + """Consume disclosure clicks before QListView selection/drag/activation. A change + of the view's font, palette, style or enabled state redraws every row from + another font or colour, so the kept rows are read again. The view and its viewport + are both watched for those; only the viewport's clicks are the disclosure's.""" + if event.type() in self.REDRAWN_BY: + self.forget_rows() if event.type() not in { QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonRelease, @@ -509,21 +643,41 @@ def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 PreviewWrapMode.toggle(view, index) return pressed.isValid() + def text_inks(self, index) -> Sequence[Sequence[QTextLayout.FormatRange]]: + """Format ranges drawn over a row's prepared paragraphs, one sequence for each leading + paragraph (`PreparedTextLayout.paint`): colour that moves from frame to frame, which + the prepared text is not laid out again for. None by default.""" + return () + def _prepared_text(self, option: QStyleOptionViewItem, index) -> PreparedTextLayout: - """Use identical fonts, field markers and available width in both passes.""" + """Use identical fonts, field markers and available width in both passes. The row's + text is laid out once for a selection state and a width, and kept with the row.""" + painting, selected = self._painting + if painting is not option: + selected = bool(option.state.value & self.SELECTED) + row = self.prepared_row(index) + width = None + view = self.parent() + if view.wordWrap() if row.wrap_mode is None else row.wrap_mode.wrapped: + width = max( + 1, + view.viewport().width() - self.TEXT_INSET_X * 2 - self._text_gutter(index), + ) + texts = row.texts + text = texts.get((selected, width)) + if text is None: + text = texts[(selected, width)] = self._laid_out_text(option, index, selected, width) + return text + + def _laid_out_text( + self, option: QStyleOptionViewItem, index, selected: bool, width: int | None + ) -> PreparedTextLayout: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) font = QFont(opt.font) font.setStrikeOut(bool(index.data(Qt.ItemDataRole.UserRole + 1))) font.setUnderline(False) - selected = bool(option.state & QStyle.StateFlag.State_Selected) layout = index.data(LAYOUT_ROLE) - width = None - if self._row_wraps(index): - width = max( - 1, - self.parent().viewport().width() - self.TEXT_INSET_X * 2 - self._text_gutter(index), - ) return self._text_renderer.prepare( layout if isinstance(layout, StyledTextLayout) else opt.text, TextPaintContext( diff --git a/src/pyqt_reactive/widgets/shared/list_item_text_rendering.py b/src/pyqt_reactive/widgets/shared/list_item_text_rendering.py index 1d047882..58356cbf 100644 --- a/src/pyqt_reactive/widgets/shared/list_item_text_rendering.py +++ b/src/pyqt_reactive/widgets/shared/list_item_text_rendering.py @@ -1,5 +1,6 @@ """One Qt text layout for painting and measuring styled list previews.""" +from collections.abc import Sequence from dataclasses import dataclass from math import ceil @@ -56,9 +57,18 @@ class PreparedTextLayout: size: QSize line_guides: tuple[PreparedLineGuide, ...] = () - def paint(self, painter: QPainter, origin: QPointF) -> None: - for paragraph in self.paragraphs: - paragraph.draw(painter, origin) + def paint( + self, + painter: QPainter, + origin: QPointF, + inks: Sequence[Sequence[QTextLayout.FormatRange]] = (), + ) -> None: + """Draw the paragraphs and their guides. ``inks`` holds, for each leading paragraph, + the format ranges drawn over that paragraph's own formats. They are applied as the + glyphs are drawn, so the text is not laid out again: a colour that changes on every + frame (a band moving along a name) costs a draw of text that is already shaped.""" + for number, paragraph in enumerate(self.paragraphs): + paragraph.draw(painter, origin, list(inks[number]) if number < len(inks) else []) for guide in self.line_guides: guide.paint(painter, origin) diff --git a/tests/test_list_preview_wrapping.py b/tests/test_list_preview_wrapping.py index c0e0b4f8..7e20dfc0 100644 --- a/tests/test_list_preview_wrapping.py +++ b/tests/test_list_preview_wrapping.py @@ -554,3 +554,91 @@ def test_manager_rebuild_reuses_row_owned_wrap_choice(qtbot, preview_list): updater.update(operations) assert view.item(1) is not first assert view.item(1).data(PREVIEW_WRAP_ROLE) is None + + +def test_a_row_is_drawn_with_ink_over_its_prepared_text_and_is_not_laid_out_again(qtbot): + """A delegate's `text_inks` colours part of a row as it is drawn. The prepared text is + the same object before and after, so the colour cost no layout.""" + from PySide6.QtGui import QImage, QPainter, QTextCharFormat, QTextLayout + + red = QColor(255, 0, 0) + + class Inked(MultilinePreviewItemDelegate): + span = (0, 0) + + def text_inks(self, index): + band = QTextLayout.FormatRange() + band.start, band.length = self.span[0], self.span[1] - self.span[0] + ink = QTextCharFormat() + ink.setForeground(red) + band.format = ink + return ([band],) + + view = ReorderableListWidget() + qtbot.addWidget(view) + delegate = Inked(QColor("black"), QColor("gray"), QColor("white"), parent=view) + view.setItemDelegate(delegate) + view.resize(380, 200) + view.addItem(QListWidgetItem("MMMMMMMMMMMMMMMMMMMM")) + view.show() + index = view.model().index(0, 0) + option = QStyleOptionViewItem() + option.initFrom(view) + option.rect = view.visualRect(index) + + def reds() -> list[int]: + image = QImage(view.viewport().size(), QImage.Format.Format_ARGB32) + image.fill(QColor("white")) + painter = QPainter(image) + delegate.paint(painter, option, index) + painter.end() + return [x for x in range(image.width()) + if any(image.pixelColor(x, y) == red for y in range(option.rect.top(), option.rect.bottom()))] + + prepared = delegate._prepared_text(option, index) + assert reds() == [] + delegate.span = (0, 3) + left = reds() + delegate.span = (10, 13) + right = reds() + assert left and right and max(left) < min(right) + assert delegate._prepared_text(option, index) is prepared + + +def test_a_row_is_read_from_its_model_once_until_the_model_says_it_changed(qtbot, preview_list): + """Painting and measuring a row again reads nothing from its model and lays nothing out; + a change of the row's data does both once more.""" + from PySide6.QtGui import QImage, QPainter + + view = preview_list + delegate = view.itemDelegate() + item = QListWidgetItem("first line\nsecond line") + view.addItem(item) + index = view.model().index(0, 0) + option = QStyleOptionViewItem() + option.initFrom(view) + option.rect = view.visualRect(index) + read, laid = [], [] + prepare_row, laid_out_text = delegate.prepare_row, delegate._laid_out_text + delegate.prepare_row = lambda index: (read.append(1), prepare_row(index))[1] + delegate._laid_out_text = lambda *args: (laid.append(1), laid_out_text(*args))[1] + delegate.forget_rows() + + def drawn() -> None: + image = QImage(view.viewport().size(), QImage.Format.Format_ARGB32) + painter = QPainter(image) + delegate.paint(painter, option, index) + painter.end() + delegate.sizeHint(option, index) + + drawn() + drawn() + drawn() + assert (len(read), len(laid)) == (1, 1) + item.setText("another line") + drawn() + drawn() + assert (len(read), len(laid)) == (2, 2) + delegate.name_color = QColor("blue") + drawn() + assert (len(read), len(laid)) == (3, 3)