Skip to content
Closed
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/motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions src/toad/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
LoadingStyle,
LeftColumnAlignment,
NavigationBarPosition,
NormalScrollbar,
NotificationPolicy,
PulseLoading,
SchemeName,
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 10 additions & 7 deletions src/toad/qt/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 = "<br>".join(f'{self.styled("─" * max(room.rule(group), 0), block.role)} '
f'<b>{self.title(group, block)}</b> '
f'{self.styled("─" * max(room.rule(group), 0), block.role)}'
for group in groups)
return f'<p align="center" style="white-space:pre">{rows}</p>'
colour = self.theme(RuleColour)
rule = f'<td valign="middle"><hr style="background-color:{colour};color:{colour}"/></td>'
rows = "".join(f'<tr>{rule}<td width="1" valign="middle" style="white-space:pre">'
f'&nbsp;<b>{self.title(group, block)}</b>&nbsp;</td>{rule}</tr>'
for group in groups)
return f'<table width="100%" cellspacing="0" cellpadding="0">{rows}</table>'

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)
Expand Down
143 changes: 143 additions & 0 deletions src/toad/qt/overlay_scrollbar.py
Original file line number Diff line number Diff line change
@@ -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
7 changes: 5 additions & 2 deletions src/toad/qt/view_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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()
Expand All @@ -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)
Expand Down
20 changes: 19 additions & 1 deletion src/toad/setting_choices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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

Expand Down
62 changes: 60 additions & 2 deletions tools/qt_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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]
Expand Down Expand Up @@ -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 "
Expand Down
2 changes: 2 additions & 0 deletions tools/qt_inherit_ratchet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading