Skip to content
Merged
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
13 changes: 13 additions & 0 deletions src/toad/client/relationship_row_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
38 changes: 34 additions & 4 deletions src/toad/pointer_gesture.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -30,19 +32,31 @@ 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

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
Expand All @@ -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:
Expand All @@ -76,3 +105,4 @@ def released(self, control: GestureControl, position: Offset) -> Gesture:


NO_GESTURE, DRAGGING = NoGesture(), DraggingGesture()
HELD, UNANSWERED_HOLD = HeldGesture(), UnansweredHold()
2 changes: 2 additions & 0 deletions src/toad/qt/client_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
208 changes: 208 additions & 0 deletions src/toad/qt/finger_press.py
Original file line number Diff line number Diff line change
@@ -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))
37 changes: 15 additions & 22 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
Loading
Loading