diff --git a/src/toad/app.py b/src/toad/app.py index 26d6f8e49..47339e85c 100644 --- a/src/toad/app.py +++ b/src/toad/app.py @@ -4,7 +4,6 @@ import os import signal import sys -from enum import IntEnum from functools import cached_property from inspect import isabstract from pathlib import Path @@ -23,7 +22,6 @@ from rich.console import RenderableType from textual import events, on from textual.await_complete import AwaitComplete -from textual.css.scalar import Scalar, Unit from textual.notifications import Notify from textual.reactive import Required, var from textual.signal import Signal @@ -32,6 +30,7 @@ from textual.widgets._footer import KeyGroup from textual.widgets.markdown import Markdown +from toad.screen_width import ScreenWidth from toad.app_core import CorePrewarm from toad.application_actions import ApplicationCommands from toad.application_outcome import ApplicationOutcome, Ended, Succeeded @@ -112,21 +111,6 @@ class ApplicationNotRunningError(RuntimeError): """The application has no event loop to accept cross-thread work.""" -class ScreenWidth(IntEnum): - """Native sizing modes; legacy breakpoint classes are derived from them.""" - - side_panel_width: Scalar | None - - def __new__(cls, minimum_width: int, side_panel_width: Scalar | None): - mode = int.__new__(cls, minimum_width) - mode._value_ = minimum_width - mode.side_panel_width = side_panel_width - return mode - - NARROW = (0, None) - WIDE = (100, Scalar(50, Unit.PERCENT, Unit.WIDTH)) - - class ToadApp(DeclaredWidgetActions, WorkspaceSessionShutdown, WorkspaceHost, ClientApplication, CorePrewarm, Transfers, HostsNeovim, actions=(ApplicationAction,), inherit_bindings=False): """The top level app.""" diff --git a/src/toad/client/application_actions.py b/src/toad/client/application_actions.py index d5d2a42e2..5bf4f1738 100644 --- a/src/toad/client/application_actions.py +++ b/src/toad/client/application_actions.py @@ -256,6 +256,14 @@ def menu(cls, app: ClientApplication) -> tuple[tuple[ApplicationAction, str], .. for command in member.offered(app)) + +class OpensWindow: + """An application action whose `apply` opens a window over the app: Settings, the team + board, the keymap, a transfer, the bus switcher. Each frontend presents every such window + through its one presentation owner (Qt's `PresentedWindow`), so the windows a reader can + open are this family's members, read wherever all of them must be checked.""" + + # Declaration order is the order of the menu and the palette. class NewSessionAction(ApplicationAction): """Start this launch's session: its attached agent's, or a native thread.""" @@ -300,7 +308,7 @@ async def apply(self, app: ClientApplication) -> None: app.session_navigation.direct_messages() -class OpenBusAction(ApplicationAction): +class OpenBusAction(OpensWindow, ApplicationAction): """Connect to this machine's bus or choose another machine.""" title = "Switch bus (local or remote)" @@ -311,7 +319,7 @@ async def apply(self, app: ClientApplication) -> None: app.open_bus_switcher() -class SettingsAction(ApplicationAction): +class SettingsAction(OpensWindow, ApplicationAction): """Edit persistent application preferences.""" keys = {TextEntryMode: ("ctrl+comma",)} @@ -321,7 +329,7 @@ async def apply(self, app: ClientApplication) -> None: await app.edit_settings() -class TeamAction(ApplicationAction, declared_name="team"): +class TeamAction(OpensWindow, ApplicationAction, declared_name="team"): """Open the live team board, including teammates' orders and original evidence.""" keys = {TextEntryMode: ("f2",)} @@ -331,7 +339,7 @@ async def apply(self, app: ClientApplication) -> None: await app.open_team_board() -class KeymapAction(ApplicationAction): +class KeymapAction(OpensWindow, ApplicationAction): """Browse keyboard shortcuts and change their keys for each editing mode.""" keys = {TextEntryMode: ("f1",)} @@ -341,7 +349,7 @@ async def apply(self, app: ClientApplication) -> None: await app.open_keymap_browser() -class TransferMenuAction(ApplicationAction): +class TransferMenuAction(OpensWindow, ApplicationAction): """Export wire history or import a thread through Core.""" show = True diff --git a/src/toad/client/bus_submission.py b/src/toad/client/bus_submission.py index 765d843e4..e8560ee79 100644 --- a/src/toad/client/bus_submission.py +++ b/src/toad/client/bus_submission.py @@ -33,6 +33,7 @@ from toad.client.prompt_composer import PromptComposer from toad.client.submission import ( BusDestination, + ComposeAccess, MessageDestination, SubmissionOwner, SubmissionStart, @@ -79,8 +80,9 @@ def delivery_unknown(self, description: str, draft: SubmittedText) -> None: self.show_send_failure(self.unknown_notice(description)) @abstractmethod - async def refresh_composer(self, read_only: bool) -> None: - """Draw compose from the caller's Core answer.""" + async def refresh_composer(self, access: ComposeAccess) -> None: + """Draw compose from the caller's Core answer: held or open, and whether it offers + files.""" @abstractmethod def draws_user_message(self, reference: MessageReference) -> bool: ... @@ -313,11 +315,14 @@ async def deliver(self) -> DeliveryOutcome: try: await self.after.wait() observed = await preparation.run_thread(access.observing, destination.root) - read_only = await preparation.run_thread(destination.conversation.read_only, observed.core) - await view.refresh_composer(read_only) - if read_only: + compose = await preparation.run_thread(destination.conversation.compose_access, observed.core) + await view.refresh_composer(compose) + if compose.read_only: view.delivery_refused(MessageDestination.read_only_reason, draft) return RefusedMessage() + if compose.refuses(draft): + view.delivery_refused(compose.files_refused_reason, draft) + return RefusedMessage() route_current = await preparation.run_thread(lambda: access.current(destination.root)) if not route_current or not self.current: raise HumanSendRefusedError(RelationViolationError("Message route changed; reopen this view")) diff --git a/src/toad/client/fragments.py b/src/toad/client/fragments.py index 183dfddd5..3a37751a4 100644 --- a/src/toad/client/fragments.py +++ b/src/toad/client/fragments.py @@ -2,6 +2,7 @@ shows and its line blocks. Each frontend adds how it draws and measures those blocks.""" from abc import ABC, abstractmethod +from collections.abc import Iterable from dataclasses import dataclass, field, replace from functools import cached_property from typing import ClassVar @@ -299,6 +300,11 @@ def source_identity(self) -> EventSourceKey | ToolCallId: def key(self) -> FragmentKey: return FragmentKey(self.source_identity, self.part_position.index) + def message_head(self, fragments: Iterable["HistoryFragment"]) -> "HistoryFragment": + """The first part of this fragment's message among ``fragments`` in order: where a + tap on any of its parts brings the reader (both frontends' clicked-head reveal).""" + return next((part for part in fragments if part.source_identity == self.source_identity), self) + @property def pinned_dividers(self) -> tuple[Divider, ...]: """The header a top row in this fragment pins, and an arrival burst stacks: none for a diff --git a/src/toad/client/history.py b/src/toad/client/history.py index c69b146af..2a926436d 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -59,6 +59,7 @@ from toad.client.source_resumption import ResumesSource from toad.client.submission import ( BusDestination, + ComposeAccess, SubmissionOwner, SubmissionStart, SubmittedText, @@ -617,8 +618,8 @@ async def mark_page(self, page: MessagePage) -> None: await asyncio.to_thread( self.loader.core.call, CommsMarkPageReadTool(page=page, worktree=self.loader.project)) - async def read_only(self) -> bool: - return await self.runtime.run_thread(self.loader.conversation.read_only, self.loader.core) + async def compose_access(self) -> ComposeAccess: + return await self.runtime.run_thread(self.loader.conversation.compose_access, self.loader.core) async def update_mentions(self, view: WireView) -> None: await self.loader.conversation.update_mentions(view, self.loader) diff --git a/src/toad/client/message_files.py b/src/toad/client/message_files.py index d9030a0d7..f59f633ab 100644 --- a/src/toad/client/message_files.py +++ b/src/toad/client/message_files.py @@ -28,6 +28,7 @@ from toad.client.input_decision import InputAccepted, InputDecision from toad.client.message_file_links import file_size from toad.client.prompt_composer import PromptComposer +from toad.client.submission import ComposeAccess class FilePicker(DeclaredChoice, affix="FilePicker"): @@ -88,6 +89,9 @@ class MessagePromptComposer(PromptComposer): sends with the text.""" attached_files: tuple[FileUpload, ...] = () + takes_files: bool = True + """Whether this composer's bus takes files, as its Core last answered (`ComposeAccess`); + open until it answers, as every bus that takes files is.""" @property def input_decision(self) -> InputDecision: @@ -98,8 +102,21 @@ def input_decision(self) -> InputDecision: def prompt_symbol(self, text: str, shell_mode: bool) -> str: return self.settings.ui.input.agent_symbol + def offer_files(self, takes_files: bool) -> None: + if self.takes_files != takes_files: + self.takes_files = takes_files + self.show_files_offered() + + @abstractmethod + def show_files_offered(self) -> None: + """Offer Attach only while `takes_files`.""" + def attach_file(self) -> None: - """The attach action: the picker this composer's settings name opens.""" + """The attach action: the picker this composer's settings name opens, on a bus that + takes files. A key pressed before the bus answered meets the reason instead.""" + if not self.takes_files: + self.show_failure(ComposeAccess.files_refused_reason) + return self.settings.ui.input.file_picker.open(self) @abstractmethod diff --git a/src/toad/client/prepared_pages.py b/src/toad/client/prepared_pages.py index 41acf84d5..c1d7c4811 100644 --- a/src/toad/client/prepared_pages.py +++ b/src/toad/client/prepared_pages.py @@ -31,7 +31,7 @@ from toad.client.history_reads import NothingToRead, PaintedRead from toad.client.history_state import DEFERRED_WORK, SourceWork from toad.client.input_decision import TranscriptNotReady -from toad.client.submission import SubmissionOwner, SubmissionStart, SubmittedText +from toad.client.submission import ComposeAccess, SubmissionOwner, SubmissionStart, SubmittedText from toad.commit_claims import RETAINED_SOURCE_CLAIM, CommitClaim, RetainedBlockClaim from toad.status_thread import NoStatusThread from toad.work_preparation import ( @@ -655,8 +655,9 @@ def seen_page(self, history, seen: tuple[HistoryFragment, ...]): async def mark_page(self, page: MessagePage) -> None: raise ValueError("This transcript has no saved-source reader") - async def read_only(self) -> bool: - return True + async def compose_access(self) -> ComposeAccess: + """A source not yet ready holds compose, and takes nothing.""" + return ComposeAccess(read_only=True, takes_files=False) async def update_mentions(self, view) -> None: return diff --git a/src/toad/client/prompt_composer.py b/src/toad/client/prompt_composer.py index 39b3ab5f4..d24a79a15 100644 --- a/src/toad/client/prompt_composer.py +++ b/src/toad/client/prompt_composer.py @@ -119,6 +119,10 @@ def prompt_symbol(self, text: str, shell_mode: bool) -> str: return symbols.shell_symbol return symbols.multiline_symbol if "\n" in text or "```" in text else symbols.agent_symbol + def offer_files(self, takes_files: bool) -> None: + """Whether this composer's bus takes files. A prompt to an agent attaches none, so it + offers none either way; a message composer offers Attach while its bus takes them.""" + @abstractmethod def show_failure(self, text: str) -> None: """Say, under the input, why something typed or attached did not go.""" diff --git a/src/toad/client/submission.py b/src/toad/client/submission.py index 706a472d9..1baa500eb 100644 --- a/src/toad/client/submission.py +++ b/src/toad/client/submission.py @@ -12,6 +12,7 @@ from agent_comms.messaging.message_files import FileUpload from agent_comms.messaging.message_reference import MessageReference from agent_comms.transport.request import CoreAccess +from agent_comms.transport.tools.sidebar import CommsMessageFilesTool from toad.client.input_decision import InputDecision, InputRefused @@ -35,12 +36,40 @@ def text(self) -> str: return self.source_text.strip() +@dataclass(frozen=True) +class ComposeAccess: + """What compose may do in one conversation, as its Core answered: whether it is held + (a read-only saved view), and whether its messages may carry files. A bus older than + message files takes none: files and the read that lists them shipped together, so a + Core that does not serve that read takes no upload either.""" + + read_only: bool + takes_files: bool + + files_refused_reason: ClassVar[str] = "This bus takes no files (its agent-comms predates them)" + """Why a message carrying files is not sent here.""" + + @property + def block_reason(self) -> str: + """Why compose is held here; empty while it is open.""" + return MessageDestination.read_only_reason if self.read_only else "" + + def refuses(self, draft: SubmittedText) -> bool: + """A draft carrying files to a bus that takes none is refused before it is sent.""" + return bool(draft.files) and not self.takes_files + + class MessageDestination(ABC): """What a bus send asks of the conversation it writes to; every conversation kind is one.""" read_only_reason: ClassVar[str] = "Read-only saved view" """Why compose is held when read_only answers True.""" + def compose_access(self, core: CoreAccess) -> ComposeAccess: + """What compose may do here, from this destination's Core; reads Core, so off the UI + thread.""" + return ComposeAccess(self.read_only(core), core.serves(CommsMessageFilesTool)) + @abstractmethod def send_target(self) -> NamedTarget: ... diff --git a/src/toad/delivery_failure_view.py b/src/toad/delivery_failure_view.py index 25abe2ba4..98ad87acf 100644 --- a/src/toad/delivery_failure_view.py +++ b/src/toad/delivery_failure_view.py @@ -17,7 +17,7 @@ from toad.app_node import ToadNode from toad.client.bus_submission import ConversationSubmission, SubmissionView from toad.client.prompt_composer import ComposerStatus -from toad.client.submission import MessageDestination +from toad.client.submission import ComposeAccess from toad.widgets.flash import Flash from toad.widgets.prompt import Prompt from toad.worker_group import InputHistoryRecord @@ -43,11 +43,12 @@ def draws_user_message(self, reference: MessageReference) -> bool: ... def compute_status(self) -> str | Content | RichText: return self.composed_status() - async def refresh_composer(self, read_only: bool) -> None: + async def refresh_composer(self, access: ComposeAccess) -> None: """Draw compose from the caller's Core answer.""" if not self.is_attached: return - reason = MessageDestination.read_only_reason if read_only else "" + self.prompt.offer_files(access.takes_files) + reason = access.block_reason area = self.prompt.prompt_text_area area.disabled = bool(reason) area.tooltip = reason or None diff --git a/src/toad/forms/presentation.py b/src/toad/forms/presentation.py index 460956134..a813c298f 100644 --- a/src/toad/forms/presentation.py +++ b/src/toad/forms/presentation.py @@ -1,9 +1,11 @@ """Native form geometry and paint, supplied directly to Textual's owners.""" from __future__ import annotations +from abc import abstractmethod + from textual.color import Color, TRANSPARENT from textual.css._style_properties import Edges -from textual.css.scalar import Scalar +from textual.css.scalar import Scalar, Unit from textual.geometry import Spacing from textual.layouts.horizontal import HorizontalLayout from textual.screen import ModalScreen @@ -16,6 +18,7 @@ from textual.widgets import Input from toad.app_node import FollowsTheme from toad.widget_view import CenteredView +from toad.window_presentation import BesideApp, FillsApp, WindowPresentation from toad.widgets.checkbox import Checkbox from ui_theme.scheme import BackgroundColour, ErrorColour, ForegroundColour, PrimaryColour, SurfaceColour @@ -91,3 +94,28 @@ def paint_background(self) -> Color: def theme_changed(self) -> None: # A theme changes the entire visible modal, not each offscreen field. self.refresh() + + +class PanelPresentation(WindowPresentation): + """How Textual lays a panel over the app for one screen width class: its width.""" + + @classmethod + @abstractmethod + def panel_width(cls) -> Scalar | None: + """The panel's width, or None to take the screen's whole width.""" + + +class FilledPanel(PanelPresentation, FillsApp): + """A narrow terminal's panel: the whole screen, as Qt's window fills a phone's app window.""" + + @classmethod + def panel_width(cls) -> Scalar | None: + return None + + +class SidePanel(PanelPresentation, BesideApp): + """A wide terminal's panel: half the screen, its right side, the conversation still in view.""" + + @classmethod + def panel_width(cls) -> Scalar | None: + return Scalar(50, Unit.PERCENT, Unit.WIDTH) diff --git a/src/toad/motion.py b/src/toad/motion.py index d84e82d8c..02318d607 100644 --- a/src/toad/motion.py +++ b/src/toad/motion.py @@ -13,15 +13,16 @@ from textual import constants from ui_theme.clock import AnimationClock -from ui_theme.effects import Amount, Effect, Transition +from ui_theme.effects import Amount, Effect, Glide, Transition _TAB_DURATION = 0.15 _TAB_FPS = 60 TAB_OPEN = Transition(Amount, 0.0, 1.0, _TAB_DURATION, _TAB_FPS) TAB_CLOSE = Transition(Amount, 1.0, 0.0, _TAB_DURATION, _TAB_FPS) # A reader following the end glides down to rows that arrived, over the time the first of them -# takes to fade in (``ARRIVAL``'s `NEW_TEXT`), instead of jumping their whole height at once. -FOLLOW_ARRIVAL = Transition(Amount, 0.0, 1.0, 0.25, 60) +# takes to fade in (``ARRIVAL``'s `NEW_TEXT`), instead of jumping their whole height at once. It +# is motion, so it moves on every frame the screen shows (120 on a Pixel 8a), not a fixed 60. +FOLLOW_ARRIVAL = Glide(Amount, 0.0, 1.0, 0.25) # 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) @@ -29,6 +30,10 @@ # rather than vanishing in one frame. SCROLLBAR_FADE = Transition(Amount, 1.0, 0.0, 0.3, _TAB_FPS) +# A tapped message whose head is above the viewport glides its head to the top, rather than +# the view jumping there in one frame. +HEAD_REVEAL = Glide(Amount, 0.0, 1.0, 0.18) + def animations_enabled() -> bool: """Whether this process animates: Textual's own animation level, which the TUI's clock @@ -42,7 +47,7 @@ class TransitionTarget(ABC): shrinking away are all this; each frontend only says what an amount moves. It advances by what it showed, not by the wall clock: a tick counts at most two of the - effect's frames, so a loop held up by other work (opening a session, say) delays the motion + effect's frames (its cadence on this clock's medium), so a loop held up by other work (opening a session, say) delays the motion rather than skipping it, and every transition is seen from start to end.""" def start_transition(self, clock: AnimationClock, effect: Effect[Amount]) -> None: @@ -70,7 +75,7 @@ def finish(self) -> None: def repaint(self) -> None: now = self.clock.time - self.shown_for += min(now - self.shown_at, 2 / self.effect.frames_per_second) + self.shown_for += min(now - self.shown_at, 2 * self.effect.cadence.interval(self.clock.frame_interval)) self.shown_at = now if self.shown_for >= self.effect.duration: self.finish() diff --git a/src/toad/project_link.py b/src/toad/project_link.py index e048c6ab3..b10ae02be 100644 --- a/src/toad/project_link.py +++ b/src/toad/project_link.py @@ -10,6 +10,7 @@ from dataclasses import dataclass from functools import partial from pathlib import Path +from time import monotonic from typing import Annotated, ClassVar from agent_comms.nominal.field_codec import PathText from urllib.parse import SplitResult, quote, unquote, urlsplit @@ -100,16 +101,40 @@ def file_spelling(cls, root, value, *, position=None, search=True) -> LineLink: if suffix is not None: # Colons may belong to a real POSIX filename; don't erase that identity. try: - return DirectProjectFileLink(cls.existing_file(root, value), original_root=root, position=position) + return DirectProjectFileLink(cls.linked_file(root, value), original_root=root, position=position) except ProjectLinkProblem: value, position = spelling, position or suffix try: - return DirectProjectFileLink(cls.existing_file(root, value), original_root=root, position=position) + return DirectProjectFileLink(cls.linked_file(root, value), original_root=root, position=position) except ProjectLinkProblem: if search and SearchProjectFileLink.accepts(value): return SearchProjectFileLink(value, original_root=root, position=position) return NO_LINK + LINKED_SECONDS: ClassVar[float] = 10.0 + _linked: ClassVar[dict[tuple[Path, str], tuple[float, Path | None]]] = {} + + @classmethod + def linked_file(cls, root: Path, value: str) -> Path: + """`existing_file` for drawing text as a link: a path spelled in a message is checked + once per `LINKED_SECONDS`, not on every row it is drawn in. Formatting a history row + resolved each path-like word on disk (a realpath and a stat per word, per row, per + width), which a history drawn on the phone's row thread did while the screen waited + for the interpreter. Opening a link still checks the file as it is then (`resolve`).""" + key, now = (root, value), monotonic() + checked = cls._linked.get(key) + if checked is None or now - checked[0] > cls.LINKED_SECONDS: + try: + found: Path | None = cls.existing_file(root, value) + except ProjectLinkProblem: + found = None + if len(cls._linked) > 4096: + cls._linked.clear() + checked = cls._linked[key] = (now, found) + if checked[1] is None: + raise ProjectLinkProblem(value, root) + return checked[1] + @staticmethod def existing_file(root: Path, value: str) -> Path: candidate = Path(value).expanduser() diff --git a/src/toad/prompt_actions.py b/src/toad/prompt_actions.py index 1c59bad23..a8e0d247a 100644 --- a/src/toad/prompt_actions.py +++ b/src/toad/prompt_actions.py @@ -64,6 +64,10 @@ class AttachFileAction(MessageAction): keys = {TextEntryMode: ("ctrl+t",)} title = "Attach" + def available(self, editor): + """Offered while the composer's bus takes files (`ComposeAccess.takes_files`).""" + return editor.prompt.takes_files + async def apply(self, editor: PromptTextArea) -> None: editor.prompt.attach_file() diff --git a/src/toad/qt/activity.py b/src/toad/qt/activity.py index d4af5bc6f..3df74c6c4 100644 --- a/src/toad/qt/activity.py +++ b/src/toad/qt/activity.py @@ -25,6 +25,7 @@ from toad.client.prompt_stack import ObservedSweep from toad.qt.core_events import QtCoreObserver from toad.qt.lines import QtLineRenderer +from toad.qt.widget_animation import frame_interval from toad.status_thread import ObservedActivity from toad.qt.metrics import UiGap @@ -95,14 +96,13 @@ def __init__(self, renderer: QtLineRenderer) -> None: # One text row, always reserved, as Textual's throbber row: only its paint changes. self.setFixedHeight(self.fontMetrics().lineSpacing()) self.timer = QTimer(self) + self.timer.setTimerType(Qt.TimerType.PreciseTimer) self.timer.timeout.connect(self.update) def sweep(self, working: bool) -> None: self.working = working if working: - screen = self.screen() - rate = screen.refreshRate() if screen is not None else 0.0 - self.timer.start(max(8, round(1000 / (rate if rate >= 20 else 60)))) + self.timer.start(max(1, round(frame_interval(self.screen()) * 1000))) else: self.timer.stop() self.update() diff --git a/src/toad/qt/command_form.py b/src/toad/qt/command_form.py index bfcf5b3cd..cf03cc268 100644 --- a/src/toad/qt/command_form.py +++ b/src/toad/qt/command_form.py @@ -35,8 +35,9 @@ from toad.client.pending import Applying, ChoicesPreparation, awaited from toad.client.command_draft import CommandFormCore from toad.client.host import CommandOrigin -from toad.qt.host import QtCommsHost, ScreenWideWindow +from toad.qt.host import QtCommsHost from toad.widget_contracts import DismissibleContract, SubmitsContract +from toad.qt.presented_window import PresentedWindow @awaited(Applying) @@ -181,7 +182,7 @@ def repaint_choice(self, name: str) -> None: self.form.editor(DottedFieldPath(name)).paint() -class QtCommandWindow(ScreenWideWindow, QDialog, DismissibleContract, metaclass=PyQtWidgetMeta): +class QtCommandWindow(PresentedWindow, QDialog, DismissibleContract, metaclass=PyQtWidgetMeta): """The window a command dialog's form is presented in, over the window it started on; dismissing it (Escape, Back, Cancel) closes the dialog unanswered, as Textual's `CommandDialog` screen dismisses.""" @@ -205,7 +206,6 @@ def __init__(self, host: QtCommsHost, window: QWidget | None, definition: Target self.dialog = QtCommandWindow(window, definition.label) super().__init__(host, definition, target, fields, core, self.dialog) self.dialog.layout().addWidget(self) - self.dialog.fit_screen() self.dialog.finished.connect(self.closed) def present(self) -> None: diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index 85a039536..2b27b30ca 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -447,7 +447,7 @@ def focus_changed(self, focused: bool) -> None: """The frame's border follows focus (Textual's `PromptContainer.border`), and the badge shows the editing mode only while focused.""" colour = self.renderer.theme(PrimaryColour if focused else MutedColour) - self.frame.setStyleSheet( + self.renderer.apply_sheet(self.frame, f"#prompt-frame {{ border: 1px solid {colour}; border-radius: 2px }}" if self.settings.ui.input.box.bordered else "#prompt-frame { border: none }") @@ -688,6 +688,9 @@ def pick_in_window(self) -> None: def pick_by_path_search(self) -> None: open_path_search(self, self, self.host.app.project_dir.path, self.host.app.run_operation) + def show_files_offered(self) -> None: + self.attach_button.setVisible(self.takes_files) + def show_attached(self) -> None: chips = self.attached_row.layout() while (item := chips.takeAt(0)) is not None: @@ -769,7 +772,7 @@ def paint(self, status: NotificationStatus) -> None: self.show() def paint_colour(self) -> None: - self.setStyleSheet(f"{self.renderer.color_style(self.status.role)}; padding: 0 8px 4px 8px") + self.renderer.apply_sheet(self, f"{self.renderer.color_style(self.status.role)}; padding: 0 8px 4px 8px") def notifications_observed(self, results) -> None: for status in CheckedNotifications.for_references(self.references, results): diff --git a/src/toad/qt/file_pickers.py b/src/toad/qt/file_pickers.py index 03e4c9aed..99b0c00b7 100644 --- a/src/toad/qt/file_pickers.py +++ b/src/toad/qt/file_pickers.py @@ -20,6 +20,7 @@ from toad.client.message_files import FileSearch, MessagePromptComposer from toad.client.project_paths import ProjectPathSearch from toad.prompt_actions import AttachFileAction +from toad.qt.presented_window import PresentedWindow def read_picked(url: QUrl, composer: MessagePromptComposer) -> None: @@ -49,7 +50,7 @@ def open_file_dialog(parent: QWidget, composer: MessagePromptComposer) -> QFileD return dialog -class QtPathSearch(ProjectPathSearch, QDialog): +class QtPathSearch(PresentedWindow, ProjectPathSearch, QDialog): """The project's paths, ranked as you type; choosing one attaches that file.""" shown_limit = 100 diff --git a/src/toad/qt/goal.py b/src/toad/qt/goal.py index 6d728776b..7bf5e0791 100644 --- a/src/toad/qt/goal.py +++ b/src/toad/qt/goal.py @@ -49,12 +49,12 @@ GoalInteractionControl, ) from toad.qt.core_events import QtCoreObserver -from toad.qt.host import ScreenWideWindow from toad.qt.lines import QtLineRenderer from toad.session_observation import GoalObservation from toad.core.events import ThreadRowsChanged from toad.widget_contracts import DismissibleContract, SubmitsContract from toad.qt.metrics import UiGap +from toad.qt.presented_window import PresentedWindow from ui_theme.scheme import SecondaryColour @@ -292,7 +292,7 @@ def show_execution_text(self, text: str) -> None: self.standby.setText(text) -class QtGoalHistory(ScreenWideWindow, QDialog, DismissibleContract): +class QtGoalHistory(PresentedWindow, QDialog, DismissibleContract): """The goal's revisions and failed attempts, listed as the TUI's GoalDetails lists them.""" dismiss_control = QDialog.reject @@ -321,10 +321,9 @@ def __init__(self, bar: QtGoalBar, page: GoalHistoryPage) -> None: layout = QVBoxLayout(self) layout.addWidget(scroll, 1) layout.addWidget(buttons) - self.fit_screen() -class QtGoalEdit(ScreenWideWindow, QDialog, DismissibleContract, SubmitsContract): +class QtGoalEdit(PresentedWindow, QDialog, DismissibleContract, SubmitsContract): """The goal's objective in an editor; Save writes it through the session's settle-by-read.""" dismiss_control = QDialog.reject @@ -350,7 +349,6 @@ def __init__(self, bar: QtGoalBar, session: QtGoalSession, goal) -> None: layout.addWidget(WrappedText(f"Progress (read-only): {goal.progress}")) layout.addWidget(self.error) layout.addWidget(buttons) - self.fit_screen() def save(self) -> None: text = self.editor.toPlainText().strip() diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 4169eff43..abbe1330d 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -75,7 +75,7 @@ from toad.qt.lines import QtLineRenderer from toad.transcript_filter import DrawnFilter, FilterState from toad.frame_presentation import ARRIVAL -from toad.motion import FOLLOW_ARRIVAL, TransitionTarget +from toad.motion import FOLLOW_ARRIVAL, HEAD_REVEAL, TransitionTarget from toad.qt.widget_animation import WidgetAnimation from ui_theme.scheme import BackgroundColour, ForegroundColour, PrimaryColour, SurfaceHoverColour @@ -195,6 +195,7 @@ class HistoryRows(QAbstractListModel): def __init__(self) -> None: super().__init__() self.fragments: tuple[HistoryFragment, ...] = () + self._rows: dict = {} def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: # type: ignore[override] return 0 if parent.isValid() else len(self.fragments) @@ -209,10 +210,17 @@ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole): # def show(self, fragments: tuple[HistoryFragment, ...]) -> None: self.beginResetModel() self.fragments = fragments + # Every row a key names, built with the rows: a lookup is asked per changed row on + # each receipt update, arrival, glide and reader restore, and a scan compared every + # row's key each time. + rows: dict = {} + for row, fragment in enumerate(fragments): + rows.setdefault(fragment.key, row) + self._rows = rows self.endResetModel() def row_of(self, key) -> int: - return next((row for row, fragment in enumerate(self.fragments) if fragment.key == key), -1) + return self._rows.get(key, -1) class ArrivalFade(WidgetAnimation): @@ -272,6 +280,32 @@ def land(self) -> None: window.follow_end() +class HeadReveal(WidgetAnimation, TransitionTarget): + """A tapped message whose head is above the viewport glides its head up to the top + (`HEAD_REVEAL`), as Textual's clicked-head reveal scrolls it into view. A finger that + takes the rows again stops it where it is.""" + + def __init__(self, window: QtHistoryWindow, start: float, target: float) -> None: + self.window, self.start, self.target = window, start, target + self.bind_widget(window, window.animation_clock) + self.start_transition(window.animation_clock, HEAD_REVEAL) + + def apply_amount(self, amount: float) -> None: + window = self.window + window.scroll_y = self.start + (self.target - self.start) * amount + + def land(self) -> None: + window = self.window + if window.head_reveal is self: + window.head_reveal = None + window.scroll_y = self.target + + def cancel(self) -> None: + """Stop where it is: the reader's own scrolling owns the rows now.""" + self.window.head_reveal = None + self.animation.stop() + + class HistoryRowDelegate(RowDocumentDelegate): """Each fragment's line blocks as Qt rich text, rendered on the pool at the row's width (dividers fill it); a row paints its plain text until then. A painted row tells the @@ -563,11 +597,14 @@ def hold_arrival(self, arrivals: tuple[HistoryFragment, ...]) -> None: """Qt holds no rows below a following reader: arrivals rise where `repaint` names them.""" async def _show(self, changes: list[tuple[HistoryFragment, Shown]]) -> None: - """A status change lays the rows out again: a row's cache key carries how its fragment - is shown, so the changed rows render anew.""" - changed = [fragment for fragment, shown in changes if fragment.request_show(shown)] + """A status change repaints only the rows it changed. A row's cache key carries how + its fragment is shown, so the repaint asks the delegate for the new look, which keeps + drawing the last one until it is prepared, and that arrival lays the rows out + (`RowDocumentDelegate._row_prepared`). Laying every row out here on each receipt + update cost the whole history's measurement while the new looks were not even ready.""" + changed = tuple(fragment for fragment, shown in changes if fragment.request_show(shown)) if changed: - self.window.rows_changed() + self.repaint(continuing=changed) def repaint(self, fragments: tuple[HistoryFragment, ...] = (), *, continuing=()) -> None: """Repaint only the rows the pager named. The shared contract already says which @@ -735,6 +772,9 @@ class QtStickyHeader(HeaderPin, QWidget): def __init__(self, window: QtHistoryWindow) -> None: super().__init__(window) + # It fills its rectangle (paintEvent), so the rows it covers are not painted under it: a + # glide repaints only the band it floats over (`VirtualRowView.scrollContentsBy`). + self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, True) self.history_window = window self.documents: tuple[QTextDocument, ...] = () self.drawn: tuple = () @@ -888,8 +928,10 @@ def __init__(self, renderer: QtLineRenderer, scope, parent: QWidget | None = Non # fires it once when the drag ends (and Scrolling/Inactive ticks still # run it as before). Leaves at_end/follows_tail transitions in `scrolled` # alone — those are cheap and only do work when the state actually flips. + # A finger pulling past an edge is the one drag that asks for rows at once + # (`overshot`): no scroll travel measures it. self._scroller_dragging = False - self._drag_skipped_ticks = 0 + self._overshoot = 0.0 _scroller = QScroller.scroller(self.viewport()) _scroller.stateChanged.connect(self._on_scroller_state) # The floating "jump to latest" button: child of the window (not the viewport), so @@ -902,16 +944,26 @@ def __init__(self, renderer: QtLineRenderer, scope, parent: QWidget | None = Non # Arriving rows fading in, and the glide down to them (`arrive`). self.arrivals: list[ArrivalFade] = [] self.glide: ArrivalGlide | None = None + # A tapped message's head gliding to the top (`reveal_head_at`). + self.head_reveal: HeadReveal | None = None + # A press that stops a fling is not a tap on a row (Android's lists do the same). + self._fling_stopped = False # Rows that arrived at the end the reader follows, not yet glided to (`glide_to_end`). self._arrived: tuple = () + # A press makes its row Qt's current index, and autoScroll would then scroll that + # row into view at once (QAbstractItemView.currentChanged → scrollTo): a jump on + # every tap, and one that fights a drag starting on a row. A tap's reveal is the + # explicit `reveal_head_at`. + self.setAutoScroll(False) self.viewport().installEventFilter(self) # Block menu: a right-click, or a held finger (`FingerPress` delivers it as one), on a # message row emits `block_menu_requested` with the row's fragment. ConversationView # mounts the handler and runs the resulting commands. self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self._emit_block_menu_at) - # A tap on a link opens it, in place of the row's own click (`FingerPress.tapped`). - FingerPress.install(QApplication.instance()).tapped.connect(self._link_tapped) + # A tap on a link opens it, and a tap on a message reveals its head, in place of the + # row's own click (`FingerPress.tapped`). + FingerPress.install(QApplication.instance()).tapped.connect(self._row_tapped) # Reader keys (ctrl+d / ctrl+u / shift+g) come from the `ReaderAction` family # declared in `src/toad/reader_actions.py`. Both backends drive from that one # declaration: Textual through the Action/BindingsMap path, Qt through @@ -1016,17 +1068,31 @@ def eventFilter(self, obj: QWidget, event: QEvent) -> bool: # type: ignore[over if self.jump_bar.isVisible(): self._place_jump_bar() self.repin_header() + elif event.type() == QEvent.Type.Scroll: + self.overshot(event.overshootDistance().y()) return super().eventFilter(obj, event) - def _link_tapped(self, press: Press) -> None: - """A tap on a link drawn in a row opens it, and the row doesn't also take the tap.""" + def _row_tapped(self, press: Press) -> None: + """A tap on a row: a link drawn there opens; otherwise a message whose head is above + the viewport glides its head to the top (`reveal_head_at`). Either way the row + doesn't also take the tap. A tap on rows still moving (a fling, a reveal) only stops + them, as Android's lists do: the reader was catching the rows, not choosing one.""" viewport = self.viewport() if not press.within(viewport): return - href = self.anchor_at(press.at(viewport)) + stopped, self._fling_stopped = self._fling_stopped, False + scroller = QScroller.scroller(viewport) + if stopped or scroller.state() == QScroller.State.Scrolling: + scroller.stop() + press.claim() + return + point = press.at(viewport) + href = self.anchor_at(point) if href: press.claim() self.open_link(href) + elif self.reveal_head_at(point): + press.claim() def anchor_at(self, point: QPoint) -> str: """The href of the link drawn at `point` (viewport coordinates), or "" over plain text.""" @@ -1349,26 +1415,59 @@ def scrolled(self, value: int) -> None: elif not self.follows_tail: self.reader_position = RowPosition(value) if self._scroller_dragging: - self._drag_skipped_ticks += 1 return self.respond_to_scroll(value) + _flinging = False + + def reveal_head_at(self, point: QPoint) -> bool: + """A tap at ``point`` (viewport coordinates): when the tapped message's head is above + the viewport, glide it up to the top. A head already on screen stays where it is, + as in Textual (`reveal_message_head`). Whether it moved the rows.""" + index = self.indexAt(point) + if not index.isValid(): + return False + model_rows = self.model_rows + head = index.data(HistoryRows.FRAGMENT).message_head(model_rows.fragments) + row = model_rows.row_of(head.key) + if row < 0: + return False + top = self.visualRect(model_rows.index(row, 0)).top() + if top >= 0: + return False + if self.head_reveal is not None: + self.head_reveal.cancel() + start = self.scroll_y + self.head_reveal = HeadReveal(self, start, max(0.0, start + top)) + return True + def _on_scroller_state(self, state) -> None: - """Track QScroller state transitions. On the drag → not-drag edge, flush the - post-scroll work `scrolled` skipped while the finger was down, using the - current scrollbar position. Prints the skipped-tick count once per drag so - the perf win is visible in logcat.""" + """On the drag → not-drag edge, answer the drag's last position at once. A finger + taking the rows stops a head reveal; a press that stops a fling is remembered, so + its release is not read as a tap on a row.""" was_dragging = self._scroller_dragging self._scroller_dragging = (state == QScroller.State.Dragging) + if state in (QScroller.State.Pressed, QScroller.State.Dragging) and self.head_reveal is not None: + self.head_reveal.cancel() + if state == QScroller.State.Pressed: + self._fling_stopped = self._flinging + self._flinging = state == QScroller.State.Scrolling + if state == QScroller.State.Inactive: + self._overshoot = 0.0 if was_dragging and not self._scroller_dragging: - print( - f"QtHistoryWindow drag ended: skipped {self._drag_skipped_ticks} " - f"respond_to_scroll ticks during drag", - flush=True, - ) - self._drag_skipped_ticks = 0 self.respond_to_scroll(self.verticalScrollBar().value()) + def overshot(self, distance: float) -> None: + """A finger (or a fling's momentum) pulled the rows past an edge: the content can't + move, so no scroll travel is measured, yet the reader asked for more. Each pull + further past it asks the shared lookahead for that edge's next page, as a wheel + step at an edge does (`wheelEvent`).""" + further = abs(distance) - abs(self._overshoot) + self._overshoot = distance + if distance and further > 0: + rows = further / self._font_line_spacing() + self.lookahead.request_boundary(-rows if distance < 0 else rows) + def wheelEvent(self, event) -> None: # type: ignore[override] """A wheel at an edge with nowhere left to scroll still asks for the next page.""" rows = -event.angleDelta().y() / 120 * self._font_line_spacing() * QApplication.wheelScrollLines() diff --git a/src/toad/qt/keymap_screen.py b/src/toad/qt/keymap_screen.py index db2813e38..55ce69112 100644 --- a/src/toad/qt/keymap_screen.py +++ b/src/toad/qt/keymap_screen.py @@ -28,19 +28,19 @@ from toad.client.keymap_browser import KeymapBrowsing from toad.keymap import KeyInvocationId from toad.qt.metrics import UiGap +from toad.qt.presented_window import PresentedWindow if TYPE_CHECKING: from toad.qt.window import QtToadApp -class QtKeymapScreen(KeymapBrowsing, QDialog): +class QtKeymapScreen(PresentedWindow, KeymapBrowsing, QDialog): """Modal keymap browser: heading, search, focus filter, the action × mode table, the selection's summary, the keys field with Apply/Reset/Close, and a status line.""" def __init__(self, app: QtToadApp, focused: frozenset[KeyInvocationId]) -> None: super().__init__(app) self.app = app - self.setWindowFlags(Qt.WindowType.Dialog) self.setWindowTitle("Keyboard shortcuts") self.begin_browsing(app, focused) diff --git a/src/toad/qt/lines.py b/src/toad/qt/lines.py index d86998ccd..b3ea299af 100644 --- a/src/toad/qt/lines.py +++ b/src/toad/qt/lines.py @@ -105,6 +105,15 @@ def follow(self, scheme: ColourScheme, diff_marks: DiffMarks) -> None: for repaint in tuple(self.followers): repaint() + @staticmethod + def apply_sheet(widget: QWidget, sheet: str) -> None: + """Give ``widget`` this style sheet. Qt repolishes a widget and asks its parents to + lay out again on every `setStyleSheet`, even with the sheet it already has, so a + line restyled on each status update or focus change re-laid out the composer each + time; an unchanged sheet now costs nothing.""" + if widget.styleSheet() != sheet: + widget.setStyleSheet(sheet) + def themed(self, widget: QWidget, paint: Callable[[], None]) -> None: """``paint`` draws ``widget``'s own colours from this renderer's scheme: now, and again each time the scheme changes. Colours set once keep the scheme they were diff --git a/src/toad/qt/presented_window.py b/src/toad/qt/presented_window.py new file mode 100644 index 000000000..3624ec96e --- /dev/null +++ b/src/toad/qt/presented_window.py @@ -0,0 +1,179 @@ +"""Every window Toad opens over its app window, presented as the screen's width class says. + +`toad.screen_width.ScreenWidth` decides, from the app window's width in columns of its text: +NARROW (a phone, or a desktop window as narrow as one) fills the app window as a phone app's +page does, under a header whose ← goes back; WIDE floats a dialog no larger than its screen. +Textual's windows read the same class (its settings panel fills a narrow terminal). + +The presentation is applied each time the window is shown, in `setVisible`, which `show`, +`open` and `exec` all reach, so a window has it by inheriting `PresentedWindow` and no caller +presents anything: a window opened from anywhere, and a window added later, is presented the +same way. `tools/qt_inherit_ratchet.py` fails a Qt dialog that does not inherit it. + +Tristan, Android, 2026-11-18: Settings opened as a small floating dialog over the chat with one +line of its content showing, and the team window drew part of itself off screen. +""" + +from __future__ import annotations + +from abc import abstractmethod + +from PySide6.QtCore import QEvent, QObject, QPoint, QRect, Qt +from PySide6.QtWidgets import QBoxLayout, QHBoxLayout, QLabel, QLayout, QToolButton, QWidget + +from toad.qt.metrics import UiGap +from toad.screen_width import ScreenWidth +from toad.window_presentation import BesideApp, FillsApp, WindowPresentation + +def window_width(host: QWidget) -> ScreenWidth: + """The width class of the window `host`: its width in columns of its font's text.""" + width = host.width() if host.isVisible() and host.width() > 0 else host.screen().availableGeometry().width() + return ScreenWidth.of(width / max(1, host.fontMetrics().averageCharWidth())) + + +class QtWindowPresentation(WindowPresentation): + """How Qt lays a window over the app window, for one width class.""" + + @classmethod + def present(cls, window: PresentedWindow, host: QWidget) -> None: + """Lay `window` out for this width class before it is shown.""" + window.layout().setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint) + window.setMinimumSize(0, 0) + flags = cls.window_flags() + if window.windowFlags() != flags: + window.setWindowFlags(flags) + window.page_header().setVisible(cls.shows_header()) + cls.place(window, host) + + @classmethod + @abstractmethod + def window_flags(cls) -> Qt.WindowType: ... + + @classmethod + @abstractmethod + def shows_header(cls) -> bool: ... + + @classmethod + @abstractmethod + def place(cls, window: QWidget, host: QWidget) -> None: + """Size and place `window`; also run when the app window resizes or turns while it shows.""" + + +class FilledWindow(QtWindowPresentation, FillsApp): + """A phone app's page: exactly the app window's area, under the window's own ← header.""" + + @classmethod + def window_flags(cls) -> Qt.WindowType: + return Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint + + @classmethod + def shows_header(cls) -> bool: + return True + + @classmethod + def place(cls, window: QWidget, host: QWidget) -> None: + window.setMaximumSize(host.size()) + window.setGeometry(QRect(host.mapToGlobal(QPoint(0, 0)), host.size())) + + +class FloatingWindow(QtWindowPresentation, BesideApp): + """A desktop dialog centred over the app: at least half the app window wide and seven + tenths as tall (more when its own size or its layout asks for more), never past its screen + less the system's bars. Settings once floated at its layout's 228x165 hint over the chat.""" + + least_width = 1 / 2 + least_height = 7 / 10 + + @classmethod + def window_flags(cls) -> Qt.WindowType: + return Qt.WindowType.Dialog + + @classmethod + def shows_header(cls) -> bool: + return False + + @classmethod + def place(cls, window: QWidget, host: QWidget) -> None: + # The window's client area, inside the screen less its bars and the window's frame (as + # thick as the app window's own). + frame, inside = host.frameGeometry(), host.geometry() + available = host.screen().availableGeometry().adjusted( + inside.left() - frame.left(), inside.top() - frame.top(), + inside.right() - frame.right(), inside.bottom() - frame.bottom()) + hint = window.sizeHint() + width = min(available.width(), max(window.width(), hint.width(), int(host.width() * cls.least_width))) + height = min(available.height(), max(window.height(), hint.height(), int(host.height() * cls.least_height))) + placed = QRect(0, 0, width, height) + placed.moveCenter(QRect(host.mapToGlobal(QPoint(0, 0)), host.size()).center()) + placed.moveLeft(max(available.left(), min(placed.left(), available.right() + 1 - width))) + placed.moveTop(max(available.top(), min(placed.top(), available.bottom() + 1 - height))) + window.setMaximumSize(available.size()) + window.setGeometry(placed) + + +class PresentedWindow: + """A window opened over the app window. Listed before the window's Qt dialog class, so its + `setVisible` presents the window each time it is shown, and its header's ← and Android's + back key close it as the dialog's own Close does.""" + + _page_header: QWidget | None = None + _presentation: type[QtWindowPresentation] | None = None + _presentation_host: QWidget | None = None + + def presentation_host(self) -> QWidget: + """The app window this window is opened over: its parent's window. A window is always + opened over one, so a window built without a parent is refused when it is shown.""" + parent = self.parentWidget() + if parent is None: + raise TypeError(f"{type(self).__qualname__} is shown without the window it opens over " + "as its parent") + return parent.window() + + def page_header(self) -> QWidget: + """The ← header a filled window shows above its content, built the first time.""" + if self._page_header is None: + layout = self.layout() + if not isinstance(layout, QBoxLayout): + raise TypeError(f"{type(self).__qualname__} is a PresentedWindow without a box layout " + "for its page header") + header = QWidget(self) + row = QHBoxLayout(header) + row.setContentsMargins(0, 0, 0, UiGap.normal) + back = QToolButton(header) + back.setText("←") + back.setToolTip("Back") + back.setAutoRaise(True) + back.clicked.connect(self.close) + title = QLabel(self.windowTitle(), header) + self.windowTitleChanged.connect(title.setText) + row.addWidget(back) + row.addWidget(title, 1) + layout.insertWidget(0, header) + self._page_header = header + return self._page_header + + def setVisible(self, visible: bool) -> None: # noqa: N802 (Qt override) + if visible and not self.isVisible(): + host = self.presentation_host() + presentation = QtWindowPresentation.for_width(window_width(host)) + if self._presentation_host is not host: + host.installEventFilter(self) + self._presentation_host = host + self._presentation = presentation + presentation.present(self, host) + super().setVisible(visible) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 (Qt override) + """The app window resized or turned while this window shows: place it again.""" + if (watched is self._presentation_host and self.isVisible() and self._presentation is not None + and event.type() in (QEvent.Type.Resize, QEvent.Type.Move)): + self._presentation.place(self, watched) + return super().eventFilter(watched, event) + + def keyPressEvent(self, event) -> None: # noqa: N802 (Qt override) + """Android's back key closes the window, as its ← and its Close do.""" + if event.key() == Qt.Key.Key_Back: + event.accept() + self.close() + return + super().keyPressEvent(event) diff --git a/src/toad/qt/prompt_stack.py b/src/toad/qt/prompt_stack.py index aba24ebf5..b1eba3b58 100644 --- a/src/toad/qt/prompt_stack.py +++ b/src/toad/qt/prompt_stack.py @@ -44,6 +44,7 @@ from toad.qt.lines import QtLineRenderer from toad.qt.metrics import UiGap from toad.status_thread import ObservedActivity +from toad.qt.presented_window import PresentedWindow class QtFlash(FlashNotice, ElidedLine, metaclass=PyQtWidgetMeta): @@ -66,7 +67,7 @@ def show_flash(self, content, tone: type[FlashTone]) -> None: scheme = self.renderer.scheme ink = tone.colour.rgb(scheme) tint = BackgroundColour.rgb(scheme).blend(ink, 0.1) - self.setStyleSheet(f"color: {ink.hex}; background: {tint.hex}") + self.renderer.apply_sheet(self, f"color: {ink.hex}; background: {tint.hex}") self.setText(str(content)) self.show() @@ -160,7 +161,7 @@ def show(self, row: ThreadStatusModel) -> None: # type: ignore[override] def paint_title(self) -> None: """The title in its row's status role, under the renderer's current scheme.""" - self.title.setStyleSheet( + self.renderer.apply_sheet(self.title, f"QToolButton {{ {self.renderer.color_style(self.title_role_for(self.row, self.status))};" " border: none; text-align: left; padding: 0 4px }") @@ -192,7 +193,7 @@ def close_activity(self) -> None: self.close_core_events() -class QtInputDeliveryDetails(DeliveryDetailsPage, QDialog, metaclass=PyQtWidgetMeta): +class QtInputDeliveryDetails(PresentedWindow, DeliveryDetailsPage, QDialog, metaclass=PyQtWidgetMeta): """Textual's `InputDeliveryDetails` as a dialog; `DeliveryDetailsPage` owns its text. A Qt thread view has no input-delivery observation, so the delivery is the view's diff --git a/src/toad/qt/queue_ui.py b/src/toad/qt/queue_ui.py index 3d4afaaf4..9cca95703 100644 --- a/src/toad/qt/queue_ui.py +++ b/src/toad/qt/queue_ui.py @@ -27,6 +27,7 @@ from toad.qt.metrics import UiGap from toad.motion import ROW_REVEAL, TransitionTarget from toad.qt.widget_animation import WidgetAnimation +from toad.qt.presented_window import PresentedWindow # Qt's QWIDGETSIZE_MAX, which PySide does not export: no maximum height. QWIDGETSIZE_MAX = (1 << 24) - 1 @@ -192,7 +193,7 @@ def __init__(self, composer: "Composer") -> None: self.hide() -class QtQueueInspection(QueueInspectionOwner, QDialog, metaclass=PyQtWidgetMeta): +class QtQueueInspection(PresentedWindow, QueueInspectionOwner, QDialog, metaclass=PyQtWidgetMeta): """Textual's ``QueueInspection`` as a dialog; `QueueInspectionOwner` owns the reading, the actions and how they settle.""" @@ -200,7 +201,6 @@ def __init__(self, submissions: "ConversationSubmissions", renderer: "QtLineRend parent: QWidget | None = None) -> None: super().__init__(parent) self.setWindowTitle(self.title) - self.setWindowFlags(Qt.WindowType.Dialog) self.inspect_submissions(submissions) layout = QVBoxLayout(self) layout.setContentsMargins(UiGap.dialog, UiGap.dialog, UiGap.dialog, UiGap.dialog) diff --git a/src/toad/qt/settings_screen.py b/src/toad/qt/settings_screen.py index 8c905eea9..1677c3bcc 100644 --- a/src/toad/qt/settings_screen.py +++ b/src/toad/qt/settings_screen.py @@ -9,13 +9,14 @@ from typing import TYPE_CHECKING -from PySide6.QtCore import Qt, QTimer, Signal +from PySide6.QtCore import QTimer, Signal from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLineEdit, QTabWidget, QVBoxLayout, QWidget from formbridge.forms.declared_fields import FormPage from toad.qt.forms import QtFormView from toad.settings_editing import SettingsEditing +from toad.qt.presented_window import PresentedWindow if TYPE_CHECKING: from toad.qt.window import QtToadApp @@ -23,7 +24,7 @@ # The screen. -class QtSettingsScreen(SettingsEditing, QDialog): +class QtSettingsScreen(PresentedWindow, SettingsEditing, QDialog): """Modal settings editor: a search above one tab per declared page. Discard rolls back unsaved edits; closing sends the typed edits and the app saves them.""" @@ -32,7 +33,6 @@ class QtSettingsScreen(SettingsEditing, QDialog): def __init__(self, app: QtToadApp, parent: QWidget | None = None) -> None: super().__init__(parent or app) self.app = app - self.setWindowFlags(Qt.WindowType.Dialog) self.setWindowTitle("Settings") self.build_pages() diff --git a/src/toad/qt/submission_view.py b/src/toad/qt/submission_view.py index 6b29dfacd..3cd392c24 100644 --- a/src/toad/qt/submission_view.py +++ b/src/toad/qt/submission_view.py @@ -7,7 +7,7 @@ from collections.abc import Awaitable, Callable from toad.client.bus_submission import ConversationSubmission, SubmissionView -from toad.client.submission import MessageDestination +from toad.client.submission import ComposeAccess class QtSubmissionView(SubmissionView): @@ -20,10 +20,12 @@ def show_send_failure(self, text: str) -> None: composer_block: str = "" - async def refresh_composer(self, read_only: bool) -> None: - """Hold the composer with the destination's read-only reason, or release it.""" - self.composer_block = MessageDestination.read_only_reason if read_only else "" + async def refresh_composer(self, access: ComposeAccess) -> None: + """Hold the composer with the destination's read-only reason, or release it, and offer + files where the bus takes them.""" + self.composer_block = access.block_reason self.on_composer("hold", lambda composer: composer.hold(self.composer_block)) + self.on_composer("files", lambda composer: composer.offer_files(access.takes_files)) def draws_user_message(self, reference) -> bool: return self.message_history.draws(reference) diff --git a/src/toad/qt/team_board_screen.py b/src/toad/qt/team_board_screen.py index 8df48c9c1..7101cd271 100644 --- a/src/toad/qt/team_board_screen.py +++ b/src/toad/qt/team_board_screen.py @@ -46,6 +46,7 @@ from toad.core.events import TeamHudChanged, TeamHudFailed from toad.qt.core_events import QtCoreObserver from toad.qt.metrics import UiGap +from toad.qt.presented_window import PresentedWindow if TYPE_CHECKING: from agent_comms.team.team_hud import TeamHud @@ -53,7 +54,7 @@ from toad.qt.window import QtToadApp -class QtTeamBoardScreen(QtCoreObserver, QDialog): +class QtTeamBoardScreen(PresentedWindow, QtCoreObserver, QDialog): """Modal team board dialog. `team_name` restricts the view to a single teammate (empty = show all), @@ -63,7 +64,7 @@ class QtTeamBoardScreen(QtCoreObserver, QDialog): def __init__(self, app: "QtToadApp", team_name: str = "") -> None: super().__init__() - self.setParent(app, Qt.WindowType.Dialog) + self.setParent(app) self.setWindowTitle("Team") self.resize(900, 650) self.app = app # QtCoreObserver's AppScoped expects this diff --git a/src/toad/qt/transfer.py b/src/toad/qt/transfer.py index 7f7fd5095..417c6ae40 100644 --- a/src/toad/qt/transfer.py +++ b/src/toad/qt/transfer.py @@ -25,6 +25,7 @@ from toad.client.transfer_forms import ExportFormatInput, ExportScopeInput, ThreadImportForm, TransferForm, WireExportForm from toad.client.transfers import ThreadImportRequest, Transfer, TransferHost, WireExportRequest from toad.qt.metrics import UiGap +from toad.qt.presented_window import PresentedWindow if TYPE_CHECKING: from agent_comms.installer.harness_install import Harness @@ -45,7 +46,7 @@ def _choices(options) -> QComboBox: return combo -class QtTransferDialog(TransferForm, QDialog): +class QtTransferDialog(PresentedWindow, TransferForm, QDialog): """The frame every Qt transfer dialog shares: heading, the form's rows, an error line, and submit/cancel buttons.""" diff --git a/src/toad/qt/widget_animation.py b/src/toad/qt/widget_animation.py index 1bf306fc7..ba522ddc7 100644 --- a/src/toad/qt/widget_animation.py +++ b/src/toad/qt/widget_animation.py @@ -12,10 +12,20 @@ from __future__ import annotations import shiboken6 +from PySide6.QtGui import QScreen from PySide6.QtWidgets import QWidget from ui_theme.clock import AnimationClock + +def frame_interval(screen: QScreen | None) -> float: + """Seconds between the frames `screen` shows: one over its refresh rate (a Pixel 8a's 120 Hz), + or 60 Hz where it reports none (offscreen, some remote displays). Motion ticks at it + (`ui_theme.effects.DisplayRate`); the window's clock and the activity sweep both read it here.""" + rate = screen.refreshRate() if screen is not None else 0.0 + return 1 / (rate if rate >= 20 else 60) + + class WidgetAnimation: """A clock target whose frames move `widget`, alive on the clock only while the widget is.""" diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index e72dfb129..b8c331e05 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -25,7 +25,7 @@ from agent_comms.ui_model.sidebar import ChannelRowModel, SidebarModel from formbridge.operations import OperationKind from PySide6.QtCore import QEvent, QMargins, QObject, QPoint, QRect, QSize, Qt, QTimer -from PySide6.QtGui import QColor, QKeySequence, QShortcut +from PySide6.QtGui import QColor, QKeySequence, QScreen, QShortcut from PySide6.QtWidgets import ( QApplication, QFrame, @@ -58,6 +58,7 @@ from toad.app_core import CorePrewarm from toad.client.application import ClientApplication from toad.qt.workspace_frame import QtWorkspaceFrame +from toad.qt.widget_animation import frame_interval from toad.widget_view import WorkspaceHosted from toad.workspace_frame import WorkspaceFrame from toad.client.session_scope import NoConversationView @@ -1297,9 +1298,9 @@ async def _refresh_source(self) -> None: self.sync_working() label = self.conversation.label(source.references()) self.on_composer("label", lambda composer: composer.labelled(label)) - read_only = await asyncio.to_thread(self.conversation.read_only, source.core) - await self.refresh_composer(read_only) - self.thread_status = await self.conversation.status_text(source, read_only=read_only) + compose = await asyncio.to_thread(self.conversation.compose_access, source.core) + await self.refresh_composer(compose) + self.thread_status = await self.conversation.status_text(source, read_only=compose.read_only) await self.conversation.update_mentions(self, source) # The kind's composer and activity (ConversationActivity) @@ -1537,6 +1538,9 @@ def __init__(self, connection: CoreConnection, project: Checkout, # The one animation clock every effect's frames come from (ui_theme's # `AnimationClock`, as Textual's colours own theirs), on one Qt timer. self._animation_timer = QTimer(self) + # Motion ticks every frame the screen shows; a coarse timer's few percent of slack + # would land some ticks between two frames and show one frame twice. + self._animation_timer.setTimerType(Qt.TimerType.PreciseTimer) self._animation_timer.timeout.connect(self._tick_animation) self._layout_pending = False self.animation_clock = AnimationClock(self._schedule_animation, enabled=animations_enabled()) @@ -1698,6 +1702,9 @@ def __init__(self, connection: CoreConnection, project: Checkout, self.winId() self.windowHandle().safeAreaMarginsChanged.connect(self.fit_safe_area) self.fit_safe_area(self.windowHandle().safeAreaMargins()) + self._display_screens: set[QScreen] = set() + self.windowHandle().screenChanged.connect(self.follow_display) + self.follow_display() # The saved settings drawn now the widgets exist, as Textual's `on_load` applies them # all; from here each change applies its `Effect` (`ClientApplication.open_settings`). self.saved_settings.apply_all() @@ -1756,6 +1763,15 @@ def _schedule_animation(self, interval: float | None) -> None: def _tick_animation(self) -> None: self.animation_clock.tick() + def follow_display(self, *_changed) -> None: + """The clock's frame interval is the screen's this window is on: it follows the window to + another screen, and a screen that changes its refresh rate (a phone's adaptive 60/120 Hz).""" + screen = self.windowHandle().screen() + self.animation_clock.frame_interval = frame_interval(screen) + if screen is not None and screen not in self._display_screens: + self._display_screens.add(screen) + screen.refreshRateChanged.connect(self.follow_display) + def paint_tabs(self) -> None: self.tabs.blockSignals(True) badge = self.settings.sidebar.unread_counts.badge diff --git a/src/toad/screen_width.py b/src/toad/screen_width.py new file mode 100644 index 000000000..6690e875e --- /dev/null +++ b/src/toad/screen_width.py @@ -0,0 +1,25 @@ +"""How wide the app's window is, counted the same way by every frontend. + +A width is counted in columns of the frontend's own text: a terminal's cells, or Qt's window +width over its font's average character width. Under a hundred columns (a phone holds about +fifty, a narrow terminal) is NARROW; wider is WIDE. Counting text, not pixels, makes the rule +the same at every display density: a phone's 412 device-independent pixels hold the same fifty +columns at any DPI. What each class means for a window opened over the app is +`toad.window_presentation`'s. +""" + +from __future__ import annotations + +from enum import IntEnum + + +class ScreenWidth(IntEnum): + """A screen's width class; its value is the fewest columns it starts at.""" + + NARROW = 0 + WIDE = 100 + + @classmethod + def of(cls, columns: float) -> ScreenWidth: + """The class a screen `columns` wide is in: the widest one it reaches.""" + return max(mode for mode in cls if mode <= columns) diff --git a/src/toad/screens/settings.py b/src/toad/screens/settings.py index 3e2d1ac63..ec61e775e 100644 --- a/src/toad/screens/settings.py +++ b/src/toad/screens/settings.py @@ -18,7 +18,8 @@ from textual.geometry import Spacing from textual.color import Color -from toad.app import ScreenWidth +from toad.forms.presentation import PanelPresentation +from toad.screen_width import ScreenWidth from toad.form_family import SchemeChoosing from toad.settings_editing import SettingsEditing from toad.forms.editors import SelectEditor @@ -46,7 +47,7 @@ class SettingsPanel(WidgetView, containers.Vertical): @property def width(self): - return ScreenWidth(self.screen.horizontal_breakpoint).side_panel_width + return PanelPresentation.for_width(ScreenWidth(self.screen.horizontal_breakpoint)).panel_width() class SettingsSearch(WidgetView, containers.VerticalGroup): diff --git a/src/toad/textual_colours.py b/src/toad/textual_colours.py index 0f80d6e6d..14bf35f24 100644 --- a/src/toad/textual_colours.py +++ b/src/toad/textual_colours.py @@ -300,7 +300,7 @@ def __init__(self, app: ToadApp) -> None: self._add(scheme) self._observer: BaseObserver | None = None self._cadence = ClockCadence() - self.clock = AnimationClock(self._schedule) + self.clock = AnimationClock(self._schedule, frame_interval=app.frame_interval) # The catalog and pywal. diff --git a/src/toad/widgets/comms_chat.py b/src/toad/widgets/comms_chat.py index 60d02476b..bd8bf45fd 100644 --- a/src/toad/widgets/comms_chat.py +++ b/src/toad/widgets/comms_chat.py @@ -265,10 +265,10 @@ async def _refresh_source(self) -> None: snapshot = history.source_snapshot() if not await history.source_is_current(snapshot): return - read_only = await source.read_only() + compose = await source.compose_access() if not await history.source_is_current(snapshot): return - await self.refresh_composer(read_only) + await self.refresh_composer(compose) self._refreshed_from = announced # A sent message may now be drawn: its queue entry retires before mentions are read. self.submissions.settle() @@ -276,7 +276,7 @@ async def _refresh_source(self) -> None: # and the agent records, which can take seconds on a busy bus. They are # not this conversation's messages, so they run after this work ends # and the history can load pages while they wait. - self.run_worker(partial(self._refresh_labels, source, changed, newly_announced, read_only), + self.run_worker(partial(self._refresh_labels, source, changed, newly_announced, compose.read_only), group=self.LABELS_GROUP) LABELS_GROUP = "chat-labels" diff --git a/src/toad/widgets/prompt.py b/src/toad/widgets/prompt.py index 29fc02926..f10f5c8ab 100644 --- a/src/toad/widgets/prompt.py +++ b/src/toad/widgets/prompt.py @@ -1162,6 +1162,10 @@ def __init__(self, *, placeholder: str | None = None, **kwargs): def supports_completion(self) -> bool: return False + def show_files_offered(self) -> None: + """Attach's key is offered (`AttachFileAction.available`) only while the bus takes files.""" + self.refresh_bindings() + def sync_configuration(self) -> None: pass diff --git a/src/toad/widgets/transcript_history.py b/src/toad/widgets/transcript_history.py index e414774c1..d55a5268b 100644 --- a/src/toad/widgets/transcript_history.py +++ b/src/toad/widgets/transcript_history.py @@ -702,9 +702,8 @@ async def reveal_message_head( The fragment the cursor rests on after: the head, or the clicked part when the head stays put.""" page = self.page_holding(fragment.key) original = page.prepared - first = next(index for index, part in enumerate(original.fragments) - if part.source_identity == fragment.source_identity) - head = original.fragments[first] + head = fragment.message_head(original.fragments) + first = original.fragments.index(head) window = self.window head_placement = self.fragment_placement(head) if head_placement.head_on_screen(window): diff --git a/src/toad/window_presentation.py b/src/toad/window_presentation.py new file mode 100644 index 000000000..bf0d00da5 --- /dev/null +++ b/src/toad/window_presentation.py @@ -0,0 +1,50 @@ +"""How a window opened over the app is laid out, for each screen width class: one family both +frontends' presentations inherit, so neither can lay a window out by a rule of its own. + +On a NARROW screen (a phone) a window fills the app, as a phone app's page does (`FillsApp`). +On a WIDE one it sits beside the app's content (`BesideApp`): Textual draws a side panel half +the screen wide, Qt a dialog floating over the app. Each frontend's members inherit one of these +and its own toolkit base, and each frontend finds its member for a width through `for_width` on +its toolkit base, so a width class with no member in a frontend fails there, not silently. +""" + +from __future__ import annotations + +from abc import ABC +from typing import ClassVar + +from toad.screen_width import ScreenWidth + + +class WindowPresentation(ABC): + """How a window over the app is laid out on a screen of one width class.""" + + width: ClassVar[ScreenWidth] + + @classmethod + def for_width(cls, width: ScreenWidth) -> type[WindowPresentation]: + """The member of this (toolkit's) family that lays a window out at `width`.""" + pending, found = list(cls.__subclasses__()), [] + while pending: + member = pending.pop() + pending.extend(member.__subclasses__()) + if "width" in {name for ancestor in member.__mro__ for name in vars(ancestor)} \ + and member.width is width and member not in found: + found.append(member) + concrete = [member for member in found if not member.__abstractmethods__] + if len(concrete) != 1: + raise TypeError(f"{cls.__qualname__} has {len(concrete)} presentations for {width.name}: " + f"{[member.__qualname__ for member in concrete]}") + return concrete[0] + + +class FillsApp(WindowPresentation): + """A narrow screen's window: it takes the app's whole window, as a phone app's page does.""" + + width = ScreenWidth.NARROW + + +class BesideApp(WindowPresentation): + """A wide screen's window: it leaves the app's content in view beside or under it.""" + + width = ScreenWidth.WIDE diff --git a/tests/textual/test_application_actions_in_the_running_app.py b/tests/textual/test_application_actions_in_the_running_app.py index f81630ce3..4449a257d 100644 --- a/tests/textual/test_application_actions_in_the_running_app.py +++ b/tests/textual/test_application_actions_in_the_running_app.py @@ -165,6 +165,9 @@ def call(self, request): raise TimeoutError("The test did not release command preparation") return self.original.call(request) + def serves(self, request_type): + return self.original.serves(request_type) + async with running_session(workspace) as (ui, app, config, path): project = Checkout(workspace.project) command, = NewThreadCliCommand.project_bindings(workspace.comms, project) diff --git a/tests/textual/test_older_bus.py b/tests/textual/test_older_bus.py new file mode 100644 index 000000000..2c5d18d4d --- /dev/null +++ b/tests/textual/test_older_bus.py @@ -0,0 +1,140 @@ +"""A newer Toad on a bus older than message files: its pages draw every message with no file +chips and ask that bus for no files, compose offers no Attach, and a draft carrying files is +refused with its reason before it is sent. The phone's APK on the laptop's older bus failed +every page read on the files read that bus did not have (2026-11-18).""" + +import base64 +from pathlib import Path + +from agent_comms.comms import Comms +from agent_comms.errors import RelationViolationError +from agent_comms.execution.launch_root import LaunchRoot +from agent_comms.messaging.channel_targets import ChannelTarget +from agent_comms.messaging.historical_views import UnobservedConversation +from agent_comms.messaging.message_files import FileUpload +from agent_comms.nominal.field_codec import FieldCodec +from agent_comms.projects.checkouts import Checkout +from agent_comms.registry.threads import NativeThread +from agent_comms.transport.request import CoreAccess, RequestPoster +from agent_comms.transport.tool_caller import HumanCaller +from agent_comms.transport.tool_request import ServedRequest +from agent_comms.transport.tools.served import ServedCommsUserSendTool +from agent_comms.transport.tools.sidebar import CommsMessageFilesTool, CommsMessageFileTool +from support.agents import AppAgents +from support.roots import installed_wire + +from toad.client.bus_submission import TypedText +from toad.client.conversation import ChannelConversation +from toad.client.history import WireSource +from toad.client.history_preparation import OLDER_END, PageRequest +from toad.client.line_blocks import Spans +from toad.client.message_file_links import MessageFileLink +from toad.client.message_files import MessagePromptComposer +from toad.client.submission import ComposeAccess +from toad.message_rows import IrcMessageStyle +from toad.widgets.wire_history import WireFragment + +UNEXPOSED = frozenset({CommsMessageFilesTool.declared_name, CommsMessageFileTool.declared_name}) + + +class OlderBusCore(CoreAccess, RequestPoster): + """A remote Core on a bus older than message files: each request is posted, as across the + connector, and that connector serves every tool but the two file reads, refusing one it + lacks as it did then, with an undifferentiated refusal.""" + + def __init__(self, comms: Comms) -> None: + self.comms = comms + self.posted: list[str] = [] + + def call(self, request): + return FieldCodec.decode(request.result_type(), request.posted(self)) + + def serves(self, request_type) -> bool: + return request_type.declared_name not in UNEXPOSED + + def forget_served(self) -> None: + """This connector's tools never change.""" + + def post(self, request): + self.posted.append(request.declared_name) + if request.declared_name in UNEXPOSED: + raise RelationViolationError(f"The connector exposes no tool {request.declared_name!r}.") + return FieldCodec.encode(ServedRequest.serving(request).apply_without_thread(self.comms, HumanCaller())) + + def exchange(self, request): + return self.post(request) + + def post_observed(self, request): + return self.post(request) + + +def older_bus(tmp_path: Path) -> tuple[Comms, OlderBusCore, Checkout]: + comms = installed_wire(tmp_path / "wire") + comms.registry.declare(NativeThread("peer", frozenset({"team"}), Checkout(tmp_path))) + for body in ("first", "second"): + HumanCaller().invoke(ServedCommsUserSendTool(target="#team", body=body), comms) + return comms, OlderBusCore(comms), Checkout(tmp_path) + + +def test_a_page_from_an_older_bus_draws_its_messages_and_asks_it_for_no_files(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "data")) + comms, core, project = older_bus(tmp_path) + source = WireSource(comms.root, ChannelConversation(ChannelTarget("#team")), project, + comms.messaging.user_identity(project).name, IrcMessageStyle(), + access=AppAgents.unrun(project.path, LaunchRoot.from_path(comms.root)).app.coordination_access, + core=core, fragments=WireFragment) + through = source.observe(UnobservedConversation()).through + prepared = source.read(PageRequest(OLDER_END, through), through) + assert len(prepared.fragments) == 2 + assert not [span for fragment in prepared.fragments for block in fragment.blocks(fragment.shown) + if isinstance(block, Spans) for span in block.spans if isinstance(span.link, MessageFileLink)] + assert CommsMessageFilesTool.declared_name not in core.posted + + +def test_compose_on_an_older_bus_takes_no_files(tmp_path: Path) -> None: + _, core, _ = older_bus(tmp_path) + access = ChannelConversation(ChannelTarget("#team")).compose_access(core) + assert access == ComposeAccess(read_only=False, takes_files=False) + upload = FileUpload("a.txt", "text/plain", base64.b64encode(b"a").decode()) + assert access.refuses(TypedText("with a file", (upload,))) + assert not access.refuses(TypedText("plain", ())) + assert not ComposeAccess(read_only=False, takes_files=True).refuses(TypedText("with a file", (upload,))) + + +class Composer(MessagePromptComposer): + """The shared message composer with only its drawing recorded.""" + + settings = None + + def __init__(self) -> None: + self.offered: list[bool] = [] + self.failures: list[str] = [] + self.opened = 0 + + def show_files_offered(self) -> None: + self.offered.append(self.takes_files) + + def pick_in_window(self) -> None: + self.opened += 1 + + def pick_by_path_search(self) -> None: + self.opened += 1 + + def show_attached(self) -> None: ... + + def sync_queue(self) -> None: ... + + def show_failure(self, text: str) -> None: + self.failures.append(text) + + def restore_draft(self, text: str) -> None: ... + + +def test_a_composer_on_an_older_bus_offers_no_attach_and_says_why() -> None: + composer = Composer() + composer.offer_files(True) + assert composer.offered == [] # open until the bus answers: no change, nothing redrawn + composer.offer_files(False) + assert composer.offered == [False] + composer.attach_file() + assert composer.opened == 0 and composer.failures == [ComposeAccess.files_refused_reason] diff --git a/tools/history_bus.py b/tools/history_bus.py new file mode 100644 index 000000000..4a109c20b --- /dev/null +++ b/tools/history_bus.py @@ -0,0 +1,70 @@ +"""A scratch bus whose #comms has a long history, served as the phone reaches a bus, for the +history drives (qt_drive's `history_scroll_back`, `tools/tui_scroll_back.py`) when the live bus +is not the thing measured, or is not up. + + RUNTIME/bin/python tools/history_bus.py RUNTIME WORK [MESSAGES] + +Seeds WORK/root with MESSAGES (default 400) channel messages of mixed length, Markdown, code and +file paths (the history row's formatting resolves those) from two peers, serves it over loopback +TLS with a UI grant (`tools/android/shipped_run.ScratchBus`), writes WORK/trust.pem (its +certificate with the system's CAs, for SSL_CERT_FILE) and prints the UI profile's path. It +serves until stopped. +""" + +from __future__ import annotations + +import signal +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent / "android")) +from shipped_run import CHANNEL, PEER, THREAD, ScratchBus, run # noqa: E402 + +BODIES = ( + "short note {n}", + "A longer message {n}, the kind a teammate writes when explaining what changed: the pager " + "reads older pages as the reader nears the top, and each page's rows are measured before they " + "are shown, so a slow measurement is a slow page.", + "Changed `src/toad/qt/history.py` and src/toad/motion.py for {n}; see README.md and " + "tools/qt_drive.py:2400 for the drive.", + "## Status {n}\n\n- the first point\n- the second point, with **bold** and `code`\n- a third\n\n" + "Then a closing paragraph.", + "```python\ndef page_{n}(rows):\n return [row for row in rows if row.shown]\n```\nThat's the shape.", +) + + +def seed(bus: ScratchBus, messages: int) -> None: + bus.seed() + cli = bus.runtime / "bin" / "agent-comms" + run(cli, "--root", bus.root, "register", "--name", "scratch-second", "--worktree", bus.work, + "--tags", CHANNEL, "--execution", "external", cwd=bus.work) + from agent_comms.comms import Comms + from agent_comms.installer.active_route import resolve_comms_route + + comms = Comms(resolve_comms_route(bus.root)) + senders = (PEER, "scratch-second", THREAD) + for n in range(messages): + comms.messaging.send(senders[n % len(senders)], f"#{CHANNEL}", BODIES[n % len(BODIES)].format(n=n)) + + +def main(runtime: Path, work: Path, messages: int) -> None: + work.mkdir(parents=True, exist_ok=True) + work.chmod(0o700) # the UI profile's grant lives in an owner-only directory + bus = ScratchBus(runtime, work) + seed(bus, messages) + profile = bus.serve() + import certifi + + (work / "trust.pem").write_text(Path(certifi.where()).read_text() + (work / "cert.pem").read_text()) + print(profile, flush=True) + stop = {"now": False} + signal.signal(signal.SIGTERM, lambda *_: stop.update(now=True)) + try: + while not stop["now"]: + signal.pause() + finally: + bus.stop() + + +if __name__ == "__main__": + main(Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]) if len(sys.argv) > 3 else 400) diff --git a/tools/qt_drive.py b/tools/qt_drive.py index f80c98dc0..2009ea4ff 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -25,6 +25,17 @@ from collections.abc import Callable from typing import ClassVar + +# A drive never touches the reader's own settings: run as a script with no XDG_CONFIG_HOME or +# XDG_STATE_HOME of its own, it keeps them under OUTDIR before anything of Toad is imported (a +# module can read them at import). Drives run without them wrote the real toad.json +# (2026-11-17); every caller had to remember to set both. +if __name__ == "__main__" and len(sys.argv) > 2: + for variable, folder in (("XDG_CONFIG_HOME", "config"), ("XDG_STATE_HOME", "state")): + if not os.environ.get(variable): + os.environ[variable] = str((Path(sys.argv[2]) / folder).resolve()) + Path(os.environ[variable]).mkdir(parents=True, exist_ok=True) + import qasync from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QRect, QTimer, Qt from PySide6.QtGui import QContextMenuEvent, QImage, QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent, QPainter, QTextDocument @@ -41,8 +52,9 @@ from toad.qt.frame_probe import FrameProbe, ProbedApplication from toad.client.application import BusDiscovery from toad.client.application_actions import ( - ApplicationAction, NewSessionAction, NewThreadAction, QuitAction, SettingsAction, + ApplicationAction, NewSessionAction, NewThreadAction, OpensWindow, QuitAction, SettingsAction, ) +from toad.qt.presented_window import FilledWindow, PresentedWindow, QtWindowPresentation, window_width from toad.qt.settings_screen import QtSettingsScreen from toad.client.bus_submission import TypedText from toad.client.conversation import ChannelConversation @@ -1147,6 +1159,128 @@ async def run(self) -> None: self.report("3-notice", notices=app.float_layer.shown_notices(), shown=app.float_layer.isVisible()) +class OlderBusScenario(ParticipantSteps): + summary = ("open #comms and expect FILES (\"absent\" or \"served\") for this bus: with absent, the " + "history draws its messages, no notice is posted, and the composer offers no Attach") + + async def run(self) -> None: + from toad.client.message_file_links import MessageFileLink + files = os.environ.get("FILES", "served") + self.app.resize(412, 915) + await self.open_named("#comms") + await until(lambda: self.page.messages.model_rows.rowCount(), "the first page") + await asyncio.sleep(2.0) + fragments = self.page.messages.model_rows.fragments + chips = sum(1 for fragment in fragments for block in fragment.blocks(fragment.shown) + for span in getattr(block, "spans", ()) if isinstance(span.link, MessageFileLink)) + composer = self.page.composer + failures = self.failures_since(0) + self.report("1-history", files=files, fragments=len(fragments), chips=chips, + takes_files=composer.takes_files, attach_shown=composer.attach_button.isVisible(), + failures=failures) + assert not failures, f"notices posted: {failures}" + assert composer.takes_files == (files == "served"), f"takes_files={composer.takes_files} on a bus with files {files}" + assert composer.attach_button.isVisible() == (files == "served"), "Attach is offered against what the bus takes" + if files == "absent": + assert chips == 0, f"{chips} file chips drawn from a bus without files" + +class WindowsPhoneScenario(Scenario): + summary = ("open every window an OpensWindow action opens (one per transfer kind) at WIDTH x HEIGHT " + "(412x915, a phone): fail when any part of one is drawn outside the app window, when a " + "window is not a PresentedWindow, when on a phone it does not fill the app window or on a " + "desktop (WIDTH 1280 HEIGHT 800) it does not float inside the screen, and when Settings " + "gives its pages under 60% of its height or shows no editable setting") + + def window_rect(self, widget: QWidget) -> QRect: + return QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size()) + + def drawn_outside(self, window: QWidget, bounds: QRect) -> list[str]: + """Each visible widget of `window` drawn past `bounds`. A widget inside a scroll area's + viewport is that viewport's: the viewport clips it and scrolls to it.""" + outside = [] + for widget in [window, *window.findChildren(QWidget)]: + if not widget.isVisible() or widget.width() <= 0 or widget.height() <= 0: + continue + clipped = widget.parentWidget() + while clipped is not None and clipped is not window: + if isinstance(clipped.parentWidget(), QAbstractScrollArea) and clipped is clipped.parentWidget().viewport(): + break + clipped = clipped.parentWidget() + if clipped is not None and clipped is not window: + continue + rect = self.window_rect(widget) + if not bounds.adjusted(-1, -1, 1, 1).contains(rect): + outside.append(f"{type(widget).__name__} {rect.getRect()}") + return outside + + async def run(self) -> None: + app = self.app + width, height = int(os.environ.get("WIDTH", 412)), int(os.environ.get("HEIGHT", 915)) + app.resize(width, height) + await self.listed() + await asyncio.sleep(0.5) + presentation = QtWindowPresentation.for_width(window_width(app)) + print(f"app window {width}x{height}: {window_width(app).name}, windows {presentation.__name__}", flush=True) + faults: list[str] = [] + opened = 0 + for command, label in ApplicationAction.menu(app): + if not isinstance(command, OpensWindow): + continue + before = {id(window) for window in QApplication.topLevelWidgets() if window.isVisible()} + await command.apply(app) + await asyncio.sleep(2.0) + windows = [window for window in QApplication.topLevelWidgets() + if window.isVisible() and id(window) not in before] + step = f"{command.declared_name}-{label}".replace(" ", "_").replace("/", "_")[:48] + app_rect = self.window_rect(app) + for window in windows: + opened += 1 + name = type(window).__name__ + window.grab().save(str(self.out / f"windows_phone-{step}-{name}.png")) + rect = self.window_rect(window) + if not isinstance(window, PresentedWindow): + faults.append(f"{label}: {name} is not a PresentedWindow") + if presentation is FilledWindow: + bounds = app_rect + if abs(rect.x() - app_rect.x()) > 1 or abs(rect.y() - app_rect.y()) > 1 or \ + abs(rect.width() - app_rect.width()) > 1 or abs(rect.height() - app_rect.height()) > 1: + faults.append(f"{label}: {name} at {rect.getRect()} does not fill the app window {app_rect.getRect()}") + else: + bounds = window.screen().availableGeometry() + if rect == app_rect: + faults.append(f"{label}: {name} fills the app window on a wide screen") + outside = self.drawn_outside(window, bounds) + if outside: + faults.append(f"{label}: {name} draws {len(outside)} widgets outside {bounds.getRect()}: {outside[:4]}") + if isinstance(window, QtSettingsScreen): + share = window.tabs.height() / max(1, window.height()) + editable = [field for field in window.tabs.currentWidget().findChildren(QWidget) + if field.isVisible() and field.isEnabled() + and isinstance(field, (QAbstractButton, QLineEdit))] + print(f" settings: pages {share:.0%} of its height, {len(editable)} editable fields shown", flush=True) + if share < 0.6: + faults.append(f"{label}: settings pages take {share:.0%} of its height") + if not editable: + faults.append(f"{label}: settings shows no editable setting") + print(f"{step}: {name} at {rect.getRect()} in app {app_rect.getRect()}; outside={len(outside)}", flush=True) + if not windows: + outside = self.drawn_outside(app, self.window_rect(app)) + app.grab().save(str(self.out / f"windows_phone-{step}-in-app.png")) + print(f"{step}: no new window; in-app panels outside the app window: {len(outside)}", flush=True) + if outside: + faults.append(f"{label}: draws {len(outside)} widgets outside the app window: {outside[:4]}") + if app.bus_switcher.isVisible(): + app.bus_switcher.hide_switcher() + for window in windows: + window.close() + await asyncio.sleep(0.5) + print(f"windows opened: {opened}", flush=True) + if opened < 4: + faults.append(f"only {opened} windows opened") + if faults: + raise AssertionError("\n".join(faults)) + + class MenuTextScenario(Scenario): summary = ("open the menu at WIDTH (412) and fail when any of its lines is drawn in less height " "than its font's full height: the descenders of a description line were cut on the phone") @@ -2574,6 +2708,22 @@ def followed_arrivals(arrivals): await asyncio.sleep(0.5) top = window.indexAt(window.viewport().rect().topLeft()) reading = (self.label(top.data(HistoryRows.FRAGMENT)), window.visualRect(top).top()) + # Every frame the history paints, with where it was and whether a glide moved it: the + # motion a reader sees is these frames, not the clock's ticks. + painted: list[tuple[float, float, bool]] = [] + + class PaintedFrames(QObject): + def eventFilter(self, watched, event): # noqa: N802 - Qt virtual method name + if event.type() == QEvent.Type.Paint: + painted.append((time.perf_counter(), float(window.scroll_y), window.glide is not None, + sum(r.width() * r.height() for r in event.region()) + / max(1, watched.width() * watched.height()))) + return False + frame_watch = PaintedFrames() + window.viewport().installEventFilter(frame_watch) + if (refresh := os.environ.get("REFRESH")) and hasattr(app.animation_clock, "frame_interval"): + app.animation_clock.frame_interval = 1 / float(refresh) + print("burst: posting", flush=True) # a profiler attaches here posts = [asyncio.ensure_future(post(index)) for index in range(burst)] for index in range(0 if scrolled_up else 3): composer.editor.setPlainText(f"arrival send {index} {stamp}") @@ -2583,6 +2733,23 @@ def followed_arrivals(arrivals): if refused: raise RuntimeError(f"the scratch sender's posts were refused: {refused}") await asyncio.sleep(8.0) + window.viewport().removeEventFilter(frame_watch) + gliding = [index for index, frame in enumerate(painted) if frame[2]] + intervals = sorted((painted[i][0] - painted[i - 1][0]) * 1000 for i in gliding if i and painted[i - 1][2]) + steps = [painted[i][1] - painted[i - 1][1] for i in gliding if i and painted[i - 1][2]] + moving = sorted(step for step in steps if step > 0) + + def quantile(values, q): + return round(values[min(len(values) - 1, int(q * len(values)))], 1) if values else None + median_step = quantile(moving, 0.5) + print(f"glide frames: {len(gliding)} painted while gliding; interval ms median " + f"{quantile(intervals, 0.5)} p95 {quantile(intervals, 0.95)} max {quantile(intervals, 1.0)}; " + f"over 17 ms {sum(1 for value in intervals if value > 17)}; px per frame median {median_step} " + f"max {quantile(moving, 1.0)}; repeated frames (no move) {sum(1 for step in steps if step == 0)}; " + f"steps over twice the median {sum(1 for step in moving if median_step and step > 2 * median_step)}; " + f"share of the viewport area each gliding paint repainted: median " + f"{round(sorted(painted[i][3] for i in gliding)[len(gliding) // 2], 3) if gliding else None}", + flush=True) print("final rows:", view.messages.model_rows.rowCount(), [self.label(f) for f in view.messages.model_rows.fragments][-8:], flush=True) timer.stop() @@ -3448,6 +3615,293 @@ def readings(self) -> dict[str, Callable[[], object]]: } +class PaintClock(QObject): + """Records when the watched widget next paints.""" + + def __init__(self, painted: list[float], parent: QObject) -> None: + super().__init__(parent) + self.painted = painted + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: + if event.type() == QEvent.Type.Paint and not self.painted: + self.painted.append(time.perf_counter()) + return False + + +class HistoryScrollBackScenario(Scenario): + summary = ("at a Pixel 8a's size with the phone's touch-as-mouse gesture: read #comms idle, then " + "drag its history back by finger to its start (or about 300 earlier rows); per older " + "page, the time from the reader reaching the top to the page's rows drawn, the " + "probe's stalls and the work repeated over the scroll-back; then, by touch through " + "the window, a tap on a message whose head is above the top, a tap on moving rows and " + "a drag that starts on a row (OUT/frame-probe.log, OUT/scroll-back.txt)") + + idle_seconds: ClassVar[float] = float(os.environ.get("SCROLL_BACK_IDLE", "8")) + rows_wanted: ClassVar[int] = int(os.environ.get("SCROLL_BACK_ROWS", "300")) + + @classmethod + def finger_gesture(cls) -> FingerScrollGesture: + return TouchAsMouse() + + async def drag(self, viewport: QWidget) -> None: + """One finger drag down the viewport, as a reader pulls earlier history into view.""" + height, x = viewport.height(), viewport.width() // 2 + start, end = QPoint(x, int(height * 0.2)), QPoint(x, int(height * 0.85)) + FingerScenario.press(viewport, QEvent.Type.MouseButtonPress, start, True) + await asyncio.sleep(0.016) + for step in range(1, 13): + at = start + (end - start) * step / 12 + FingerScenario.press(viewport, QEvent.Type.MouseMove, QPoint(int(at.x()), int(at.y())), True) + await asyncio.sleep(0.016) + FingerScenario.press(viewport, QEvent.Type.MouseButtonRelease, end, False) + + async def run(self) -> None: + app = self.app + app.resize(412, 915) + probe = ProbedApplication.probe or FrameProbe(QApplication.instance(), self.out / "frame-probe.log") + probe.sink = (self.out / "frame-probe.log").open("a", buffering=1) + probe.REPORT_SECONDS = 1e9 # one report per phase, written when the phase ends + await self.open_named("#comms") + app.hide_sidebar() + await asyncio.sleep(2.0) + window = self.page.messages + results = (self.out / "scroll-back.txt").open("w", buffering=1) + painted_ms = self.time_paints(window) if os.environ.get("SCROLL_BACK_TIME_PAINT") else None + probe.sink.write(f"--- idle reading #comms rows={window.model_rows.rowCount()}\n") + probe.window_start = probe.last = time.perf_counter() + probe.reset() + await asyncio.sleep(self.idle_seconds) + probe.report(time.perf_counter()) + rows_at_start = window.model_rows.rowCount() + counts = self.count_work(window) + cpu_started = time.thread_time() + probe.sink.write(f"--- scroll back #comms rows={rows_at_start}\n") + probe.window_start = probe.last = time.perf_counter() + probe.reset() + viewport = window.viewport() + painted: list[float] = [] + viewport.installEventFilter(PaintClock(painted, viewport)) + pages, drags, deadline = [], 0, time.perf_counter() + 150 + from toad.client.history_preparation import OLDER_END + + def older_left() -> bool: + return any(OLDER_END.visible_more(history) for history in window.histories) + + while (window.model_rows.rowCount() - rows_at_start < self.rows_wanted and time.perf_counter() < deadline + and (older_left() or window.scroll_y > 0)): + first = window.model_rows.fragments[0].key + await self.drag(viewport) + drags += 1 + reached = None + while time.perf_counter() < deadline: + if window.model_rows.fragments[0].key != first: + break + if window.scroll_y <= 0 and not older_left(): + break # the reader is at the start of the history + if reached is None and window.scroll_y <= 0: + reached = time.perf_counter() + results.write(f"top at={time.time():.3f} rows={window.model_rows.rowCount()}\n") + if reached is not None and os.environ.get("SCROLL_BACK_DEBUG") and time.perf_counter() - reached > 3 \ + and not getattr(self, "_explained", False): + self._explained = True + self.explain_top(window, results) + if reached is None and QScroller.scroller(viewport).state() == QScroller.State.Inactive \ + and window.scroll_y > 0: + break # the drag settled short of the top: drag again + await asyncio.sleep(0.005) + if window.model_rows.fragments[0].key != first: + painted.clear() + while not painted and time.perf_counter() < deadline: + await asyncio.sleep(0.002) # the first viewport paint after the rows landed + shown = painted[0] if painted else time.perf_counter() + waited = (shown - reached) * 1000 if reached is not None else 0.0 + pages.append(waited) + results.write(f"page {len(pages)} at={time.time():.3f} drags={drags} " + f"rows={window.model_rows.rowCount()} visible_after_top_ms={waited:.0f}\n") + probe.report(time.perf_counter()) + results.write(f"work: main_thread_cpu_s={time.thread_time() - cpu_started:.2f} " + + " ".join(f"{name}={count}" for name, count in counts.items()) + "\n") + loaded = window.model_rows.rowCount() - rows_at_start + ordered = sorted(pages) + results.write(f"pages={len(pages)} rows_loaded={loaded} drags={drags} " + f"visible_after_top_ms_median={ordered[len(ordered) // 2] if ordered else 0:.0f} " + f"max={ordered[-1] if ordered else 0:.0f}\n") + if painted_ms is not None: + for label, values in painted_ms.items(): + values.sort() + if values: + results.write(f"paint {label}: n={len(values)} p50={values[len(values) // 2]:.1f}ms " + f"p95={values[int(len(values) * 0.95)]:.1f}ms max={values[-1]:.1f}ms " + f"total={sum(values):.0f}ms\n") + await self.taps(window, results) + results.close() + print((self.out / "scroll-back.txt").read_text(), flush=True) + self.report("done", rows=window.model_rows.rowCount(), loaded=loaded) + + def count_work(self, window) -> dict[str, int]: + """Work the scroll-back repeats, counted: the history's full relayouts (every row + measured again), the receipt updates that asked for them, and the layout requests the + composer and its parents take (each one re-lays the input area out).""" + counts = {"full_relayouts": 0, "receipt_updates": 0, "composer_layout_requests": 0} + relayout = window.rows_changed + + def counted_relayout(): + counts["full_relayouts"] += 1 + return relayout() + window.rows_changed = counted_relayout + history = self.page.message_history + show = history._show + + async def counted_show(changes): + counts["receipt_updates"] += 1 + return await show(changes) + history._show = counted_show + + class LayoutRequests(QObject): + def eventFilter(self, watched, event): + if event.type() == QEvent.Type.LayoutRequest: + counts["composer_layout_requests"] += 1 + name = f"layout_request:{type(watched).__name__}" + counts[name] = counts.get(name, 0) + 1 + return False + composer = self.page.composer + filter_ = LayoutRequests(composer) + for widget in (composer, *composer.findChildren(QWidget)): + widget.installEventFilter(filter_) + return counts + + @staticmethod + def time_paints(window) -> dict[str, list[float]]: + """SCROLL_BACK_TIME_PAINT: each row the delegate paints, and their sum per viewport + paint (one frame of the history), tools only.""" + timings: dict[str, list[float]] = {"frame rows": [], "row": []} + delegate = window.itemDelegate() + paint_row = delegate.paint + + def row(painter, option, index): + started = time.perf_counter() + try: + return paint_row(painter, option, index) + finally: + took = (time.perf_counter() - started) * 1000 + timings["row"].append(took) + if timings["frame rows"]: + timings["frame rows"][-1] += took + delegate.paint = row + + class FramePaints(QObject): + def eventFilter(self, watched, event): + if event.type() == QEvent.Type.Paint: + timings["frame rows"].append(0.0) + return False + window.viewport().installEventFilter(FramePaints(window)) + return timings + + def explain_top(self, window, results) -> None: + """Why the reader at the top is not given older rows (SCROLL_BACK_DEBUG).""" + from toad.client.history_preparation import OLDER_END + look = window.lookahead + for history in window.histories: + edge = OLDER_END.edge(history.pages).prepared + facts = dict( + state=type(history._source_state).__name__, presenting=window.presenting, + filter_idle=history.filter.idle, categories=bool(history.selected_categories), + at_boundary=OLDER_END.at_boundary(window), visible_more=OLDER_END.visible_more(history), + can_extend=OLDER_END.can_extend(edge), source_more=history.page_source.has_more(OLDER_END, edge.page), + runway=look.runway(history), demand=type(look.demand).__name__, + read_rows=look.read_rows(history, OLDER_END), pages=len(history.pages), + fragments=len(history.fragments), fragment_limit=history.fragment_limit, + unfilled=window.unfilled_rows) + results.write("top stalled: " + " ".join(f"{k}={v}" for k, v in facts.items()) + "\n") + + @staticmethod + async def settled(viewport: QWidget) -> None: + for _ in range(100): + if QScroller.scroller(viewport).state() == QScroller.State.Inactive: + return + await asyncio.sleep(0.05) + + async def taps(self, window, results) -> None: + """Real touch through the window, as Android delivers it (the app classifies each + press there, `FingerPress`): a tap on a message whose head is above the viewport; a + tap that stops a fling; a drag that starts on a row.""" + finger = QTest.createTouchDevice() + viewport, x = window.viewport(), window.viewport().width() // 2 + top_level = viewport.window() + handle = top_level.windowHandle() + + def at(point: QPoint) -> QPoint: + return viewport.mapTo(top_level, point) + + def touch(sequence) -> None: + """Deliver one touch step from a Qt timer: its commit processes events, which + inside this drive's asyncio task would step other tasks re-entrantly.""" + QTimer.singleShot(0, sequence.commit) + + model_rows = window.model_rows + await self.settled(viewport) + # Away from both ends, so a row is cut by the top and a drag has room both ways: back + # to the latest, then a viewport and a half up from it. + window.jump_to_latest() + await asyncio.sleep(2.0) + window.scroll_y = max(0, window.max_scroll_y - int(viewport.height() * 1.5) + 37) + await asyncio.sleep(1.0) + results.write(f"taps from scroll_y={window.scroll_y:.0f} of {window.max_scroll_y:.0f}\n") + # (1) the row the viewport's top cuts through: its head is above. + index = window.indexAt(QPoint(x, 1)) + rect = window.visualRect(index) + if index.isValid() and rect.top() < 0: + head = index.data(HistoryRows.FRAGMENT).message_head(model_rows.fragments) + point = QPoint(x, max(4, min(rect.bottom(), viewport.height()) // 2)) + before = window.scroll_y + touch(QTest.touchEvent(handle, finger).press(0, at(point))) + await asyncio.sleep(0.06) + released = time.perf_counter() + touch(QTest.touchEvent(handle, finger).release(0, at(point))) + moved = None + while time.perf_counter() - released < 2.0: + if moved is None and window.scroll_y != before: + moved = time.perf_counter() + if moved is not None and window.head_reveal is None: + break + await asyncio.sleep(0.002) + row = model_rows.row_of(head.key) + head_top = window.visualRect(model_rows.index(row, 0)).top() if row >= 0 else None + results.write(f"tap head-above: release_to_motion_ms={(moved - released) * 1000 if moved else -1:.0f} " + f"head_top_after={head_top} tapped_row={index.row()} head_row={row} " + f"cut_top={rect.top()} scroll_before={before:.0f} scroll_after={window.scroll_y:.0f}\n") + else: + results.write("tap head-above: no row cut by the top\n") + # (2) the rows still moving (a fling's momentum, started as QScroller starts one), then + # a tap: it stops them and reveals nothing. + await self.settled(viewport) + scroller = QScroller.scroller(viewport) + scroller.scrollTo(QPointF(0, max(0.0, window.scroll_y - viewport.height() * 3)), 1500) + await asyncio.sleep(0.15) + flinging = scroller.state() == QScroller.State.Scrolling + tap = QPoint(x, viewport.height() // 2) + touch(QTest.touchEvent(handle, finger).press(0, at(tap))) + await asyncio.sleep(0.06) + touch(QTest.touchEvent(handle, finger).release(0, at(tap))) + at_tap = window.scroll_y + await asyncio.sleep(0.6) + results.write(f"tap during fling: flinging={flinging} moved_after_tap_px={abs(window.scroll_y - at_tap):.0f} " + f"revealed={window.head_reveal is not None}\n") + # (3) a slow drag that starts on a row. + await self.settled(viewport) + before = window.scroll_y + start, end = QPoint(x, int(viewport.height() * 0.3)), QPoint(x, int(viewport.height() * 0.5)) + touch(QTest.touchEvent(handle, finger).press(0, at(start))) + await asyncio.sleep(0.15) + for step in range(1, 21): + touch(QTest.touchEvent(handle, finger).move(0, at(start + (end - start) * step / 20))) + await asyncio.sleep(0.02) + touch(QTest.touchEvent(handle, finger).release(0, at(end))) + await self.settled(viewport) + results.write(f"drag from a row: finger_px={end.y() - start.y()} rows_moved_px={before - window.scroll_y:.0f} " + f"revealed={window.head_reveal is not None}\n") + + class SettingsLiveScenario(Scenario): summary = ("change every app-wide setting that declares an Effect, one at a time, as the " "settings screen does, and report what Qt draws before and after each") @@ -3951,10 +4405,6 @@ async def run(self) -> None: print(f" {label}: FAILED {type(error).__name__}: {error}", flush=True) continue await asyncio.sleep(3.0) - # A dialog on the phone is no larger than its screen (ScreenWideWindow). - for window in QApplication.topLevelWidgets(): - if window is not self.app and window.isVisible(): - window.resize(min(window.width(), 412), min(window.height(), 640)) # The keymap opens filtered to the focused widget's keys; every key fills the table. for screen in self.app.findChildren(QtKeymapScreen): screen.focus_filter.setChecked(False) @@ -4038,6 +4488,12 @@ def main(arguments: list[str]) -> None: scenario = Scenario.member_named(own[0]) if os.environ.get("FRAME_TIME_WRITES"): time_settings_writes() + if os.environ.get("QT_DRIVE_PHONE_RENDERER"): + # The phone renders in a thread of this process (`InThreadRenderer`); a desktop + # drive uses a process pool. Measure what the phone runs. + from toad.qt import client_start + from toad.render_in_thread import InThreadRenderer + client_start._renderer_for_platform = lambda connection: InThreadRenderer() application = FrameProbe.application(arguments[:1]) install_glyph_fonts(application) # the entry's splash registers them; this drive has none FingerScrolling.install(application, scenario.finger_gesture()) diff --git a/tools/qt_inherit_ratchet.py b/tools/qt_inherit_ratchet.py index 8392bfc4d..652fc4f6b 100644 --- a/tools/qt_inherit_ratchet.py +++ b/tools/qt_inherit_ratchet.py @@ -96,6 +96,9 @@ } QT_ONLY = { + 'toad.qt.presented_window.PresentedWindow': "applies the shared WindowPresentation as a Qt window is shown: Qt opens a " + "window by show/open/exec, which all reach setVisible, so the presentation is applied there; Textual opens a " + "window by pushing a screen, which reads the same WindowPresentation family (forms.presentation.PanelPresentation)", 'toad.qt.conversation.ComposerPlaceholder': "a Qt composer's place held before it is built: Qt builds a view's widgets in " "its constructor, so a composer built there holds the view's first frame (and on Android races the first frame's EGL " "setup); Textual composes a screen's widgets and mounts them after its first frame, so it has no placeholder to hold", @@ -337,6 +340,17 @@ def bare() -> frozenset[str]: and not any(neutral(ancestor) for ancestor in cls.__mro__[1:])) +def unpresented() -> frozenset[str]: + """Qt windows opened over the app that do not inherit its one presentation owner. Every Qt + dialog is presented by `toad.qt.presented_window.PresentedWindow` (a phone fills the app + window, a desktop floats), so one that lays itself out has no ratchet baseline: zero.""" + from PySide6.QtWidgets import QDialog + from toad.qt.presented_window import PresentedWindow + return frozenset(path for path, cls in classes_under("toad").items() + if path.startswith("toad.qt.") and issubclass(cls, QDialog) + and not issubclass(cls, PresentedWindow)) + + def main() -> int: chains = ui_chains(candidate_modules()) loading = {module: chain for module, chain in chains.items() if chain} @@ -372,7 +386,11 @@ def main() -> int: for path in fixed: print(f"FIXED {path} now shares an ancestor (or is gone): delete its KNOWN_COPIES line") print(f"parallel copies: {len(found)} (ratchet baseline {len(KNOWN_COPIES)})") - return 1 if new or fixed or new_bare or rooted or new_loading or cleared or new_direct or gone_direct else 0 + windows = unpresented() + for path in sorted(windows): + print(f"UNPRESENTED {path} is a Qt dialog that does not inherit PresentedWindow: inherit it, so a phone fills the app window") + print(f"Qt dialogs outside PresentedWindow: {len(windows)} (ratchet baseline 0)") + return 1 if new or fixed or new_bare or rooted or new_loading or cleared or new_direct or gone_direct or windows else 0 if __name__ == "__main__": diff --git a/tools/tui_scroll_back.py b/tools/tui_scroll_back.py new file mode 100644 index 000000000..b9ac6f27a --- /dev/null +++ b/tools/tui_scroll_back.py @@ -0,0 +1,105 @@ +"""The Textual side of qt_drive's `history_scroll_back`: #comms on the same bus, at a phone-like +size, scrolled back by wheel steps until about 300 earlier rows load. + + PYTHONPATH=src python tools/tui_scroll_back.py PROFILE OUTDIR PROJECT + +Writes OUTDIR/scroll-back.txt: the idle loop, then per older page the time from the reader +reaching the top to its rows drawn, and the loop's lateness over the scroll-back (10 ms ticks, +the frame probe's measure), so the two frontends compare line for line. +""" + +import asyncio +import sys +import time +from pathlib import Path + +from agent_comms.projects.checkouts import Checkout +from textual import events + +from toad.app import ToadApp +from toad.client.connection import RemoteCoreConnection +from toad.client.history_preparation import OLDER_END +from toad.constants import WELCOME +from toad.launch_binding import NoAgent +from toad.navigation_context import NavigationContext +from toad.navigation_target import channel_target +from toad.widgets.history_anchor import HistoryWindow + +ROWS_WANTED, SECONDS = 300, 150 + + +async def main(profile: Path, out: Path, project: Path) -> None: + out.mkdir(parents=True, exist_ok=True) + results = (out / "scroll-back.txt").open("w", buffering=1) + app = ToadApp(agent_binding=NoAgent(), project_dir=Checkout(project), + connection=RemoteCoreConnection.read(profile)) + async with app.run_test(size=(46, 44)) as pilot: + async with asyncio.timeout(180): + while app.selected_mode != WELCOME: + await pilot.pause(0.1) + await channel_target("#comms").open(NavigationContext(app, app.selected_mode, app.project_dir, "user")) + await pilot.pause(4.0) + window = app.screen.query(HistoryWindow).first() + late: list[float] = [] + state = {"stop": False} + + async def ticker() -> None: + last = time.perf_counter() + while not state["stop"]: + await asyncio.sleep(0.01) + now = time.perf_counter() + late.append((now - last) * 1000 - 10) + last = now + + def rows() -> int: + return sum(len(history.fragments) for history in window.histories) + + def first_key(): + return next((history.fragments[0].key for history in window.histories if history.fragments), None) + + idle = asyncio.ensure_future(ticker()) + await asyncio.sleep(8) + state["stop"] = True + await idle + busy = sum(max(0.0, value) for value in late) / 8000 * 100 + results.write(f"idle: rows={rows()} worst_stall_ms={max(late):.0f} loop_busy={busy:.0f}%\n") + late.clear() + state["stop"] = False + tick = asyncio.ensure_future(ticker()) + start_rows, pages = rows(), [] + started = time.perf_counter() + deadline = started + SECONDS + def older_left() -> bool: + return any(OLDER_END.visible_more(history) for history in window.histories) + + while (rows() - start_rows < ROWS_WANTED and time.perf_counter() < deadline + and (older_left() or window.scroll_y > 0)): + first, reached = first_key(), None + while time.perf_counter() < deadline and first_key() == first: + if window.scroll_y <= 0 and not older_left(): + break # the reader is at the start of the history + # A wheel step over the history, as the terminal delivers one. + window.post_message(events.MouseScrollUp(window, 20, 20, 0, -1, 0, False, False, False, 20, 20)) + if reached is None and window.scroll_y <= 0: + reached = time.perf_counter() + await asyncio.sleep(0.016) + if first_key() != first: + await pilot.pause(0) + waited = (time.perf_counter() - reached) * 1000 if reached else 0.0 + pages.append(waited) + results.write(f"page {len(pages)} rows={rows()} visible_after_top_ms={waited:.0f}\n") + state["stop"] = True + await tick + span = time.perf_counter() - started + busy = sum(max(0.0, value) for value in late) / (span * 1000) * 100 + buckets = " ".join(f">={bound}:{sum(value >= bound for value in late)}" for bound in (16, 33, 50, 100, 200, 500)) + ordered = sorted(pages) + results.write(f"scroll back: span={span:.0f}s pages={len(pages)} rows_loaded={rows() - start_rows} " + f"visible_after_top_ms_median={ordered[len(ordered) // 2] if ordered else 0:.0f} " + f"max={ordered[-1] if ordered else 0:.0f} worst_stall_ms={max(late):.0f} " + f"loop_busy={busy:.0f}% {buckets}\n") + print((out / "scroll-back.txt").read_text(), flush=True) + + +if __name__ == "__main__": + asyncio.run(main(Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])))