diff --git a/src/toad/client/relationship_row_menu.py b/src/toad/client/relationship_row_menu.py index 95b27231b..5f48e7013 100644 --- a/src/toad/client/relationship_row_menu.py +++ b/src/toad/client/relationship_row_menu.py @@ -18,7 +18,20 @@ from collections.abc import Callable +from agent_comms.registry.relationships import RelationshipEntry + from toad.client.menu_entry import MenuEntry +from toad.navigation_target import NavigationTarget, ThreadTarget + + +def entry_target(entry: RelationshipEntry) -> NavigationTarget: + """Where a thread's relationship row opens: the person's own thread, else the target + it names. Both frontends' Comms rows open it (Textual's `RelationshipRow`, Qt's + `QtThreadCommsPanel`).""" + person = entry.person + if person is None: + return NavigationTarget.named(entry.target) + return ThreadTarget(person.thread.name) def menu_entries_for_row( diff --git a/src/toad/pointer_gesture.py b/src/toad/pointer_gesture.py index 55e09f3f3..ae8f978e1 100644 --- a/src/toad/pointer_gesture.py +++ b/src/toad/pointer_gesture.py @@ -1,8 +1,10 @@ -"""One pointer gesture on a draggable control, for every frontend. +"""One pointer gesture on a control, for every frontend. A press that moves past the control's ``drag_threshold`` becomes a drag; a press released -before that is a click. Textual's `CapturedDrag` and Qt's `QtGripPointer` both feed their own -pointer events into these states, so a click and a drag mean the same on either. +before that is a click; a press its control reports held (still, for the platform's +press-and-hold time) becomes a hold, which the control answers or doesn't. Textual's +`CapturedDrag`, Qt's `QtGripPointer` and Qt's application-wide `FingerPress` feed their own +pointer events into these states, so a click, a drag and a hold mean the same on each. """ from __future__ import annotations @@ -30,12 +32,20 @@ def clicked(self) -> None: def dragged(self) -> None: """A drag let go, after its last ``drag_to``: by default nothing more happens.""" + def held(self) -> bool: + """A press held still: the control answers with what a hold means to it (a menu) and + says whether it did. By default a hold means nothing and the press goes on.""" + return False + class Gesture: - """Where one pointer gesture on a control stands: nothing, a press, or a drag.""" + """Where one pointer gesture on a control stands: nothing, a press, a drag or a hold.""" # Whether a newer pointer move may replace a pending one: only while the gesture holds it. holds_pointer: ClassVar[bool] = True + # Whether the gesture's moves and release are its control's alone, kept from the widget + # under the pointer: only a hold the control answered. + takes_pointer: ClassVar[bool] = False def moved(self, control: GestureControl, position: Offset) -> Gesture: return self @@ -43,6 +53,10 @@ def moved(self, control: GestureControl, position: Offset) -> Gesture: def released(self, control: GestureControl, position: Offset) -> Gesture: return NO_GESTURE + def held(self, control: GestureControl) -> Gesture: + """The press has been held still: only a press not yet a drag becomes a hold.""" + return self + class NoGesture(Gesture): holds_pointer = False @@ -63,6 +77,21 @@ def released(self, control: GestureControl, position: Offset) -> Gesture: control.clicked() return NO_GESTURE + def held(self, control: GestureControl) -> Gesture: + return HELD if control.held() else UNANSWERED_HOLD + + +class HeldGesture(Gesture): + """A hold its control answered: the rest of the press is the answer's, so its moves and + release reach nothing else, and letting go is not a click.""" + + takes_pointer = True + + +class UnansweredHold(Gesture): + """A hold its control had no answer for: the press goes on as the widget under it takes + it, and letting go is not a click.""" + class DraggingGesture(Gesture): def moved(self, control: GestureControl, position: Offset) -> Gesture: @@ -76,3 +105,4 @@ def released(self, control: GestureControl, position: Offset) -> Gesture: NO_GESTURE, DRAGGING = NoGesture(), DraggingGesture() +HELD, UNANSWERED_HOLD = HeldGesture(), UnansweredHold() diff --git a/src/toad/qt/client_start.py b/src/toad/qt/client_start.py index e4cfdff1c..6fd57bb1b 100644 --- a/src/toad/qt/client_start.py +++ b/src/toad/qt/client_start.py @@ -21,6 +21,7 @@ from toad.client.connection import CoreConnection from toad.launch_binding import AgentBinding from toad.application_lifetime import ApplicationStart +from toad.qt.finger_press import FingerPress from toad.qt.finger_scrolling import FingerScrollGesture, FingerScrolling from toad.qt.frame_probe import FrameProbe from toad.qt.window import QtToadApp @@ -51,6 +52,7 @@ async def open_app(connection: CoreConnection, project: Checkout, scheme: Colour agents (`AgentBinding.launched`), as Toad's terminal launch attaches it.""" set_base_config_type(QtClientSettings) FingerScrolling.install(QApplication.instance(), FingerScrollGesture.of_platform()) + FingerPress.install(QApplication.instance()) FrameProbe.start_if_requested(QApplication.instance()) launch = await AgentBinding.launched(agent, connection.agent_processes) app = QtToadApp(connection, project, PreparationRuntime(_renderer_for_platform(connection)), scheme, diff --git a/src/toad/qt/finger_press.py b/src/toad/qt/finger_press.py new file mode 100644 index 000000000..6ba6eeae4 --- /dev/null +++ b/src/toad/qt/finger_press.py @@ -0,0 +1,208 @@ +"""What a press is: a tap, a held finger, or the start of a drag, decided once for the app. + +A press reaches Qt as the window's mouse event (Android synthesizes it from the finger), then +widget by widget down to the one under it, each of which might guess on its own whether it +was a tap or a hold. Toad had two such guesses (the sidebar tree's and the history's +TapAndHold gestures, the sidebar's with a filter that ate the release after it), and widgets +that offer a menu on right-click had no hold at all. Here the application classifies each +press once, at its window, through the shared `toad.pointer_gesture` states with the +platform's drag distance and press-and-hold interval: + +- a finger held still for the press-and-hold interval is a right-click: the widget under it + gets the `QContextMenuEvent` a right button would send, so every context menu (a + `customContextMenuRequested` connection or a `contextMenuEvent` override) answers a held + finger with no code of its own. A hold its widgets offer no menu for stays a press; +- a press that moves past the drag distance first is a drag (finger scrolling, a grip, a + reordered tab), and nothing else happens to it; +- a press released before either is a tap. A tap's consumers (`tapped`) hear it before the + widget does and may `claim` it, which ends the press without the widget's own click. + +A mouse's press is classified as a tap or a drag the same way. Holding a mouse button is not +a right-click, because a mouse has one. +""" + +from __future__ import annotations + +from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt, QTimer, Signal +from PySide6.QtGui import QContextMenuEvent, QInputDevice, QInputMethodQueryEvent, QMouseEvent, QWindow +from PySide6.QtWidgets import QApplication, QWidget +from textual.geometry import Offset + +from toad.pointer_gesture import DRAGGING, NO_GESTURE, Gesture, GestureControl, PressedGesture + +# Where a withheld release lands, in the coordinates of the widget it reaches (`_withheld`). +_FAR_OFF = QPointF(-1e5, -1e5) + + + +class Press: + """One press, from the window's first event to its release.""" + + __slots__ = ("target", "origin", "finger", "claimed") + + def __init__(self, target: QWidget | None, origin: QPointF, finger: bool) -> None: + self.target = target + """The deepest widget under the press when it began.""" + self.origin = origin + """Where it began, in global coordinates.""" + self.finger = finger + """A finger on a touch screen rather than a mouse.""" + self.claimed = False + + def within(self, widget: QWidget) -> bool: + """The press began on ``widget`` or on one of its children.""" + return self.target is not None and (widget is self.target or widget.isAncestorOf(self.target)) + + def at(self, widget: QWidget) -> QPoint: + """Where the press began, in ``widget``'s coordinates.""" + return widget.mapFromGlobal(self.origin.toPoint()) + + def claim(self) -> None: + """A tap's consumer took it: the press ends without the widget's own click.""" + self.claimed = True + + +class FingerPress(QObject, GestureControl): + """The application's one classifier of presses (see the module): a `GestureControl` fed + every press its windows receive.""" + + tapped = Signal(object) + """A `Press` released before it moved past the drag distance or was held. Delivered + before the release reaches the widget, so a consumer may `claim` it.""" + long_pressed = Signal(object) + """A finger's `Press` held still, which the widget under it answered with a menu.""" + drag_started = Signal(object) + """A `Press` that moved past the drag distance.""" + + def __init__(self, application: QApplication) -> None: + QObject.__init__(self, application) + hints = application.styleHints() + self.drag_threshold = hints.startDragDistance() + self.hold = QTimer(self, singleShot=True, interval=hints.mousePressAndHoldInterval()) + self.hold.timeout.connect(self._held_still) + self.gesture: Gesture = NO_GESTURE + self.press: Press | None = None + self.window: QWindow | None = None + # A release the window lets through, to be taken from the widget it reaches + # (`_withheld`): the press was held, or its tap claimed. + self.withholding = False + + @classmethod + def install(cls, application: QApplication) -> FingerPress: + """The application's classifier; installing again (a consumer asking for it) returns + the one already held.""" + held = application.findChild(cls) + if held is not None: + return held + classifier = cls(application) + application.installEventFilter(classifier) + return classifier + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: + # A press is seen once, at its window, before Qt routes it down to a widget (and + # before QScroller holds it back); a widget's copy of the same press is not counted. + if not isinstance(event, QMouseEvent): + return False + if not isinstance(watched, QWindow): + # The window has taken the event; only the widget is kept from it: a held press's + # moves are the menu's, and its release (or a claimed tap's) is no click. + if event.type() == QEvent.Type.MouseMove: + return self.press is not None and self.gesture.takes_pointer + return self.withholding and event.type() == QEvent.Type.MouseButtonRelease and self._withheld(watched, event) + kind = event.type() + if kind == QEvent.Type.MouseButtonPress and event.button() == Qt.MouseButton.LeftButton: + if self.press is None: + self._began(watched, event) + return False + if self.press is None or watched is not self.window: + return False + if kind == QEvent.Type.MouseMove: + pressed = self.gesture + self.gesture = pressed.moved(self, _offset(event)) + if self.gesture is DRAGGING and pressed is not DRAGGING: + self.hold.stop() + self.drag_started.emit(self.press) + return False + if kind == QEvent.Type.MouseButtonRelease and event.button() == Qt.MouseButton.LeftButton: + gesture, press = self.gesture, self.press + self.gesture = gesture.released(self, _offset(event)) + self._ended() + self.window = None + # The window keeps the release, so Qt's own record of the pointer stays true; only + # the widget it reaches doesn't take it as a click. + self.withholding = gesture.takes_pointer or press.claimed + return False + + def clicked(self) -> None: + self.tapped.emit(self.press) + + def drag_to(self, position: Offset) -> None: + """A drag's moves are the widget's own (a scroll, a grip, a reorder).""" + + def held(self) -> bool: + """The widget under a finger held still gets a right-click's context-menu request; + the hold is answered when one of its widgets offers a menu (accepts the event).""" + press = self.press + if press.target is None or _platform_edits_text(press): + # The focused text field's own long-press is the platform's (selection handles, + # the system's copy and paste); a held finger there is not a right-click. + return False + menu = QContextMenuEvent(QContextMenuEvent.Reason.Mouse, press.at(press.target), press.origin.toPoint()) + QApplication.sendEvent(press.target, menu) + if menu.isAccepted(): + self.long_pressed.emit(press) + return True + return False + + def _began(self, window: QWindow, event: QMouseEvent) -> None: + origin = event.globalPosition() + finger = event.device().type() == QInputDevice.DeviceType.TouchScreen + self.press = Press(_widget_at(window, event.scenePosition()), origin, finger) + self.window, self.gesture = window, PressedGesture(_offset(event)) + if finger: + self.hold.start() + + def _held_still(self) -> None: + if self.press is not None: + self.gesture = self.gesture.held(self) + + def _ended(self) -> None: + self.hold.stop() + self.press = None + + def _withheld(self, widget: QObject, event: QMouseEvent) -> bool: + """The release of a held or claimed press, reaching the widget its press went to: Qt + has no cancelled mouse press, so the widget gets the release far off itself, which no + Qt control counts as a click, and its own press ends. Far off, because a widget that + ignores it passes it to its parent at the same place in the parent's coordinates (a + point just off a row's overlay would be on the row). (Replacing the window's release + instead leaves Qt routing the next right-click to the window itself.)""" + self.withholding = False + off = _FAR_OFF + QApplication.sendEvent(widget, QMouseEvent( + QEvent.Type.MouseButtonRelease, off, widget.mapToGlobal(off), Qt.MouseButton.LeftButton, + Qt.MouseButton.NoButton, event.modifiers(), event.device())) + return True + + +def _offset(event: QMouseEvent) -> Offset: + position = event.globalPosition() + return Offset(round(position.x()), round(position.y())) + + +def _widget_at(window: QWindow, point: QPointF) -> QWidget | None: + for widget in QApplication.topLevelWidgets(): + if widget.windowHandle() is window: + return widget.childAt(point.toPoint()) or widget + return None + + +def _platform_edits_text(press: Press) -> bool: + """The press is on the focused widget, and that widget takes text input: Qt-for-Android + gives a hold there to the platform's text selection, as it does for exactly this widget.""" + focus = QApplication.focusWidget() + if focus is None or not press.within(focus): + return False + query = QInputMethodQueryEvent(Qt.InputMethodQuery.ImEnabled) + QApplication.sendEvent(focus, query) + return bool(query.value(Qt.InputMethodQuery.ImEnabled)) diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index f38195444..f33b0d287 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -31,6 +31,7 @@ from PySide6.QtWidgets import QApplication, QPushButton, QScroller, QStyleOptionViewItem, QWidget from pyqt_reactive.widgets.virtual_rows import HtmlRow, PlainRow, RowDocumentDelegate, RowFormatting, VirtualRowView from toad.client.pending import AwaitsFirstPage +from toad.qt.finger_press import FingerPress, Press from toad.client.fragments import EvidencedFragment, FragmentDetails, HistoryFragment, MembershipText, Shown, WireMessage from toad.core.projection import MroProjection from toad.link_opening import OpensLineLinks @@ -885,12 +886,13 @@ def __init__(self, renderer: QtLineRenderer, scope, parent: QWidget | None = Non # Rows that arrived at the end the reader follows, not yet glided to (`glide_to_end`). self._arrived: tuple = () self.viewport().installEventFilter(self) - # Block menu: right-click (desktop) and long-press (Android) on a message row - # emit `block_menu_requested` with the row's fragment. ConversationView mounts - # the handler and runs the resulting commands. + # 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) - self.viewport().grabGesture(Qt.GestureType.TapAndHoldGesture) + # 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) # 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 @@ -995,26 +997,17 @@ 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.Gesture: - held = event.gesture(Qt.GestureType.TapAndHoldGesture) - if held is not None and held.state() == Qt.GestureState.GestureFinished: - self._emit_block_menu_at(self.viewport().mapFromGlobal(held.position().toPoint())) - return True - elif event.type() == QEvent.Type.MouseButtonPress: - self._pressed_at = event.position().toPoint() - elif event.type() == QEvent.Type.MouseButtonRelease and self._tapped(event.position().toPoint()): - href = self.anchor_at(event.position().toPoint()) - if href: - self.open_link(href) - return True return super().eventFilter(obj, event) - _pressed_at: QPoint | None = None - - def _tapped(self, point: QPoint) -> bool: - """A release where the press was, not the end of a drag the scroller moved.""" - pressed, self._pressed_at = self._pressed_at, None - return pressed is not None and (point - pressed).manhattanLength() <= QApplication.startDragDistance() + 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.""" + viewport = self.viewport() + if not press.within(viewport): + return + href = self.anchor_at(press.at(viewport)) + if href: + press.claim() + self.open_link(href) def anchor_at(self, point: QPoint) -> str: """The href of the link drawn at `point` (viewport coordinates), or "" over plain text.""" diff --git a/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index d1adbade2..3ed397702 100644 --- a/src/toad/qt/thread_comms_panel.py +++ b/src/toad/qt/thread_comms_panel.py @@ -46,6 +46,10 @@ from toad.client.sort_control import ThreadSortForm from toad.thread_identity import SessionIdentity from toad.qt.metrics import UiGap +from toad.client.relationship_row_menu import entry_target, menu_entries_for_row + +# The relationship an entry row shows; a group's own line keeps its group in UserRole. +_ENTRY = Qt.ItemDataRole.UserRole.value + 1 class QtRelationshipSort(RelationshipOrder, QtSortButton[ThreadSort]): @@ -105,6 +109,11 @@ def __init__(self, search: SidebarFilter, parent: QWidget | None = None) -> None self._tree.setRootIsDecorated(True) self._tree.itemExpanded.connect(self._item_expanded) self._tree.itemCollapsed.connect(self._item_collapsed) + # A row opens on a tap and offers Open / Copy on a right-click or a held finger, + # as Textual's `RelationshipRow` does (`request_navigation`, `show_row_menu`). + self._tree.itemClicked.connect(self._item_clicked) + self._tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self._tree.customContextMenuRequested.connect(self._offer_row_menu) column.addWidget(self._tree, 1) @property @@ -194,7 +203,53 @@ def _add_entry_item(self, parent_item: QTreeWidgetItem, entry: RelationshipEntry row = QTreeWidgetItem(parent_item, [display]) if entry.detail: row.setToolTip(0, entry.detail) - row.setData(0, Qt.ItemDataRole.UserRole, entry) + row.setData(0, _ENTRY, entry) + + def _row_entry(self, item: QTreeWidgetItem | None) -> tuple[object, RelationshipEntry] | None: + """The group and relationship an entry row shows; a group or "none" line shows none.""" + if item is None or item.data(0, _ENTRY) is None: + return None + return item.parent().data(0, Qt.ItemDataRole.UserRole), item.data(0, _ENTRY) + + def _item_clicked(self, item: QTreeWidgetItem) -> None: + shown = self._row_entry(item) + if shown is not None and shown[1].available: + asyncio.ensure_future(self._open_current(*shown)) + + def _offer_row_menu(self, point) -> None: + """Open / Copy for the row under ``point`` (viewport coordinates), from the shared + `menu_entries_for_row`, in the window's menu panel.""" + shown = self._row_entry(self._tree.itemAt(point)) + app = self._app() + if shown is None or app is None: + return + group, entry = shown + app.offer_entries(menu_entries_for_row( + target_name=entry.target, + copy=app.copy_to_clipboard, + open_callback=(lambda: asyncio.ensure_future(self._open_current(group, entry))) if entry.available else None, + )) + + async def _open_current(self, group, entry: RelationshipEntry) -> None: + """Open the relationship as it stands now: the list read again, and a relationship + that changed since it was drawn is not opened (Textual's `_navigate_current`).""" + app = self._app() + identity = self.thread_identity + if app is None or identity.root_path is None: + return + if identity.root_path != app.coordination_access.observation.observed().root: + app.show_warning("This view uses a different wire; open its matching connection to navigate.", "Comms") + return + service = await self.observed_source(app.coordination_access, app.preparation, identity.root_path) + if service is None: + return + snapshot = await app.preparation.run_thread(service.relationships, identity.thread_name()) + current = snapshot.current_entry(group, entry) + if current is None: + app.show_warning("This relationship changed; refresh the list before opening it.", "Comms") + self.present() + return + app.open_target(entry_target(current)) def _item_expanded(self, item: QTreeWidgetItem) -> None: group_type = item.data(0, Qt.ItemDataRole.UserRole) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 04c557555..7f622760c 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -523,41 +523,19 @@ def clear_address(self) -> None: self.clear() -class SwallowsRelease(QObject): - """Eats the one release that ends a held finger, then goes: the finger was holding the - row for its actions, so letting go must not also tap it and open that bus.""" - - def eventFilter(self, watched: QObject, event: QEvent) -> bool: - if event.type() == QEvent.Type.MouseButtonRelease: - watched.removeEventFilter(self) - self.deleteLater() - return True - return False - - class HeldRowMenu(QObject): - """A tree line's held actions (SidebarItem.held_actions), offered where a finger is held - on it or a mouse right-clicks it (a phone has no right button), in the window's own - panel, as its menu is (QtToadApp.offer).""" - - def __init__(self, listing: Welcome) -> None: - super().__init__(listing) - self.listing = listing - rows = listing.rows + """A tree line's menu (SidebarItem.menu_entries), offered where a mouse right-clicks it + or a finger is held on it (`FingerPress` delivers a held finger as the same context-menu + request), in the window's own panel, as its menu is (QtToadApp.offer). Every tree of + conversation rows has one: the welcome's and the sidebar's, as every Textual sidebar row + answers a right-click (`CommsRow.context_activation`). ``listing`` is what a row's + entries act through (its ``host`` window; the welcome's own rows reach the welcome).""" + + def __init__(self, rows: ConversationRows, listing) -> None: + super().__init__(rows) + self.rows, self.listing = rows, listing rows.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) rows.customContextMenuRequested.connect(self.offer) - rows.viewport().grabGesture(Qt.GestureType.TapAndHoldGesture) - rows.viewport().installEventFilter(self) - - def eventFilter(self, watched: QObject, event: QEvent) -> bool: - if event.type() == QEvent.Type.Gesture: - held = event.gesture(Qt.GestureType.TapAndHoldGesture) - if held is not None and held.state() == Qt.GestureState.GestureFinished: - viewport = self.listing.rows.viewport() - viewport.installEventFilter(SwallowsRelease(viewport)) - self.offer(viewport.mapFromGlobal(held.position().toPoint())) - return True - return False def offer(self, point: QPoint) -> None: """``point`` is in the tree's viewport, where QAbstractScrollArea reports it. @@ -565,7 +543,7 @@ def offer(self, point: QPoint) -> None: (base rows adapt their `held_actions` via `MenuEntry.from_offered`, rich rows like `ConversationRow` return the shared `menu_entries_for_row` output directly).""" - rows = self.listing.rows + rows = self.rows item: SidebarItem | None = rows.itemAt(point) if item is None: return @@ -641,7 +619,7 @@ def __init__(self, window: QtToadApp) -> None: window.renderer.themed(self.project, lambda: self.project.setStyleSheet(window.renderer.color_style(MutedRole))) self.new_session_button = QtStartSessionButton(window, parent=self) self.rows = ConversationRows(window) - self.held_menu = HeldRowMenu(self) + self.held_menu = HeldRowMenu(self.rows, self) self.address = BusAddress(window) # Gesture hint line below the rows, mirroring Textual's WelcomeNote(HINTS) # at the tail of `WelcomeScreen.compose`. The content is owned per-frontend @@ -1031,6 +1009,13 @@ def __init__(self, window: QtToadApp) -> None: # tree. Textual's `SideBar` also owns one (same class, same match rule). self.filter: SidebarFilter = SidebarFilter() self.filter.subscribe(self._on_filter_changed) + # A row's menu on a right-click or a held finger, as the welcome's rows have it. + self.held_menu = HeldRowMenu(self, self) + + @property + def host(self) -> QtToadApp: + """The window a row's menu entries act in (`HeldRowMenu`).""" + return self.window def _on_filter_changed(self, _value: str) -> None: """Re-present the whole tree so rows whose names newly stop (or newly start) diff --git a/src/toad/widgets/thread_comms.py b/src/toad/widgets/thread_comms.py index 183096cbb..2a3bd3a66 100644 --- a/src/toad/widgets/thread_comms.py +++ b/src/toad/widgets/thread_comms.py @@ -24,7 +24,7 @@ from toad.category_filter import CategoryFilterView from toad.client.connection import Observing -from toad.client.relationship_row_menu import menu_entries_for_row +from toad.client.relationship_row_menu import entry_target, menu_entries_for_row from toad.core import events as core_events from toad.native_style import ( AutoHeight, @@ -37,7 +37,7 @@ OneRow, TransparentBackground, ) -from toad.navigation_target import NavigationTarget, SelectTarget, ThreadTarget +from toad.navigation_target import NavigationTarget, SelectTarget from toad.session_scope import SessionScope from toad.sidebar_changes import SidebarChange from toad.sidebar_contracts import RelationshipMemberRows @@ -66,13 +66,6 @@ from toad.worker_group import WorkerGroup -def entry_target(entry: RelationshipEntry) -> NavigationTarget: - person = entry.person - if person is None: - return NavigationTarget.named(entry.target) - return ThreadTarget(person.thread.name) - - class RelationshipRowPresentation(WorkerGroup): """Presents the selected relationship row; a newer selection supersedes one running.""" diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 01dc9814f..8023bd24e 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -25,7 +25,7 @@ from typing import ClassVar import qasync -from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt +from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt, QTimer from PySide6.QtGui import QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent, QTextDocument from PySide6.QtTest import QTest from PySide6.QtWidgets import QAbstractButton, QAbstractScrollArea, QDialog, QLabel, QScroller, QStyleOptionViewItem, QApplication, QPushButton, QWidget @@ -50,6 +50,7 @@ from toad.qt.client_start import open_app from toad.qt.glyph_fonts import install_glyph_fonts from toad.qt.theme import current_scheme, offered_schemes +from toad.qt.finger_press import FingerPress from toad.qt.finger_scrolling import FingerScrollGesture, FingerScrolling, TouchAsMouse from toad.goal_interactions.controls import CollapseInteraction, HistoryInteraction from pyqt_reactive.widgets.fitted_text import WrappedText @@ -86,6 +87,7 @@ from toad.qt.menu import QtMenuRow from toad.qt.activity import ChannelActivity from toad import paths +from toad.qt.thread_comms_panel import QtThreadCommsPanel from toad.qt.window import ConversationRow, ConversationView, MenuActionRun, QtToadApp from toad.conversation_turn import LocalTurnBinding from toad.core.events import TextAgentFail, UnsupportedResumeAgentFail @@ -3013,6 +3015,174 @@ async def run(self) -> None: print(f"{path.value}: read={shown(field.value)!r} " f"draws={reading() if reading else '-'!r}", flush=True) app.grab().save(str(self.out / "settingsread-end.png")) +class HoldScenario(Scenario): + summary = ("at a Pixel 8a's size, with real touch through the window and the phone's touch-as-mouse " + "gesture: hold a finger on a sidebar channel, on a history row and on a tab; each that " + "offers a menu on right-click opens the same menu, and letting go doesn't also tap it. A " + "hold then a drag scrolls with no menu, and a tap still opens a row") + + @classmethod + def finger_gesture(cls) -> FingerScrollGesture: + return TouchAsMouse() + + def __init__(self, app: QtToadApp, out: Path) -> None: + super().__init__(app, out) + self.finger = QTest.createTouchDevice() + self.faults: list[str] = [] + + async def touch(self, widget: QWidget, point: QPoint, held_ms: int, moves: tuple[int, ...] = ()) -> None: + """A finger down at `point` (in `widget`), held for `held_ms`, moved up by each of + `moves` pixels a frame apart, then lifted, through the window as Android delivers it.""" + window = widget.window() + handle, at = window.windowHandle(), widget.mapTo(window, point) + await self.dispatched(lambda: QTest.touchEvent(handle, self.finger).press(0, at).commit()) + await asyncio.sleep(held_ms / 1000) + for step in moves: + at = at - QPoint(0, step) + await self.dispatched(lambda: QTest.touchEvent(handle, self.finger).move(0, at).commit()) + await asyncio.sleep(0.016) + await self.dispatched(lambda: QTest.touchEvent(handle, self.finger).release(0, at).commit()) + await asyncio.sleep(0.6) + + @staticmethod + async def dispatched(deliver) -> None: + """Deliver input through the window from Qt's own dispatch, as the platform does: the + window processes Qt's events at once, which from inside this scenario's asyncio task + would enter the loop's other tasks within it.""" + done = asyncio.get_running_loop().create_future() + + def run() -> None: + deliver() + done.set_result(None) + + QTimer.singleShot(0, run) + await done + + def menu(self) -> list[str]: + """The menu the window shows, row by row, or nothing when it is closed.""" + panel = self.app.menu_panel + return [row.label.text() for row in panel.findChildren(QtMenuRow)] if panel.isVisible() else [] + + def close_menu(self) -> None: + self.app.menu_panel.hide() + + async def right_click(self, widget: QWidget, point: QPoint) -> list[str]: + """A mouse's right button at `point`, through the window, where Qt turns it into the + context-menu request (a widget-level click skips that).""" + window = widget.window() + handle, at = window.windowHandle(), widget.mapTo(window, point) + await self.dispatched(lambda: QTest.mouseClick(handle, Qt.MouseButton.RightButton, + Qt.KeyboardModifier.NoModifier, at)) + await asyncio.sleep(0.4) + clicked = self.menu() + self.close_menu() + return clicked + + def expect(self, step: str, fact: bool, said: str) -> None: + if not fact: + self.faults.append(f"{step}: {said}") + + async def held_menu(self, step: str, widget: QWidget, point: QPoint) -> None: + """A hold opens the menu a right-click opens there, and its release taps nothing.""" + page = self.page + # The right-click first: what a mouse offers there before any finger has touched. When + # a menu panel moves the layout under a held finger, Qt routes the next mouse + # right-click to the widget that was under that point (Qt's own state, with or without + # FingerPress), which a phone, having no mouse, never meets. + clicked = await self.right_click(widget, point) + # The menu panel sits in the window's layout: the rows return to where they were + # only once it is gone. + await asyncio.sleep(0.4) + await self.touch(widget, point, 1100) + held = self.menu() + self.report(step, menu=held) + self.close_menu() + await asyncio.sleep(0.4) + self.expect(step, bool(held), "a held finger opened no menu") + self.expect(step, held == clicked, f"the hold's menu {held} is not the right-click's {clicked}") + self.expect(step, self.page is page, f"letting go opened {type(self.page).__name__}") + + async def run(self) -> None: + app = self.app + app.resize(412, 915) + await self.open_named("#comms") + tree = app.sidebar + await self.expand("#comms") + # 1. A sidebar row that isn't open: the hold offers its menu, and letting go doesn't open it. + other = await self.found(lambda row: isinstance(row, ConversationRow) and row.target.name != "#comms" + and not tree.visualItemRect(row).isEmpty(), "another listed row") + held_on: list[str] = [] + FingerPress.install(QApplication.instance()).long_pressed.connect( + lambda press: held_on.append(type(press.target).__name__)) + clicked: list[str] = [] + tree.itemClicked.connect(lambda item: clicked.append(item.key)) + # A channel's line has its order control drawn over it: the hold lands on that overlay. + await self.held_menu("1-sidebar-row", tree.viewport(), tree.visualItemRect(other).center()) + # 1b. A thread's line, which has no control drawn over it. + thread = await self.found(lambda row: isinstance(row, ConversationRow) and row.parent() is not None + and not tree.visualItemRect(row).isEmpty(), "a listed thread line") + await self.held_menu("1b-thread-line", tree.viewport(), tree.visualItemRect(thread).center()) + print(f"1-sidebar: held on {held_on}; rows a release clicked {clicked}", flush=True) + self.expect("1-sidebar", not clicked, f"letting go of a hold clicked {clicked}") + # 2. A message row in the history: its block menu. + # A point a third down the rows: a long row's centre can lie off the page, the sticky + # header covers the top and the floating "back to bottom" bar the bottom, and a hold on + # either is that control's own press. + history = self.page.messages + viewport = history.viewport() + on_row = QPoint(viewport.width() // 4, viewport.height() // 3) + self.expect("2-history-row", history.indexAt(on_row).isValid(), "no message row under the held point") + requested: list[str] = [] + history.block_menu_requested.connect(lambda fragment: requested.append(type(fragment).__name__)) + await self.held_menu("2-history-row", viewport, on_row) + print(f"2-history-row: block menu asked for {requested}", flush=True) + # 3. A tab offers no menu on right-click: a hold there stays the tab's press. + tabs = app.tabs + await self.touch(tabs, tabs.tabRect(0).center(), 1100) + self.report("3-tab", menu=self.menu()) + self.expect("3-tab", not self.menu(), f"a tab offered a menu {self.menu()} a right-click doesn't") + self.close_menu() + # 4. A hold that then drags scrolls the history, and opens no menu. + bar = history.verticalScrollBar() + bar.setValue(bar.maximum()) + await asyncio.sleep(0.4) + before = bar.value() + viewport = history.viewport() + await self.touch(viewport, QPoint(viewport.width() // 2, int(viewport.height() * 0.3)), 300, + moves=(-24,) * 14) + await asyncio.sleep(1.0) + self.report("4-hold-then-drag", scrolled=(before, bar.value()), menu=self.menu()) + self.expect("4-hold-then-drag", bar.value() != before, "the drag after a short hold didn't scroll") + self.expect("4-hold-then-drag", not self.menu(), f"the drag opened a menu {self.menu()}") + self.close_menu() + # 5. A tap still opens a row. + page = self.page + await self.touch(tree.viewport(), tree.visualItemRect(other).center(), 60) + await until(lambda: self.page is not page and not isinstance(self.page, QtOpeningSessionView), "tapped row") + self.report("5-tap-opens") + # 6. A thread's Comms rows (the thread pane) offer Open / Copy, as Textual's do. + await self.open_named("scratch-live-pipeline") + # A phone's pane gives the Comms tree under its category toggles little room: a + # taller window shows its rows. + app.resize(412, 1600) + app.thread_side.toggle_pane() + await asyncio.sleep(1.0) + picker = app.thread_pane.menu.picker + picker.setCurrentIndex([picker.itemText(index) for index in range(picker.count())].index("Comms")) + panel: QtThreadCommsPanel = app.thread_pane._comms_panel + comms = panel._tree + + def entry_rows(): + return [item for item in comms.findItems("", Qt.MatchFlag.MatchContains | Qt.MatchFlag.MatchRecursive) + if panel._row_entry(item) is not None + and comms.viewport().rect().contains(comms.visualItemRect(item).center())] + + await until(lambda: comms.isVisible() and entry_rows(), "a Comms relationship row") + await self.held_menu("6-comms-row", comms.viewport(), comms.visualItemRect(entry_rows()[0]).center()) + if self.faults: + raise AssertionError("\n".join(self.faults)) + + class FingerScenario(Scenario): summary = ("at a Pixel 8a's width with the phone's touch-as-mouse gesture: drag every visible " "scroll area by finger on the welcome, sidebar, #comms, the multi-line composer, the " diff --git a/tools/qt_inherit_ratchet.py b/tools/qt_inherit_ratchet.py index d7613970e..c702b3a2a 100644 --- a/tools/qt_inherit_ratchet.py +++ b/tools/qt_inherit_ratchet.py @@ -123,8 +123,8 @@ 'toad.qt.host.ScreenWideWindow': "a Qt top-level window clamped to the Android screen's available width (screen less system bars)", 'toad.qt.metrics.UiGap': 'Qt pixel spacing tokens; Textual spaces in cells through its CSS', 'toad.qt.action_shortcuts.ActionKeys': "Qt has no binding map: it installs a QShortcut per action and sets its keys again when ui.key_mode or ui.keymap changes; Textual's App binds the same catalog keys through its BindingsMap and set_keymap", - 'toad.qt.window.HeldRowMenu': "Qt TapAndHold gesture and context-menu event filter on the tree's viewport; the entries come from each row's shared menu_entries", - 'toad.qt.window.SwallowsRelease': 'a Qt event filter that eats the one mouse release ending a held finger, so the hold does not also tap the row', + 'toad.qt.window.HeldRowMenu': "connects the Qt tree's customContextMenuRequested (a right-click, or a held finger FingerPress delivers as one) to the panel; the entries come from each row's shared menu_entries", + 'toad.qt.finger_press.Press': "one Qt press: the QWidget under it, its global QPointF and whether a touch screen made it, and a tap consumer's claim", } KNOWN_BARE = frozenset({