From aaede917bb47b3cc4818badde0cfe239d305a9ac Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 04:33:38 -0500 Subject: [PATCH] qt menus float as one surface; composer buttons are the input box's height Every pop-up Toad opens (the application menu, a message's and a sidebar row's menu, the bus-connect choices, a sort choice) is the window's one QtMenu. It is a child of the window in no layout, placed at the anchor it was asked from (under it, or above it where there is no room below), so opening or closing it moves nothing underneath. A tap outside closes it and does nothing else (the press and its release are eaten); Escape closes it ahead of any shortcut bound to Escape; Back closes it through go_back. The sort choice's QMenu (a top-level popup window, the EGL hazard on Android) is gone; it lists its choices in the same menu under its button. The menu is one surface: the float tone, one rule-coloured border, flat rows with the float hover tone and muted descriptions. The per-row button boxes and the chrome frame around it are gone. It is the window's width up to 420 px and scrolls only when its rows do not fit. Every button in the composer's box row is the box's one-line height, pinned to the bottom of a taller box (Composer.fit_buttons). tools/qt_drive.py menu_float checks each menu changes no pixel outside it, the outside tap and Escape, the anchors, the composer's button, and quits with the menu open. Depends on the contrast fork's ui_theme roles (FloatToneColour, FloatHoverToneColour, RuleColour). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/channel_sort.py | 51 +++++---- src/toad/qt/composer.py | 29 +++++- src/toad/qt/history.py | 5 +- src/toad/qt/menu.py | 167 ++++++++++++++++++++++++++---- src/toad/qt/thread_comms_panel.py | 2 - src/toad/qt/window.py | 29 +++--- tools/qt_drive.py | 131 ++++++++++++++++++++++- 7 files changed, 344 insertions(+), 70 deletions(-) diff --git a/src/toad/qt/channel_sort.py b/src/toad/qt/channel_sort.py index 452d22fdb..ff85de4cc 100644 --- a/src/toad/qt/channel_sort.py +++ b/src/toad/qt/channel_sort.py @@ -4,7 +4,8 @@ Both inherit `SortControlBase` (the current form, label and tooltip) and `CommsSortWrite` (the request each order is stored by, written through the observed Core) — the same two owners Textual's `ChannelListSort` and `ChannelSortChoice` inherit — so the two frontends -label and write an order identically. This module adds only the QToolButton and its menu. +label and write an order identically. This module adds only the QToolButton; its choices +open in the window's one pop-up menu (`QtMenu`). """ from __future__ import annotations @@ -15,56 +16,54 @@ from typing import TYPE_CHECKING from PySide6.QtCore import Qt -from PySide6.QtGui import QAction -from PySide6.QtWidgets import QMenu, QToolButton, QWidget +from PySide6.QtWidgets import QToolButton, QWidget from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta from agent_comms.display_order import ChannelSort, DisplayOrder, ThreadSort +from toad.client.menu_entry import MenuEntry from toad.client.sort_control import ChannelListOrder, ChannelMemberOrder, ChannelSortForm, CommsSortWrite, SortControlBase, ThreadSortForm +from toad.qt.menu import QtMenu + if TYPE_CHECKING: from toad.qt.window import QtToadApp class QtSortButton[Order: DisplayOrder](SortControlBase[Order], QToolButton, metaclass=PyQtWidgetMeta): - """A sort choice as a one-line button whose menu lists its form's orders, then any - settings it toggles; a pick hands the order to `write_picked`, and only the observation - that follows repaints the label.""" + """A sort choice as a one-line button whose tap lists its form's orders, then any + settings it toggles, in the window's pop-up menu under the button; a pick hands the + order to `write_picked`, and only the observation that follows repaints the label.""" def __init__(self, form_type, scope: str, parent: QWidget | None = None) -> None: super().__init__(form_type=form_type, scope=scope, parent=parent) self.setWindowFlags(Qt.WindowType.Widget) self.setAutoRaise(True) - self.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) - # The label already ends in the shared "▾"; Qt's own menu arrow would draw a second. - self.setStyleSheet("QToolButton { padding: 0px; border: none; }" - "QToolButton::menu-indicator { image: none; width: 0px; }") + # The label already ends in the shared "▾". + self.setStyleSheet("QToolButton { padding: 0px; border: none; }") # One text line tall, as Textual's one-row segment. self.setFixedHeight(self.fontMetrics().lineSpacing()) self._form_type = form_type - menu = QMenu(self) - menu.aboutToShow.connect(self._fill) - self.setMenu(menu) - self._fill() + self.clicked.connect(self.open_choices) self.sort_changed() def visibility_fields(self): """Settings the menu toggles beside the orders, as Textual's `SortChoice` lists them.""" return () - def _fill(self) -> None: - menu = self.menu() - menu.clear() + def choice_entries(self) -> tuple[MenuEntry, ...]: + """The orders, then the settings this choice toggles, each with its current mark.""" choices = self._form_type.choices - for order in choices.choices(): - action = QAction(choices.label(order), menu) - action.triggered.connect(partial(self._picked, order)) - menu.addAction(action) - for path in self.visibility_fields(): - field = path.bind(self.saved_settings().state) - action = QAction(f"{'✓' if field.value else '○'} {field.label}", menu) - action.triggered.connect(partial(self._toggle_visibility, path)) - menu.addAction(action) + orders = tuple(MenuEntry(label=choices.label(order), run=partial(self._picked, order)) + for order in choices.choices()) + toggles = tuple( + MenuEntry(label=f"{'✓' if field.value else '○'} {field.label}", + run=partial(self._toggle_visibility, path)) + for path in self.visibility_fields() + for field in (path.bind(self.saved_settings().state),)) + return orders + toggles + + def open_choices(self) -> None: + QtMenu.of(self).show_entries(self.choice_entries(), QtMenu.anchor_of(self)) def saved_settings(self): raise NotImplementedError(f"{type(self).__name__} toggles no settings") diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index ee5dd3c2b..98897c1a7 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -339,7 +339,9 @@ def __init__(self, host: ComposerHost, renderer: QtLineRenderer, placeholder: st self.send_button = QPushButton(SubmitAction.title, self) self.send_button.setFocusPolicy(Qt.FocusPolicy.NoFocus) # tapping keeps the keyboard up self.send_button.clicked.connect(self.submit) - # The row's margins are the input box setting's frame margin (`place_input_box`). + # The row's margins are the input box setting's frame margin (`place_input_box`); every + # button beside the box is the box's one-line height, pinned to its bottom + # (`fit_buttons`). self.frame_row = frame_row = QHBoxLayout() frame_row.addWidget(self.frame, 1) frame_row.addWidget(self.send_button, 0, Qt.AlignmentFlag.AlignBottom) @@ -383,6 +385,25 @@ def cells(spacing): left, top, right, bottom = cells(box.label_padding) self.glyph.setContentsMargins(left, top, right, bottom) self.focus_changed(self.editor.hasFocus()) + self.fit_buttons() + + def one_line_box_height(self) -> int: + """The input box's height holding one line: the editor's one-line height, the box's + padding, and its border where it draws one.""" + padding = self.frame.layout().contentsMargins() + border = 2 if self.settings.ui.input.box.bordered else 0 + return self.editor_height(1) + padding.top() + padding.bottom() + border + + def fit_buttons(self) -> None: + """Every button in the box's row (send, and any a composer adds beside it) is the + box's one-line height and at least as wide as tall: level with a one-line box, and + pinned to the bottom of a taller one (each is added bottom-aligned).""" + height = self.one_line_box_height() + for index in range(self.frame_row.count()): + button = self.frame_row.itemAt(index).widget() + if button is not None and button is not self.frame: + button.setFixedHeight(height) + button.setMinimumWidth(height) def update_prompt(self) -> None: """A leading symbol or the placeholder setting changed: draw both again.""" @@ -447,7 +468,11 @@ def fit_height(self) -> None: lines = max(1, min(5, typed)) self.editor.setVerticalScrollBarPolicy( Qt.ScrollBarPolicy.ScrollBarAsNeeded if typed > 5 else Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.editor.setFixedHeight(self.editor.fontMetrics().lineSpacing() * lines + 24) + self.editor.setFixedHeight(self.editor_height(lines)) + + def editor_height(self, lines: int) -> int: + """The editor's height showing `lines` lines.""" + return self.editor.fontMetrics().lineSpacing() * lines + 24 @property def text(self) -> str: diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index d28ed9c8d..ed99a28c6 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -811,7 +811,8 @@ class QtHistoryWindow(ReaderWindow, WorkspaceHosted, VirtualRowView, # Emitted when the viewer right-clicks or long-presses a message row; carries the # fragment under that point. Consumers (ConversationView) build a block menu from # the shared `MenuCommand` family and offer it through the host's offer panel. - block_menu_requested = Signal(object, name="blockMenuRequested") + #: The row's fragment, and where it was pressed in the window's coordinates. + block_menu_requested = Signal(object, QPoint, name="blockMenuRequested") history: QtConversationHistory # `scroll_revision` + `history_change` are declared on JumpsToLatest (shared with Textual). @@ -1060,7 +1061,7 @@ def _emit_block_menu_at(self, point: QPoint) -> None: fragment = self.model_rows.data(index, HistoryRows.FRAGMENT) if fragment is None: return - self.block_menu_requested.emit(fragment) + self.block_menu_requested.emit(fragment, self.viewport().mapTo(self.window(), point)) # Geometry, in pixels diff --git a/src/toad/qt/menu.py b/src/toad/qt/menu.py index 3bd1ff186..c59627e30 100644 --- a/src/toad/qt/menu.py +++ b/src/toad/qt/menu.py @@ -1,9 +1,15 @@ -"""Qt's structured menu widget: renders a tuple of toolkit-neutral MenuEntry rows as +"""Qt's one pop-up menu: renders a tuple of toolkit-neutral MenuEntry rows as `[bold key] [label / description]`, matching the Textual `Menu` widget's row structure. -A single widget renders both the application (hamburger) menu and the message-context -(long-press on a row) menu, so the two paths share rendering, layout and click handling, -and the only thing that differs is which MenuEntry tuple each one supplies. +A single widget renders every pop-up Toad opens (the application menu, a message's and a +sidebar row's held/right-click menu, the bus-connect choices, a sort choice), so they share +rendering, placement, dismissal and click handling, and the only thing that differs is +which MenuEntry tuple each one supplies and where it was asked for. + +It floats: a child of the window placed over the window's content and outside every layout, +so opening or closing it moves nothing underneath. It is not a top-level window (a QMenu or +a `Qt.Popup`): on Qt for Android every QWindow needs its own EGL surface, and a second one +deadlocks the compositor. """ from __future__ import annotations @@ -11,22 +17,27 @@ from collections.abc import Callable, Iterable from functools import partial -from PySide6.QtCore import Qt +from PySide6.QtCore import QEvent, QObject, QRect, Qt from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( + QApplication, QFrame, QHBoxLayout, QLabel, QPushButton, + QScrollArea, QVBoxLayout, QWidget, ) +from ui_theme.scheme import FloatHoverToneColour, FloatToneColour, MutedColour, RuleColour + from pyqt_reactive.widgets.fitted_text import ElidedLine from toad.client.block_menu import BlockMenu from toad.client.input_modality import InputModality, KeyboardInput, TouchInput from toad.client.menu_entry import MenuEntry +from toad.qt.lines import QtLineRenderer from toad.qt.metrics import UiGap @@ -76,7 +87,7 @@ def __init__(self, entry: MenuEntry, menu: QtMenu, chosen: Callable[[MenuEntry], if entry.description and not menu.input_modality.describes_inline(): description = ElidedLine(entry.description) description.setParent(self._button) - description.setEnabled(False) # the theme's muted text, as a secondary line + description.setObjectName("toad-menu-description") # muted (`QtMenu.paint`) text.addWidget(description) lines = 2 inner.addLayout(text, 1) @@ -89,32 +100,146 @@ def _fire(self) -> None: class QtMenu(BlockMenu, QFrame): - """A column of MenuEntry rows. The container itself is a QFrame (not a top-level - window — important on Qt-for-Android where every QWindow needs its own EGL surface - and a floating menu would deadlock the compositor). Its visibility is managed by - whatever opened it (hamburger button, long-press handler). `show_entries()` swaps - the current entry list in place and shows the menu; `hide()` is inherited.""" - - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) + """The window's pop-up menu: one surface of MenuEntry rows floating over the window's + content (see the module docstring for why it is a child widget). `show_entries` lists + the rows and places the menu at the `anchor` it was asked from: under it, or above it + where there is no room below, kept inside the window. A tap outside the menu closes it + and does nothing else (the press and its release are eaten), as does Escape; Back closes + it through the window's `go_back`. A choice closes it and runs the entry. + + Its chrome is one surface: the theme's float tone, one rule-coloured border, the rows + flat on it, the float hover tone under a finger or the pointer (`paint`).""" + + #: The widest a menu draws, in pixels; a phone's narrower window caps it first, and + #: the rows elide within whichever is narrower. + WIDEST = 420 + + def __init__(self, window: QWidget) -> None: + super().__init__(window) self.setWindowFlags(Qt.WindowType.Widget) + self.setObjectName("toad-menu") self.input_modality = platform_input() - self._layout = QVBoxLayout(self) - self._layout.setContentsMargins(UiGap.frame, UiGap.normal, UiGap.frame, UiGap.normal) - self._layout.setSpacing(UiGap.tight) + self._anchor = QRect() + self._eating_release = False + self._rows = QWidget() + self._rows.setObjectName("toad-menu-rows") + self._layout = QVBoxLayout(self._rows) + self._layout.setContentsMargins(0, 0, 0, 0) + self._layout.setSpacing(0) + self._scroll = QScrollArea(self) + self._scroll.setFrameShape(QFrame.Shape.NoFrame) + self._scroll.setWidgetResizable(True) + self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._scroll.setWidget(self._rows) + outer = QVBoxLayout(self) + outer.setContentsMargins(1, UiGap.normal, 1, UiGap.normal) # 1px: inside the border + outer.setSpacing(0) + outer.addWidget(self._scroll) + window.installEventFilter(self) self.hide() - def show_entries(self, entries: Iterable[MenuEntry]) -> None: - """Replace the rows with ``entries`` and show the menu. A selection runs the - entry's action and dismisses the menu.""" + @classmethod + def of(cls, widget: QWidget) -> QtMenu: + """The pop-up menu of the window `widget` is in: the window's own direct child.""" + return widget.window().findChild(cls, "toad-menu", Qt.FindChildOption.FindDirectChildrenOnly) + + @staticmethod + def anchor_of(widget: QWidget) -> QRect: + """`widget`'s rectangle in its window, as `show_entries` takes an anchor.""" + return QRect(widget.mapTo(widget.window(), widget.rect().topLeft()), widget.size()) + + def paint(self, renderer: QtLineRenderer) -> None: + """One surface in the renderer's theme: the float tone (a tier above what it floats + over) and one rule-coloured border; rows flat on it, the float hover tone under a + finger or the pointer; descriptions muted.""" + hover = renderer.theme(FloatHoverToneColour) + self.setStyleSheet( + f"#toad-menu {{ background: {renderer.theme(FloatToneColour)};" + f" border: 1px solid {renderer.theme(RuleColour)}; border-radius: 6px; }}" + "#toad-menu QScrollArea, #toad-menu-rows { background: transparent; border: none; }" + "#toad-menu QPushButton { background: transparent; border: none; border-radius: 0; padding: 0;" + " text-align: left; }" + f"#toad-menu QPushButton:hover, #toad-menu QPushButton:pressed {{ background: {hover}; }}" + f"#toad-menu-description {{ color: {renderer.theme(MutedColour)}; }}") + + def show_entries(self, entries: Iterable[MenuEntry], anchor: QRect | None = None) -> None: + """Replace the rows with ``entries`` and show the menu at ``anchor`` (a rectangle in + the window's coordinates: the button or the pressed point that asked for it), or at + the top of the window with none. A selection runs the entry's action and dismisses + the menu.""" while self._layout.count(): item = self._layout.takeAt(0) widget = item.widget() if widget is not None: + widget.setParent(None) widget.deleteLater() for entry in entries: - self._layout.addWidget(QtMenuRow(entry, self, self._chose, parent=self)) + self._layout.addWidget(QtMenuRow(entry, self, self._chose, parent=self._rows)) + self._anchor = anchor if anchor is not None else QRect() + self.place() self.show() + self.raise_() + QApplication.instance().installEventFilter(self) + + def place(self) -> None: + """Under the anchor (or above it, where there is more room there and too little + below), inside the window by a frame gap, WIDEST wide or the window's width, as + tall as its rows within the room it has; it scrolls only when they do not fit.""" + window = self.parentWidget() + area = window.rect().adjusted(UiGap.frame, UiGap.frame, -UiGap.frame, -UiGap.frame) + margins = self.layout().contentsMargins() + width = min(area.width(), self.WIDEST) + wanted = self._rows.sizeHint().height() + margins.top() + margins.bottom() + anchor = self._anchor + if not anchor.isValid(): + geometry = QRect(area.left() + (area.width() - width) // 2, area.top(), width, min(wanted, area.height())) + else: + below, above = area.bottom() - anchor.bottom(), anchor.top() - area.top() + x = max(area.left(), min(anchor.left(), area.right() + 1 - width)) + if wanted <= below or below >= above: + geometry = QRect(x, anchor.bottom() + 1, width, min(wanted, below)) + else: + height = min(wanted, above) + geometry = QRect(x, anchor.top() - height, width, height) + self._scroll.setVerticalScrollBarPolicy( + Qt.ScrollBarPolicy.ScrollBarAlwaysOff if geometry.height() >= wanted + else Qt.ScrollBarPolicy.ScrollBarAsNeeded) + self.setGeometry(geometry) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual method name + kind = event.type() + if watched is self.parentWidget() and kind == QEvent.Type.Resize and self.isVisible(): + self.place() + return False + if self._eating_release: + if kind in (QEvent.Type.MouseButtonRelease, QEvent.Type.MouseButtonDblClick): + self._eating_release = False + QApplication.instance().removeEventFilter(self) + return True + return kind == QEvent.Type.MouseMove + if not self.isVisible(): + return False + if kind == QEvent.Type.MouseButtonPress and not self.geometry().contains( + self.parentWidget().mapFromGlobal(event.globalPosition().toPoint())): + self._eating_release = True + self.hide() + return True + if kind == QEvent.Type.ShortcutOverride and event.key() == Qt.Key.Key_Escape: + # Escape is the open menu's: no shortcut bound to it (the composer's dismiss) runs, + # and the key press that follows comes here and closes the menu. + event.accept() + return True + if kind == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape: + self.hide() + return True + return False + + def hideEvent(self, event) -> None: # noqa: N802 - Qt virtual method name + """Closed: the app stops passing its events here, unless the outside tap that + closed it still has its release to eat.""" + if not self._eating_release: + QApplication.instance().removeEventFilter(self) + super().hideEvent(event) def _chose(self, entry: MenuEntry) -> None: self.hide() diff --git a/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index d1adbade2..59de28c32 100644 --- a/src/toad/qt/thread_comms_panel.py +++ b/src/toad/qt/thread_comms_panel.py @@ -24,12 +24,10 @@ from agent_comms.registry.relationships import SortableRelationshipGroup from PySide6.QtCore import Qt from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta -from PySide6.QtGui import QAction from PySide6.QtWidgets import ( QCheckBox, QHBoxLayout, QLabel, - QMenu, QToolButton, QTreeWidget, QTreeWidgetItem, diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index ee8ab44d4..249c05f4b 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -23,7 +23,7 @@ from agent_comms.transport.request import CoreAccess from agent_comms.ui_model.sidebar import ChannelRowModel, SidebarModel from formbridge.operations import OperationKind -from PySide6.QtCore import QEvent, QMargins, QObject, QPoint, Qt, QTimer +from PySide6.QtCore import QEvent, QMargins, QObject, QPoint, QRect, QSize, Qt, QTimer from PySide6.QtGui import QColor, QKeySequence, QShortcut from PySide6.QtWidgets import ( QApplication, @@ -571,7 +571,8 @@ def offer(self, point: QPoint) -> None: return entries = item.menu_entries(self.listing) if entries: - self.listing.host.offer_entries(entries) + pressed = rows.viewport().mapTo(rows.window(), point) + self.listing.host.offer_entries(entries, QRect(pressed, QSize(1, 1))) class QtWelcomeOrigin(ProjectSessionOrigin): @@ -1411,12 +1412,13 @@ def thread_identity(self): # through `widgets/menu.Menu`. Keeping the action list derived means a new menu # command declared in `src/toad/menus.py` reaches Qt without any edit here. - def open_block_menu(self, fragment: QtWireFragment) -> None: + def open_block_menu(self, fragment: QtWireFragment, pressed: QPoint) -> None: + """The block menu for `fragment`, at `pressed` (the window's coordinates).""" self.held_fragment = fragment entries = QtMenu.command_entries(_block_menu_commands(fragment), self.app.settings, self._run_block_menu_command) if entries: - self.app.offer_entries(entries) + self.app.offer_entries(entries, QRect(pressed, QSize(1, 1))) def _run_block_menu_command(self, command: MenuCommand) -> None: result = command.apply(self) @@ -1641,13 +1643,11 @@ def __init__(self, connection: CoreConnection, project: Checkout, chrome_layout = QVBoxLayout(chrome) chrome_layout.setContentsMargins(0, 0, 0, 0) chrome_layout.setSpacing(0) - # QtMenu is the shared rendering for both the hamburger (application) menu and - # the row-context (message) menu. Its rows render MenuEntry data (bold key - # shortcut + label), matching Textual's MenuKey/MenuDescription widgets. Parent - # is QtToadApp so the menu is a child QWidget, not a top-level QWindow — the - # EGL-deadlock hazard that killed off QMessageBox applies to any popup window. + # QtMenu is the window's one pop-up menu (the application menu, the held/right-click + # row menus, the bus-connect choices, a sort choice). It floats over the content as + # a child of the window, in no layout, so opening it moves nothing (`QtMenu`). self.menu_panel = QtMenu(self) - chrome_layout.addWidget(self.menu_panel) + self.renderer.themed(self.menu_panel, lambda: self.menu_panel.paint(self.renderer)) # Bus switcher: inline overlay panel for the hamburger "Switch bus" entry. # Registered as a `BusListing` so `tailnet_answered` routes answers to it # while shown (same shape as Welcome, which is always registered). @@ -1999,7 +1999,7 @@ def show_menu(self) -> None: if self.menu_panel.isVisible(): self.menu_panel.hide() return - self.menu_panel.show_entries(self._application_menu_entries()) + self.menu_panel.show_entries(self._application_menu_entries(), QtMenu.anchor_of(self.menu)) def _application_menu_entries(self) -> tuple[MenuEntry, ...]: """Project ApplicationAction.menu(self) into MenuEntry rows. The key_display @@ -2026,10 +2026,11 @@ def offer(self, actions: tuple[OfferedAction, ...]) -> None: — the same widget the hamburger and the message-row menus use.""" self.offer_entries(tuple(MenuEntry.from_offered(action) for action in actions)) - def offer_entries(self, entries: tuple[MenuEntry, ...]) -> None: + def offer_entries(self, entries: tuple[MenuEntry, ...], anchor: QRect | None = None) -> None: """Rich-row API: callers that have `MenuEntry` with keybindings and descriptions - (the hamburger menu, the row-context menu) populate the shared QtMenu directly.""" - self.menu_panel.show_entries(entries) + (the hamburger menu, the row-context menu) populate the shared QtMenu directly, at + `anchor` in this window's coordinates (where they were asked from).""" + self.menu_panel.show_entries(entries, anchor) def offer_bus_connect(self, decision: BusConnectDecision) -> None: """Render the shared bus-connect decision through the same menu panel the hamburger diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 784514eec..560837314 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -25,8 +25,8 @@ from typing import ClassVar import qasync -from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt -from PySide6.QtGui import QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent +from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QRect, Qt +from PySide6.QtGui import QContextMenuEvent, QImage, QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent from PySide6.QtTest import QTest from PySide6.QtWidgets import QAbstractButton, QAbstractScrollArea, QDialog, QLabel, QScroller, QStyleOptionViewItem, QApplication, QPushButton, QWidget @@ -82,7 +82,8 @@ from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle from toad.client.input_modality import KeyboardInput, TouchInput from toad.qt.float_layer import QtNoticeCard -from toad.qt.menu import QtMenuRow +from toad.qt.menu import QtMenu, QtMenuRow +from toad.qt.channel_sort import QtChannelListSort from toad.qt.window import ConversationRow, ConversationView, MenuActionRun, QtToadApp from toad.conversation_turn import LocalTurnBinding from toad.core.events import TextAgentFail, UnsupportedResumeAgentFail @@ -809,6 +810,130 @@ async def run(self) -> None: self.report("3-notice", notices=app.float_layer.shown_notices(), shown=app.float_layer.isVisible()) +def changed_outside(before: QImage, after: QImage, kept: QRect) -> int: + """How many pixels differ between two grabs of one window outside `kept`.""" + before, after = (image.convertToFormat(QImage.Format.Format_RGB32) for image in (before, after)) + width, height = before.width(), before.height() + if (width, height) != (after.width(), after.height()): + return width * height + left, right = max(0, kept.left()), min(width, kept.right() + 1) + changed = 0 + for y in range(height): + a, b = before.constScanLine(y).tobytes(), after.constScanLine(y).tobytes() + if kept.top() <= y <= kept.bottom(): + pairs = ((a[:left * 4], b[:left * 4]), (a[right * 4:], b[right * 4:])) + else: + pairs = ((a, b),) + for one, other in pairs: + if one != other: + changed += sum(1 for x in range(0, len(one), 4) if one[x:x + 4] != other[x:x + 4]) + return changed + + +class MenuFloatScenario(Scenario): + summary = ("every pop-up menu floats: the page keeps every pixel outside it, an outside tap " + "closes it without touching what was under it, Escape closes it; the composer's " + "buttons are the input box's one-line height; then quit with the menu open") + + async def floats(self, opening, step: str, faults: list[str]) -> None: + """Open a menu, check nothing underneath moved, screenshot it.""" + app, menu = self.app, self.app.menu_panel + menu.hide() + await asyncio.sleep(0.4) + for attempt in range(3): # a live row may repaint between the grabs; retry such a race + before = app.grab().toImage() + opening() + QApplication.processEvents() + after = app.grab().toImage() + moved = changed_outside(before, after, menu.geometry()) + if moved == 0 or attempt == 2: + break + menu.hide() + await asyncio.sleep(0.6) + self.report(step, shown=menu.isVisible(), geometry=menu.geometry().getRect(), moved_pixels=moved, + rows=[row.label.text() for row in menu.findChildren(QtMenuRow)]) + if not menu.isVisible(): + faults.append(f"{step}: the menu did not open") + if moved: + faults.append(f"{step}: opening it changed {moved} pixels outside it") + if menu.parentWidget() is not app or menu.isWindow() or app.navigation.layout().indexOf(menu) != -1: + faults.append(f"{step}: the menu is not a free child of the window") + + async def run(self) -> None: + app = self.app + app.resize(int(os.environ.get("WIDTH", 412)), 915) + await self.open_named("#comms") + faults: list[str] = [] + menu = app.menu_panel + # 1. The application menu, from its button. + await self.floats(app.menu.click, "1-app-menu", faults) + # 2. A tap outside closes it and the tap goes nowhere else. + tabs_before, page_before = self.tabs(), self.page + history = self.page.messages.viewport() + outside = next(QPoint(x, 12) for x in (history.width() - 12, 12) + if not menu.geometry().contains(history.mapTo(app, QPoint(x, 12)))) + QTest.mouseClick(history, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, outside) + await asyncio.sleep(0.3) + self.report("2-outside-tap", shown=menu.isVisible()) + if menu.isVisible(): + faults.append("2: an outside tap left the menu open") + if self.tabs() != tabs_before or self.page is not page_before: + faults.append("2: the outside tap also acted on what was under it") + # 3. Escape closes it. + app.menu.click() + await asyncio.sleep(0.3) + QTest.keyClick(app, Qt.Key.Key_Escape) + await asyncio.sleep(0.3) + self.report("3-escape", shown=menu.isVisible()) + if menu.isVisible(): + faults.append("3: Escape left the menu open") + # 4. A message's menu, where the row was pressed (a right-click; a held finger asks the same). + messages = self.page.messages + point = QPoint(messages.viewport().width() // 2, messages.viewport().height() // 2) + + def right_click() -> None: + QApplication.sendEvent(messages.viewport(), QContextMenuEvent( + QContextMenuEvent.Reason.Mouse, point, messages.viewport().mapToGlobal(point))) + await self.floats(right_click, "4-message-menu", faults) + pressed = messages.viewport().mapTo(app, point) + if menu.isVisible() and not (menu.geometry().top() == pressed.y() + 1 or menu.geometry().bottom() == pressed.y() - 1): + faults.append(f"4: the message menu is not at the pressed row ({pressed.y()} vs {menu.geometry().getRect()})") + menu.hide() + # 5. A sort choice's menu, under its button. + sorts = app.findChildren(QtChannelListSort) + if sorts and not app.sidebar.isVisible(): + app.show_sidebar() + await asyncio.sleep(0.5) + if sorts and sorts[0].isVisible(): + await self.floats(sorts[0].click, "5-sort-menu", faults) + under = QtMenu.anchor_of(sorts[0]) + if menu.isVisible() and under.bottom() + 1 != menu.geometry().top() and menu.geometry().bottom() + 1 != under.top(): + faults.append(f"5: the sort menu is not at its button ({under.getRect()} vs {menu.geometry().getRect()})") + menu.hide() + app.hide_sidebar() + await asyncio.sleep(0.4) + else: + print("5-sort-menu: no visible channel-list sort button here; skipped", flush=True) + # 6. The composer's buttons, one line then three. + composer = self.page.composer + for lines in (1, 3): + await self.type("\n".join(["composer line"] * lines)) + await asyncio.sleep(0.3) + frame, send = composer.frame.geometry(), composer.send_button.geometry() + self.report(f"6-composer-{lines}-lines", box=frame.getRect(), send=send.getRect()) + if send.height() != composer.one_line_box_height(): + faults.append(f"6: with {lines} line(s) the send button is {send.height()}px, the one-line box {composer.one_line_box_height()}px") + if send.bottom() != frame.bottom(): + faults.append(f"6: with {lines} line(s) the send button's bottom {send.bottom()} is not the box's {frame.bottom()}") + composer.editor.clear() + # 7. Quit with the menu open: the drive's own close ends the app with it showing. + app.menu.click() + await asyncio.sleep(0.3) + self.report("7-open-at-quit", shown=menu.isVisible()) + if faults: + raise AssertionError("menu_float faults:\n" + "\n".join(faults)) + + class FeedbackScenario(Scenario): summary = ("the reader's feedback at a Pixel 8a's width: the wait a slow thread open shows in place, " "#comms' first page loading, an operation's wait floating over the page, a notice that "