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
3 changes: 3 additions & 0 deletions src/toad/client/line_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -382,6 +384,7 @@ class Divider(SharedStandaloneBlock):
"""

renders_inline: ClassVar[bool] = True
triggers_header_collapse: ClassVar[bool] = True

spans: tuple[Span, ...]
role: type[LineRole]
Expand Down
8 changes: 6 additions & 2 deletions src/toad/client/theme_tones.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
8 changes: 8 additions & 0 deletions src/toad/qt/client_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
65 changes: 61 additions & 4 deletions src/toad/qt/name_wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]))
Expand Down
7 changes: 2 additions & 5 deletions src/toad/sidebar_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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."""
Expand Down
56 changes: 56 additions & 0 deletions tests/model/test_android_perf_ux_arrivals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
2 changes: 1 addition & 1 deletion tools/frame_work_baseline.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"list_item_delegate.MultilinePreviewItemDelegate.paint": 69.3
"name_wave.QtNameWaveDelegate.paint": 37.7
}
12 changes: 5 additions & 7 deletions tools/qt_scroll_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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__":
Expand Down
Loading