From 2b66d73872841e5b48a4be068976df55477024ee Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 04:25:56 -0500 Subject: [PATCH] qt: header rules fill the row; the conversation scrollbar can float over the text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A message header's rule was a count of ─ characters beside the title, so its ends moved with the title's length and never met the row's edges. Qt now draws each side as a real line in its own cell (the theme's RuleColour), so every rule meets both edges whatever the title; the TUI keeps its cell rule. The Scrollbar setting declares, per member, the width it takes beside the text (`size`) and the width it draws over the text while the conversation moves (`overlay`). The new Transient member takes no width and shows a bar over the text while scrolling, faded out a second after; Hidden shows none. Qt floats the overlay over the viewport (OverlayScrollBar, handle in SurfaceHoverColour, fading on the app clock through SCROLLBAR_FADE); a terminal cannot draw over its text, so Textual shows `size` only and Transient is no bar there. The default is the platform's: Transient on Android, Normal elsewhere. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/motion.py | 3 + src/toad/preferences.py | 5 +- src/toad/qt/lines.py | 17 ++-- src/toad/qt/overlay_scrollbar.py | 143 +++++++++++++++++++++++++++++++ src/toad/qt/view_settings.py | 7 +- src/toad/setting_choices.py | 20 ++++- tools/qt_drive.py | 62 +++++++++++++- tools/qt_inherit_ratchet.py | 2 + 8 files changed, 244 insertions(+), 15 deletions(-) create mode 100644 src/toad/qt/overlay_scrollbar.py diff --git a/src/toad/motion.py b/src/toad/motion.py index 49a061725..d84e82d8c 100644 --- a/src/toad/motion.py +++ b/src/toad/motion.py @@ -25,6 +25,9 @@ # A row under the composer (the queue summary, the delivery controls) opens or closes its height # instead of appearing in one frame and pushing the history up. ROW_REVEAL = Transition(Amount, 0.0, 1.0, _TAB_DURATION, _TAB_FPS) +# A scrollbar drawn over the text while it moves fades away once it has been still a moment, +# rather than vanishing in one frame. +SCROLLBAR_FADE = Transition(Amount, 1.0, 0.0, 0.3, _TAB_FPS) def animations_enabled() -> bool: diff --git a/src/toad/preferences.py b/src/toad/preferences.py index 3923961e8..d4b5ba0c6 100644 --- a/src/toad/preferences.py +++ b/src/toad/preferences.py @@ -45,7 +45,6 @@ LoadingStyle, LeftColumnAlignment, NavigationBarPosition, - NormalScrollbar, NotificationPolicy, PulseLoading, SchemeName, @@ -109,10 +108,10 @@ class ViewUiSettings(SettingsDeclaration, scopes=(ViewSettingsOwner,)): """Place the conversation column on the left, in the center, or on the right.""" scrollbar: Annotated[ type[Scrollbar], - FieldLabel("Scrollbar size"), + FieldLabel("Scrollbar"), FamilyChoices(Scrollbar), effects.conversation_layout, - ] = NormalScrollbar + ] = Scrollbar.for_host() @dataclass(frozen=True) diff --git a/src/toad/qt/lines.py b/src/toad/qt/lines.py index 8765e6021..d86998ccd 100644 --- a/src/toad/qt/lines.py +++ b/src/toad/qt/lines.py @@ -19,7 +19,7 @@ from markdown_it import MarkdownIt from metaclass_registry.mro_dispatch import handles -from ui_theme.scheme import ColourScheme, ThemeColour +from ui_theme.scheme import ColourScheme, RuleColour, ThemeColour from toad.client.line_blocks import ( Body, @@ -200,17 +200,20 @@ def barred(self, text: str, bar: type[LineRole]) -> str: @handles(Divider) def divider(self, block: Divider) -> str: """Every row of the title flanked by rules filling the width, as Textual's divider does. - One paragraph so Qt adds no extra block gap between wrapped rows.""" + A terminal can only draw its rule in whole `─` cells; Qt draws each side as a real line + reaching the edge, so every rule spans the full width whatever the title's length. + The title's cell takes its content's width and the side cells share the rest.""" bold = QFont(self.font) bold.setBold(True) room = PixelRoom(QFontMetricsF(bold), self.width) groups = [row for group in DIVIDER_TIME.project_value(block.timestamp, block.spans, room) for row in room.wrapped(group)] - rows = "
".join(f'{self.styled("─" * max(room.rule(group), 0), block.role)} ' - f'{self.title(group, block)} ' - f'{self.styled("─" * max(room.rule(group), 0), block.role)}' - for group in groups) - return f'

{rows}

' + colour = self.theme(RuleColour) + rule = f'
' + rows = "".join(f'{rule}' + f' {self.title(group, block)} {rule}' + for group in groups) + return f'{rows}
' def title(self, spans: tuple[Span, ...], block: Divider) -> str: return "".join(self.span(span, span.link.heading_role(span.role, block.role)) for span in spans) diff --git a/src/toad/qt/overlay_scrollbar.py b/src/toad/qt/overlay_scrollbar.py new file mode 100644 index 000000000..349ad38d6 --- /dev/null +++ b/src/toad/qt/overlay_scrollbar.py @@ -0,0 +1,143 @@ +"""A scroll area's vertical bar drawn over its text while it moves (`Scrollbar.overlay`). + +A bar beside the text takes its width for good; this one floats over the viewport's right +edge only while the area scrolls, and fades out a moment after it goes still. It mirrors the +area's own bar (hidden, still the model of the position), so dragging it scrolls the area and +any scroll of the area, by wheel, key, finger or code, shows it. Once faded it is hidden, so +it never takes a tap meant for the text under it. +""" + +from __future__ import annotations + +from PySide6.QtCore import QEvent, QObject, QRect, Qt, QTimer +from PySide6.QtWidgets import QAbstractScrollArea, QGraphicsOpacityEffect, QScrollBar +from ui_theme.clock import AnimationClock +from ui_theme.scheme import SurfaceHoverColour + +from toad.motion import SCROLLBAR_FADE, TransitionTarget +from toad.qt.lines import QtLineRenderer +from toad.qt.widget_animation import WidgetAnimation + + +class ScrollbarFade(WidgetAnimation, TransitionTarget): + """The overlay bar fading out on the app's clock; it is hidden where the fade lands.""" + + def __init__(self, bar: OverlayScrollBar, clock: AnimationClock) -> None: + self.bar = bar + self.bind_widget(bar, clock) + self.start_transition(clock, SCROLLBAR_FADE) + + def apply_amount(self, amount: float) -> None: + self.bar.opacity.setOpacity(amount) + + def land(self) -> None: + self.bar.fade = None + self.bar.hide() + + +class OverlayScrollBar(QScrollBar): + """The overlay for one area; `follow` attaches it, or detaches it at width 0.""" + + STILL_MS = 1000 + """How long the area stays still before the bar fades.""" + + def __init__(self, area: QAbstractScrollArea, clock: AnimationClock, renderer: QtLineRenderer) -> None: + super().__init__(Qt.Orientation.Vertical, area) + self.area, self.clock, self.renderer = area, clock, renderer + self.source = area.verticalScrollBar() + self.thickness = 0 + self.fade: ScrollbarFade | None = None + self.opacity = QGraphicsOpacityEffect(self) + self.opacity.setOpacity(1.0) + self.setGraphicsEffect(self.opacity) + self.still = QTimer(self) + self.still.setSingleShot(True) + self.still.setInterval(self.STILL_MS) + self.still.timeout.connect(self.fade_out) + self.source.rangeChanged.connect(self.setRange) + self.source.valueChanged.connect(self.moved) + self.valueChanged.connect(self.source.setValue) + self.geometry_watch = _ViewportGeometry(self) + area.viewport().installEventFilter(self.geometry_watch) + renderer.themed(self, self.paint_colours) + self.hide() + + def paint_colours(self) -> None: + """Only the handle shows, a raised tier over whatever text it floats on; the track and + the arrows draw nothing.""" + handle = SurfaceHoverColour.rgb(self.renderer.scheme).hex + self.setStyleSheet( + "QScrollBar:vertical { background: transparent; margin: 0; border: none; }" + f"QScrollBar::handle:vertical {{ background: {handle}; border-radius: {max(1, self.thickness // 2)}px;" + " min-height: 24px; }" + "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; border: none; }" + "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: transparent; }") + + @classmethod + def follow(cls, area: QAbstractScrollArea, clock: AnimationClock, renderer: QtLineRenderer, + thickness: int) -> None: + """Draw ``area``'s bar over its text ``thickness`` pixels wide while it moves; at 0 + the area has no overlay. The area's own bar is then sized by its column setting.""" + bar = area.findChild(cls, options=Qt.FindChildOption.FindDirectChildrenOnly) + if bar is None: + if not thickness: + return + bar = cls(area, clock, renderer) + if bar.thickness != thickness: + bar.thickness = thickness + bar.paint_colours() + if not thickness: + bar.stop() + bar.hide() + else: + bar.place() + + def stop(self) -> None: + self.still.stop() + if self.fade is not None: + self.fade.animation.stop() + self.fade = None + + def moved(self, value: int) -> None: + """The area scrolled: show the bar at once at full strength and restart the wait.""" + self.setValue(value) + if not self.thickness: + return + self.stop() + self.opacity.setOpacity(1.0) + self.setPageStep(self.source.pageStep()) + self.setSingleStep(self.source.singleStep()) + self.place() + if self.maximum() > self.minimum(): + self.show() + self.raise_() + self.still.start() + + def fade_out(self) -> None: + """Still long enough: fade, unless the reader is holding or pointing at the bar.""" + if self.isSliderDown() or self.underMouse(): + self.still.start() + return + if self.clock.enabled: + self.fade = ScrollbarFade(self, self.clock) + else: + self.hide() + + def place(self) -> None: + """Over the right edge of the viewport, its full height.""" + viewport = self.area.viewport().geometry() + self.setGeometry(QRect(viewport.right() + 1 - self.thickness, viewport.top(), + self.thickness, viewport.height())) + + +class _ViewportGeometry(QObject): + """Keeps the overlay over the viewport when the viewport is resized or moved.""" + + def __init__(self, bar: OverlayScrollBar) -> None: + super().__init__(bar) + self.bar = bar + + def eventFilter(self, watched, event) -> bool: # type: ignore[override] + if event.type() in (QEvent.Type.Resize, QEvent.Type.Move) and self.bar.thickness: + self.bar.place() + return False diff --git a/src/toad/qt/view_settings.py b/src/toad/qt/view_settings.py index 1f2ac6e85..290832db5 100644 --- a/src/toad/qt/view_settings.py +++ b/src/toad/qt/view_settings.py @@ -11,6 +11,7 @@ from PySide6.QtWidgets import QWidget from toad.client.view_layout import ConversationColumn, LayoutFollower +from toad.qt.overlay_scrollbar import OverlayScrollBar def capability_widgets(root: QWidget, widget_type: type) -> list: @@ -26,8 +27,8 @@ def settings_widgets(self, widget_type): def apply_layout_preferences(self) -> None: """The conversation takes the column's width (all of it with the column off), set - where the column alignment puts it; the transcript's scrollbar is the setting's cells - wide.""" + where the column alignment puts it; the transcript's scrollbar takes the setting's + cells beside the text, and draws its `overlay` cells over the text while it moves.""" ui = self.configuration_state.fields.ui cell = self.fontMetrics().averageCharWidth() width = self.width() @@ -38,6 +39,8 @@ def apply_layout_preferences(self) -> None: self.layout().setContentsMargins(left, margins.top(), width - column - left, margins.bottom()) bar = self.messages.verticalScrollBar() bar.setFixedWidth(self.scrollbar_cells(ui) * cell) + OverlayScrollBar.follow(self.messages, self.messages.animation_clock, self.messages.rows.app_renderer, + ui.scrollbar.overlay * cell) def showEvent(self, event) -> None: # type: ignore[override] super().showEvent(event) diff --git a/src/toad/setting_choices.py b/src/toad/setting_choices.py index 848d755c1..9ff99fbcf 100644 --- a/src/toad/setting_choices.py +++ b/src/toad/setting_choices.py @@ -186,9 +186,20 @@ def enabled(cls, focused: bool) -> bool: class Scrollbar(DeclaredChoice, affix="Scrollbar"): - """The conversation's vertical scrollbar width, in cells, declared once by each member.""" + """The conversation's vertical scrollbar, declared once by each member: `size` is the + width it takes beside the text, in cells; `overlay` is the width it draws over the text + while the conversation moves, gone a moment after. A terminal cannot draw over its text, + so Textual shows only `size`; Qt shows both.""" size: ClassVar[int] + overlay: ClassVar[int] = 0 + + @classmethod + def for_host(cls) -> type[Scrollbar]: + """The platform's default: a touch platform scrolls by finger, so its bar only shows + while the conversation moves and leaves the text its whole width; on a desktop the + bar stays beside the text to be grabbed.""" + return host.select({"android": TransientScrollbar, "*": NormalScrollbar}) class NormalScrollbar(Scrollbar): @@ -199,6 +210,13 @@ class ThinScrollbar(Scrollbar): size = 1 +class TransientScrollbar(Scrollbar): + """Drawn over the text while it scrolls, then faded out; it takes no width.""" + + size = 0 + overlay = 1 + + class HiddenScrollbar(Scrollbar): size = 0 diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 784514eec..d7258632e 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -26,7 +26,7 @@ import qasync from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt -from PySide6.QtGui import QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent +from PySide6.QtGui import QImage, QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent, QPainter from PySide6.QtTest import QTest from PySide6.QtWidgets import QAbstractButton, QAbstractScrollArea, QDialog, QLabel, QScroller, QStyleOptionViewItem, QApplication, QPushButton, QWidget @@ -78,7 +78,7 @@ from toad.qt.opening_view import QtOpeningSessionView from toad.thread_sidebar_declarations import panel_specs_for_view from toad.client.bus_submission import ConversationSubmission -from toad.setting_choices import CenterColumnAlignment +from toad.setting_choices import CenterColumnAlignment, HiddenScrollbar, TransientScrollbar from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle from toad.client.input_modality import KeyboardInput, TouchInput from toad.qt.float_layer import QtNoticeCard @@ -88,6 +88,7 @@ from toad.core.events import TextAgentFail, UnsupportedResumeAgentFail from toad.live_output import ResponseStream, ThoughtStream from toad.qt.history import HistoryRows +from toad.qt.overlay_scrollbar import OverlayScrollBar from toad.qt.live_turn import QtLiveFragment PROJECT = Path(__file__).resolve().parents[1] @@ -684,6 +685,63 @@ async def run(self) -> None: self.report("20-end", **self.rows()) +class HeaderRuleScenario(Scenario): + summary = ("open #comms at phone size; for each message header shown, report where its rule's " + "pixels start and end against the row width and the title's length; then the " + "conversation scrollbar Transient: report the viewport width and the bar over the " + "text while scrolling and gone once still; then Hidden") + + def rule_extent(self, header, width: int) -> tuple[int, int]: + """The leftmost and rightmost drawn pixel of the header laid out at ``width``.""" + window = self.page.messages + document = window.rows.header_document(header, window.font(), width) + image = QImage(width, max(1, int(document.size().height())), QImage.Format.Format_ARGB32) + image.fill(Qt.GlobalColor.transparent) + painter = QPainter(image) + document.drawContents(painter) + painter.end() + drawn = [x for x in range(width) if any(image.pixelColor(x, y).alpha() for y in range(image.height()))] + return (drawn[0], drawn[-1]) if drawn else (-1, -1) + + def bar(self) -> dict[str, object]: + window = self.page.messages + overlay = window.findChild(OverlayScrollBar) + return dict(viewport=window.viewport().width(), bar_beside=window.verticalScrollBar().width(), + overlay=None if overlay is None else (overlay.isVisible(), round(overlay.opacity.opacity(), 2), + overlay.geometry().getRect())) + + async def run(self) -> None: + app = self.app + app.resize(412, 915) + await self.open_named(os.environ.get("HEADER_TARGET", "#comms")) + window = self.page.messages + width = window.viewport().width() - 8 + headers = [fragment.sticky_header(len(fragment.line_blocks) - 1, 1)[-1] + for fragment in window.model_rows.fragments + if fragment.line_blocks and fragment.sticky_header(len(fragment.line_blocks) - 1, 1)] + seen: dict[int, tuple] = {} + for header in headers: + title = "".join(span.text for span in header.spans) + seen.setdefault(len(title), (title, *self.rule_extent(header, width))) + for length, (title, left, right) in sorted(seen.items())[:8]: + print(f"rule: width={width} title_len={length} left={left} right={right} title={title[:40]!r}", + flush=True) + self.report("1-headers", headers=len(headers), **self.bar()) + app.saved_settings.set(SETTINGS.ui.scrollbar, TransientScrollbar) + await asyncio.sleep(0.5) + self.report("2-transient-idle", **self.bar()) + window.scroll_y = max(0, window.scroll_y - window.viewport().height()) + await asyncio.sleep(0.15) + self.report("3-transient-scrolling", **self.bar()) + await asyncio.sleep(2.0) + self.report("4-transient-still", **self.bar()) + app.saved_settings.set(SETTINGS.ui.scrollbar, HiddenScrollbar) + await asyncio.sleep(0.5) + window.scroll_y = max(0, window.scroll_y - window.viewport().height()) + await asyncio.sleep(0.15) + self.report("5-hidden-scrolling", **self.bar()) + + class StickyScenario(Scenario): summary = ("open STICKY_TARGET (#comms by default); scroll into the middle of its tallest message " "and report the pinned header over the top row, then put that message's header on the " diff --git a/tools/qt_inherit_ratchet.py b/tools/qt_inherit_ratchet.py index 7e5cfcb26..cf6f425c8 100644 --- a/tools/qt_inherit_ratchet.py +++ b/tools/qt_inherit_ratchet.py @@ -98,6 +98,8 @@ } QT_ONLY = { + 'toad.qt.overlay_scrollbar.OverlayScrollBar': "a QScrollBar floated over a QAbstractScrollArea's viewport, mirroring the area's hidden bar: a terminal cannot draw over its text, so Textual shows `Scrollbar.size` only; the shared fact is `Scrollbar.overlay`", + 'toad.qt.overlay_scrollbar._ViewportGeometry': "an event filter keeping that overlay over the viewport on QEvent.Resize/Move; Textual has no floating child to place", 'toad.qt.widget_animation.WidgetAnimation': "a clock target's life bound to its Qt widget's C++ lifetime (destroyed signal, shiboken validity); a Textual widget is a Python object the clock can always ask", 'toad.qt.history.ArrivalFade': "a burst's rows painted at the ARRIVAL cascade's frame as QPainter opacity; Textual paints the same frame into its strips (TranscriptHistory.arrivals_began), and both read the cascade from toad.frame_presentation", 'toad.qt.action_shortcuts.BoundAction': "a live QShortcut and the action it answers: Qt fires neither of two shortcuts sharing a key (activatedAmbiguously), so ActionKeys keeps each to apply the declared binding order; Textual walks its binding chain itself",