diff --git a/src/toad/client/line_blocks.py b/src/toad/client/line_blocks.py index f9c4e75f1..5c50a73c6 100644 --- a/src/toad/client/line_blocks.py +++ b/src/toad/client/line_blocks.py @@ -347,6 +347,8 @@ class LineBlock: renders_inline: ClassVar[bool] = False """Lightweight non-Markdown blocks (headers, single-line summaries, gaps) can render directly in-process on interactive collapse/toggle without a worker-pool round-trip.""" + triggers_header_collapse: ClassVar[bool] = False + """Whether tapping this block toggles the enclosing message's collapse link.""" @property def retained_bytes(self) -> int: @@ -382,6 +384,7 @@ class Divider(SharedStandaloneBlock): """ renders_inline: ClassVar[bool] = True + triggers_header_collapse: ClassVar[bool] = True spans: tuple[Span, ...] role: type[LineRole] diff --git a/src/toad/client/theme_tones.py b/src/toad/client/theme_tones.py index 388f10f4e..a34d765ef 100644 --- a/src/toad/client/theme_tones.py +++ b/src/toad/client/theme_tones.py @@ -48,14 +48,18 @@ def resolve_rgb(cls, read: Callable[[type[ThemeColour]], Rgb]) -> Rgb: return SidebarToneColour.resolve_rgb(read).blend(read(cls.hue), cls.amount) -class ChannelRowToneColour(HueToneColour): +class ChannelRowTone(HueToneColour): + """Alternating sidebar channel row surfaces stepped toward the theme hue.""" + + +class ChannelRowToneColour(ChannelRowTone): """A channel row of the channel list.""" name = "tone-channel-row" amount = 0.13 -class ChannelAlternateRowToneColour(HueToneColour): +class ChannelAlternateRowToneColour(ChannelRowTone): """Every other channel row, one more step toward the hue.""" name = "tone-channel-row-alternate" diff --git a/src/toad/qt/client_start.py b/src/toad/qt/client_start.py index 94585908a..4f18c6be0 100644 --- a/src/toad/qt/client_start.py +++ b/src/toad/qt/client_start.py @@ -114,6 +114,14 @@ def _add_callback(self, handle, delay: float = 0): def _drain_ready(self) -> None: self._ready_armed = False + if asyncio.current_task(self) is not None: + # Re-entrant QApplication.processEvents() or modal exec() inside a running + # asyncio Task: defer ready callbacks until the outer Task yields, otherwise + # stepping another Task raises RuntimeError and drops its wakeup handle. + if self._ready and not self.is_closed(): + self._ready_armed = True + self._ready_timer.start() + return ready = self._ready deadline = monotonic() + self._DRAIN_BUDGET_SECONDS passes = 0 diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 40d7c6a6c..d83cb1345 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -1730,7 +1730,7 @@ def _header_collapse_at(self, row: int, point: QPoint) -> FragmentCollapse | Non width = self.rows.layout_width(rect.width()) block_index, _line = self.rows.block_row(fragment, self.font(), width, y_in_row) blocks = fragment.line_blocks - if block_index < len(blocks) and isinstance(blocks[block_index], Divider): + if block_index < len(blocks) and blocks[block_index].triggers_header_collapse: return collapse return None diff --git a/src/toad/qt/name_wave.py b/src/toad/qt/name_wave.py index e2186eb98..a6ff6ab58 100644 --- a/src/toad/qt/name_wave.py +++ b/src/toad/qt/name_wave.py @@ -10,7 +10,7 @@ from PySide6.QtCore import QEvent, QPointF, QRect, QSize, Qt from PySide6.QtGui import QColor, QFont, QImage, QPainter, QPixmap, QTextCharFormat, QTextLayout -from PySide6.QtWidgets import QHBoxLayout, QLabel, QStyle, QStyleOptionTab, QStylePainter, QTabBar, QToolButton, QWidget +from PySide6.QtWidgets import QHBoxLayout, QLabel, QStyle, QStyleOptionTab, QStyleOptionViewItem, QStylePainter, QTabBar, QToolButton, QWidget from pyqt_reactive.widgets.shared.list_item_delegate import MultilinePreviewItemDelegate from pyqt_reactive.widgets.shared.list_item_text_rendering import PreparedTextLayout from pyqt_reactive.widgets.shared.tear_off_tab_widget import TearOffTabBar @@ -115,22 +115,79 @@ def __init__(self, accent: QColor, *args) -> None: # font or width changes, and a changed one is another object. self.bold: dict[int, tuple[PreparedTextLayout, PreparedTextLayout, int]] = {} self._banded_prepared: dict[tuple[int, int, int], tuple[PreparedTextLayout, PreparedTextLayout]] = {} + self._row_images: dict[tuple[int, tuple[int, int] | None, int, int, int, bool, float], tuple[object, QImage]] = {} + self._active_wave: tuple[object, tuple[int, int] | None] | None = None def _set_wave_accent(self, accent: QColor) -> None: super()._set_wave_accent(accent) self._banded_prepared.clear() + self._row_images.clear() + + def forget_rows(self, *_changed) -> None: + self._row_images.clear() + super().forget_rows(*_changed) + + def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: + row = self._rows.get((index.row(), index.column(), index.internalId())) + if row is None or index.model() is not self._rows_model: + row = self.prepared_row(index) + if row.object_state_path and self._manager is not None: + super().paint(painter, option, index) + return + view = self.parent() + wraps = view.wordWrap() if row.wrap_mode is None else row.wrap_mode.wrapped + frame = QRect(option.rect) + if wraps: + frame.setLeft(0) + frame.setWidth(view.viewport().width()) + width, height = frame.width(), frame.height() + if width <= 0 or height <= 0: + return + item = view.itemFromIndex(index) + running = item is not None and item.wave_running() + span = item.painted_span if running else None + dpr = painter.device().devicePixelRatioF() + key = (id(row), span, width, height, option.state._value_, wraps, dpr) + cached = self._row_images.get(key) + if cached is not None and cached[0] is row: + painter.drawImage(frame.topLeft(), cached[1]) + return + if len(self._row_images) >= self.BANDED_KEPT: + self._row_images.clear() + image = QImage( + max(1, round(width * dpr)), + max(1, round(height * dpr)), + QImage.Format.Format_ARGB32_Premultiplied, + ) + image.setDevicePixelRatio(dpr) + image.fill(Qt.GlobalColor.transparent) + local_option = QStyleOptionViewItem(option) + local_option.rect = QRect(0, 0, width, height) + local_painter = QPainter(image) + self._active_wave = (running, span) + try: + super().paint(local_painter, local_option, index) + finally: + self._active_wave = None + local_painter.end() + self._row_images[key] = (row, image) + painter.drawImage(frame.topLeft(), image) def _prepared_text(self, option, index) -> PreparedTextLayout: prepared = super()._prepared_text(option, index) - item = self.parent().itemFromIndex(index) - if item is None or not item.wave_running(): + if self._active_wave is not None: + running, span = self._active_wave + else: + item = self.parent().itemFromIndex(index) + running = item is not None and item.wave_running() + span = item.painted_span if running else None + if not running: return prepared pid = id(prepared) kept = self.bold.get(pid) if kept is None or kept[0] is not prepared: kept = self.bold_titled(prepared) titled, length = kept[1], kept[2] - span = item.painted_span if span is None: return titled start, end = min(length, max(0, span[0])), min(length, max(0, span[1])) diff --git a/src/toad/sidebar_rows.py b/src/toad/sidebar_rows.py index 7b79c2777..db6ed7554 100644 --- a/src/toad/sidebar_rows.py +++ b/src/toad/sidebar_rows.py @@ -19,7 +19,7 @@ from ui_theme.scheme import AlternateRowToneColour, SidebarToneColour, ThemeColour from toad.client.sidebar_lines import DetailedLine -from toad.client.theme_tones import ChannelAlternateRowToneColour, ChannelRowToneColour +from toad.client.theme_tones import ChannelRowTone from toad.setting_choices import UnreadCount @@ -82,10 +82,7 @@ class ChannelLineText: class ChannelRowFace: """A channel's line in a sidebar list.""" - row_tones: ClassVar[tuple[type[ThemeColour], type[ThemeColour]]] = ( - ChannelRowToneColour, - ChannelAlternateRowToneColour, - ) + row_tones: ClassVar[tuple[type[ThemeColour], ...]] = tuple(ChannelRowTone.__subclasses__()) def present_channel(self, channel: ChannelRowModel, *, counts: type[UnreadCount]) -> None: """`counts` is the reader's unread-count setting, which says how the badge reads.""" diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 074f42079..b827ba355 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2535,3 +2535,59 @@ def mark_visible_after_paint(self): assert owner._painted_reads == {} assert owner.marked == 0 assert "retain_painted" in EvidencedFragment.__dict__ + + +def test_coalesced_loop_defers_drain_during_reentrant_process_events(monkeypatch): + """Re-entrant QApplication.processEvents() inside an asyncio Task must defer + CoalescedQEventLoop._drain_ready instead of stepping another Task and dropping its wakeup.""" + import asyncio + from PySide6.QtCore import QEventLoop + from toad.qt.client_start import CoalescedQEventLoop + + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + app.setQuitOnLastWindowClosed(False) + loop = CoalescedQEventLoop(app) + errors: list[dict] = [] + loop.set_exception_handler(lambda _loop, ctx: errors.append(ctx)) + try: + async def drive() -> bool: + sibling_done = False + + async def sibling() -> None: + nonlocal sibling_done + sibling_done = True + + task = asyncio.create_task(sibling()) + # Trigger Qt timer delivery synchronously while `drive` is still active on the stack. + app.processEvents(QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) + await task + return sibling_done + + assert loop.run_until_complete(drive()) is True + assert errors == [] + finally: + loop.close() + + +def test_line_block_triggers_header_collapse_and_channel_row_tones(): + """Divider declares triggers_header_collapse=True (replacing isinstance checks in QtHistoryWindow), + and ChannelRowFace.row_tones derives from ChannelRowTone.__subclasses__().""" + from toad.client.line_blocks import Body, Divider, Gap, LineBlock, Summary + from toad.client.theme_tones import ( + ChannelAlternateRowToneColour, + ChannelRowTone, + ChannelRowToneColour, + SidebarToggleToneColour, + ) + from toad.sidebar_rows import ChannelRowFace + + assert LineBlock.triggers_header_collapse is False + assert Divider.triggers_header_collapse is True + assert Summary.triggers_header_collapse is False + assert Gap.triggers_header_collapse is False + assert Body.triggers_header_collapse is False + assert issubclass(ChannelRowToneColour, ChannelRowTone) + assert issubclass(ChannelAlternateRowToneColour, ChannelRowTone) + assert not issubclass(SidebarToggleToneColour, ChannelRowTone) + assert ChannelRowFace.row_tones == (ChannelRowToneColour, ChannelAlternateRowToneColour) diff --git a/tools/frame_work_baseline.json b/tools/frame_work_baseline.json index dcbd95c1e..c0e5273e6 100644 --- a/tools/frame_work_baseline.json +++ b/tools/frame_work_baseline.json @@ -1,3 +1,3 @@ { - "list_item_delegate.MultilinePreviewItemDelegate.paint": 69.3 + "name_wave.QtNameWaveDelegate.paint": 37.7 } diff --git a/tools/qt_scroll_profile.py b/tools/qt_scroll_profile.py index e9e4e344e..6910b2b36 100644 --- a/tools/qt_scroll_profile.py +++ b/tools/qt_scroll_profile.py @@ -39,7 +39,7 @@ from agent_comms.projects.checkouts import Checkout from toad.client.connection import RemoteCoreConnection from toad.client.history import WirePageBuffer -from toad.qt.client_start import open_app +from toad.qt.client_start import open_app, run_qt_loop from toad.qt.glyph_fonts import install_glyph_fonts from toad.qt.theme import current_scheme @@ -269,19 +269,17 @@ async def run(profile: Path, out: Path, do_profile: bool) -> None: finally: app.close() await app.close_client() - current = asyncio.current_task() - for task in asyncio.all_tasks(): - if task is not current and not task.done(): - task.cancel() - QApplication.quit() def main(arguments: list[str]) -> None: args = [a for a in arguments[1:] if not a.startswith("--")] if len(args) != 2: raise SystemExit(f"usage: {arguments[0]} PROFILE OUTDIR [--profile]") + for variable, folder in (("XDG_CONFIG_HOME", "config"), ("XDG_STATE_HOME", "state")): + os.environ[variable] = str((Path(args[1]) / folder).resolve()) + Path(os.environ[variable]).mkdir(parents=True, exist_ok=True) install_glyph_fonts(QApplication(arguments[:1])) # the entry's splash registers them; this profile has none - qasync.run(run(Path(args[0]), Path(args[1]), "--profile" in arguments)) + run_qt_loop(run(Path(args[0]), Path(args[1]), "--profile" in arguments)) if __name__ == "__main__":