Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions src/toad/qt/channel_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down
29 changes: 27 additions & 2 deletions src/toad/qt/composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 3 additions & 2 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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

Expand Down
167 changes: 146 additions & 21 deletions src/toad/qt/menu.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
"""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

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


Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down
2 changes: 0 additions & 2 deletions src/toad/qt/thread_comms_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading