feat(status_pill): open status bar pill cards on click instead of hover

This commit is contained in:
wyzula_j authored and Jan Wyzula committed 2026-11-24 10:52:16 +01:00
1 parent 2a0fbb3a56
commit ed679df799
8 files changed
+603 -128

No files matched your search

+192 -28
View File
@@ -1,7 +1,7 @@
"""
A frameless card window that opens next to a widget, with any content widget, and the controller
that opens it on hover. Used by the status bar pills, the client info in the status bar and as a
rich tooltip.
that opens it on hover or on a click. Used by the status bar pills (click), the client info in the
status bar (hover) and as a rich tooltip.
"""
from __future__ import annotations
@@ -11,8 +11,8 @@ from enum import StrEnum
from typing import Callable
import shiboken6
from qtpy.QtCore import QEvent, QObject, QPoint, QRect, Qt, QTimer
from qtpy.QtGui import QColor, QCursor, QGuiApplication
from qtpy.QtCore import QEvent, QObject, QPoint, QRect, QSize, Qt, QTimer
from qtpy.QtGui import QColor, QCursor, QGuiApplication, QWindow
from qtpy.QtWidgets import (
QApplication,
QFrame,
@@ -36,6 +36,13 @@ class CardAlign(StrEnum):
CENTER = "center" # centred on the anchor, e.g. a wide label
class CardTrigger(StrEnum):
"""What opens and closes a card of a HoverCardController."""
HOVER = "hover" # opens on hover, closes when the cursor has left
CLICK = "click" # a click on the anchor opens and closes it; a click elsewhere closes it
class HoverCard(QWidget):
"""
The frameless card that opens next to a widget, with any content widget. It never takes
@@ -157,23 +164,32 @@ class HoverCard(QWidget):
class HoverCardController(QObject):
"""
Opens a HoverCard above an anchor widget on hover and keeps it open while the cursor is over
the anchor, the card, the gap between them or one of the extra widgets, while the anchor has
keyboard focus, or while a popup or dialog of the card is open. The card closes GRACE_MS after
the cursor has left, on Esc, and when the application is deactivated. It is kept on the
screen of the anchor and follows it when either moves or changes size.
Opens a HoverCard above an anchor widget, on hover or on a click (trigger). It is kept on the
screen of the anchor and follows it when either moves or changes size. It closes on Esc and
when the application is deactivated.
Only a cursor poll decides inside or outside: Enter and Leave events are not reliable while
the card window is shown (e.g. on macOS).
Hover: the card stays open while the cursor is over the anchor, the card, the gap between them
or one of the extra widgets, while the anchor has keyboard focus, or while a popup or dialog of
the card is open, and closes GRACE_MS after the cursor has left. Only a cursor poll decides
inside or outside: Enter and Leave events are not reliable while the card window is shown
(e.g. on macOS).
Click: a left click on the anchor, or Space / Enter while it has keyboard focus, opens and
closes the card. A click anywhere else in the anchor's window closes it, except on one of the
extra widgets or while a popup or dialog of the card is open; so does resizing that window
or switching to another one. When the window is moved, the card moves with the pill. The
cursor leaving does not close it.
Args:
anchor(QWidget): The widget the card opens above; its Enter opens the card.
anchor(QWidget): The widget the card opens above; its Enter or a click on it opens the
card.
card(HoverCard): The card window.
keep_open(Callable[[], bool] | None): Asked on each poll; True keeps the card open.
can_open(Callable[[], bool] | None): Asked before opening; False keeps the card closed.
on_close(Callable[[], None] | None): Called when the card closes.
align(CardAlign): LEFT aligns the card to the anchor's left edge, CENTER centres it on
the anchor (for a wide anchor such as the client info label).
trigger(CardTrigger): HOVER opens the card on hover, CLICK on a click on the anchor.
"""
GRACE_MS = 250 # how long the cursor may be outside before the card closes
@@ -189,11 +205,16 @@ class HoverCardController(QObject):
can_open: Callable[[], bool] | None = None,
on_close: Callable[[], None] | None = None,
align: CardAlign | str = CardAlign.LEFT,
trigger: CardTrigger | str = CardTrigger.HOVER,
):
super().__init__(anchor)
self.anchor = anchor
self.card = card
self.align = CardAlign(align)
self.trigger = CardTrigger(trigger)
self._click_window: QWindow | None = None # watched for clicks outside while open
self._click_window_size = QSize()
self._focus_widget: QWidget | None = None # watched for Esc while the card is open
self._keep_open = keep_open
self._can_open = can_open
self._on_close = on_close
@@ -225,17 +246,33 @@ class HoverCardController(QObject):
self._outside_since = None
self.poll.start()
@property
def click_trigger(self) -> bool:
"""Whether a click opens and closes the card (instead of hover)."""
return self.trigger == CardTrigger.CLICK
def open(self) -> None:
"""Show the card above the anchor."""
if self._can_open is not None and not self._can_open():
return
self.start_watching()
if self.click_trigger:
self._watch_clicks()
else:
self.start_watching()
if self.card.isVisible():
return
self.card.refresh_style() # the theme may have changed while it was closed
self.card.adjustSize()
self.place()
self.card.show()
self._set_anchor_state("set_expanded", True)
def toggle(self) -> None:
"""Open the card, or close it when it is open."""
if self.card.isVisible():
self.close()
else:
self.open()
def close(self) -> None:
"""Hide the card and stop watching the cursor."""
@@ -247,10 +284,77 @@ class HoverCardController(QObject):
"""Hide the card without the on_close hook (the cursor left)."""
self.poll.stop()
self._outside_since = None
self._unwatch_clicks()
self.card.hide()
set_hovered = getattr(self.anchor, "set_hovered", None)
if callable(set_hovered):
set_hovered(False)
self._set_anchor_state("set_expanded", False)
# a click closes the card with the cursor still on the anchor: keep its hover outline
# (real bounds: from just outside no Leave would come to clear it)
hovered = self.click_trigger and self._over(self.anchor, tolerance=0)
self._set_anchor_state("set_hovered", hovered)
def _set_anchor_state(self, setter: str, value: bool) -> None:
method = getattr(self.anchor, setter, None)
if callable(method) and shiboken6.isValid(self.anchor):
method(value)
def _watch_clicks(self) -> None:
"""Watch the anchor's window for a click outside the anchor and the extras, and moves."""
window = self.anchor.window().windowHandle()
if window is self._click_window:
return
self._unwatch_clicks()
if window is not None:
window.installEventFilter(self)
self._click_window = window
self._click_window_size = window.size()
app = QApplication.instance()
app.focusChanged.connect(self._follow_focus)
self._follow_focus(None, app.focusWidget())
def _window_resized(self) -> bool:
"""Whether the watched window changed size since the card opened; Qt also sends Resize
events without a change, e.g. when the window is exposed."""
window = self._click_window
return window is not None and window.size() != self._click_window_size
def _unwatch_clicks(self) -> None:
window, self._click_window = self._click_window, None
if window is not None:
try:
QApplication.instance().focusChanged.disconnect(self._follow_focus)
except (TypeError, RuntimeError):
pass
if shiboken6.isValid(window):
window.removeEventFilter(self)
self._follow_focus(None, None)
@SafeSlot(object, object)
def _follow_focus(self, _old: QWidget | None, new: QWidget | None) -> None:
"""
Watch the focused widget of the anchor's window: Qt offers Esc to its shortcuts (e.g. the
one of the Log Panel) before the window sees the key press.
"""
widget, self._focus_widget = self._focus_widget, None
if widget is not None and shiboken6.isValid(widget):
widget.removeEventFilter(self)
if new is None or new in (self.anchor, self.card, *self._extras):
return # filtered anyway, and their filter must stay
if self._click_window is not None and new.window().windowHandle() is self._click_window:
new.installEventFilter(self)
self._focus_widget = new
def _over(self, widget: QWidget, tolerance: int | None = None) -> bool:
"""Whether the cursor is over a shown widget (with HOVER_TOLERANCE by default)."""
rect = self._global_rect(widget, tolerance)
return widget.isVisible() and rect.contains(QCursor.pos())
def _click_outside(self, event) -> bool:
"""Whether a mouse press in the anchor's window is outside the anchor and the extras."""
pos = event.globalPosition().toPoint()
inside = [self.anchor, *self._extras]
if any(w.isVisible() and self._global_rect(w, tolerance=0).contains(pos) for w in inside):
return False
return not self.own_window_open()
def place(self) -> None:
"""
@@ -271,9 +375,10 @@ class HoverCardController(QObject):
y = max(area.top(), min(y, area.bottom() - self.card.height() + 1))
self.card.move(x, y)
def _global_rect(self, widget: QWidget) -> QRect:
def _global_rect(self, widget: QWidget, tolerance: int | None = None) -> QRect:
"""The widget's rect on screen, grown by tolerance (default HOVER_TOLERANCE)."""
rect = QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
tol = self.HOVER_TOLERANCE
tol = self.HOVER_TOLERANCE if tolerance is None else tolerance
return rect.adjusted(-tol, -tol, tol, tol)
def hovered(self) -> bool:
@@ -331,22 +436,76 @@ class HoverCardController(QObject):
if state != Qt.ApplicationState.ApplicationActive:
self.close()
def _click_event(self, obj, event) -> bool | None:
"""
Handle an event of the click trigger; True consumes it, False passes it on and None
leaves it to the shared handling in eventFilter.
"""
kind = event.type()
if (
kind == QEvent.Type.ShortcutOverride
and event.key() == Qt.Key.Key_Escape
and self.card.isVisible()
and obj is QApplication.focusWidget()
):
event.accept() # no Esc shortcut while the card is open: the key press closes it
return True
if obj is self._click_window:
if kind == QEvent.Type.MouseButtonPress and self._click_outside(event):
self.close()
elif kind == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
self.close() # the card never has focus: Esc anywhere in the window closes it
return True
elif kind == QEvent.Type.Resize and self._window_resized():
self.close() # the window was resized, maximized or restored: the card goes away
elif kind == QEvent.Type.Move and self.card.isVisible():
self.place() # the window was dragged: the card goes with the pill
return False
if obj is self.anchor:
if kind == QEvent.Type.Enter:
if self.anchor.isVisible():
self._set_anchor_state("set_hovered", True)
return False
if kind == QEvent.Type.Leave:
self._set_anchor_state("set_hovered", False)
return False
if kind == QEvent.Type.FocusIn:
return False # tabbing to the pill only outlines it
if kind == QEvent.Type.MouseButtonPress and event.button() == Qt.MouseButton.LeftButton:
self.toggle()
return False
if kind == QEvent.Type.KeyPress and event.key() in (
Qt.Key.Key_Space,
Qt.Key.Key_Return,
Qt.Key.Key_Enter,
):
if not event.isAutoRepeat(): # a held key toggles once
self.toggle()
return True
if kind == QEvent.Type.Enter:
return False # neither the card nor an extra opens it
return None
def eventFilter(self, obj, event): # pylint: disable=invalid-name
kind = event.type()
if kind == QEvent.Type.WindowDeactivate and obj in (self.anchor, self.card):
# e.g. another window of the app took the focus; Qt sends it to every widget of the
# window, and the new active window is only known once the event is through
QTimer.singleShot(0, self, self._check_activation)
if self.click_trigger:
handled = self._click_event(obj, event)
if handled is not None:
return handled or super().eventFilter(obj, event)
# Qt can deliver a late Enter to a widget that was hidden or closed in the meantime
if kind == QEvent.Type.Enter and obj is self.anchor and self.anchor.isVisible():
set_hovered = getattr(self.anchor, "set_hovered", None)
if callable(set_hovered):
set_hovered(True)
self._set_anchor_state("set_hovered", True)
self.open()
elif kind == QEvent.Type.Enter and obj is self.card:
self.open()
elif kind == QEvent.Type.Enter and obj in self._extras:
self.start_watching()
elif kind == QEvent.Type.Leave and obj is self.anchor and not self.card.isVisible():
set_hovered = getattr(self.anchor, "set_hovered", None)
if callable(set_hovered):
set_hovered(False)
self._set_anchor_state("set_hovered", False)
elif (
kind == QEvent.Type.FocusIn
and obj is self.anchor
@@ -363,14 +522,19 @@ class HoverCardController(QObject):
self.place()
return super().eventFilter(obj, event)
def anchor_window_deactivated(self) -> None:
"""Close unless the card itself or one of its popups or dialogs took the activation."""
if not self.card.isActiveWindow() and not self.own_window_open():
self.close()
@SafeSlot()
def _check_activation(self) -> None:
"""Close once another window is active than the anchor's, the card or its own windows."""
if not self.card.isVisible() or not shiboken6.isValid(self.anchor):
return
if self.anchor.isActiveWindow() or self.card.isActiveWindow() or self.own_window_open():
return
self.close()
def cleanup(self) -> None:
"""Stop the poll, close the card and stop listening to the anchor, card and extras."""
self.poll.stop()
self._unwatch_clicks()
for widget in (self.anchor, self.card, *self._extras):
if shiboken6.isValid(widget):
widget.removeEventFilter(self)
@@ -1,6 +1,6 @@
"""
The scan pill for the main window status bar: a small live progress bar, a Stop button, the number
of waiting scans, and the full ScanProgressBar in a card that opens on hover.
of waiting scans, and the full ScanProgressBar in a card that opens on a click.
"""
from __future__ import annotations
@@ -146,7 +146,7 @@ def _read_queue_status(connector, result: _QueueStatusRead) -> None:
class ScanProgressCard(HoverCard):
"""The hover card of the scan pill, with the full ScanProgressBar."""
"""The card of the scan pill, with the full ScanProgressBar."""
def __init__(self, owner: "ScanStatusItem"):
super().__init__(owner, width=400, object_name="scan_status_card")
@@ -163,7 +163,7 @@ class ScanProgressCard(HoverCard):
class ScanStatusItem(StatusPillItem):
"""
Status-bar scan pill, Stop button and waiting count, with the full ScanProgressBar on hover.
Status-bar scan pill, Stop button and waiting count, with the full ScanProgressBar on a click.
One ScanHookTracker (the card's ScanProgressBar) drives both the pill and the card. The pill
width (compact, normal, wide, fill) and the large size are chosen in its right-click menu
@@ -1,7 +1,7 @@
"""
The BEC server pill for the main window status bar: an icon for the overall state of the core
services with the label "BEC", the number of core services that are down, and the full
BECStatusBox in a card that opens on hover.
BECStatusBox in a card that opens on a click.
"""
from __future__ import annotations
@@ -63,7 +63,7 @@ def server_indicator(model: ServiceStatusModel) -> ToolIndicator:
class ServerStatusCard(HoverCard):
"""The hover card of the server pill, with the full BECStatusBox."""
"""The card of the server pill, with the full BECStatusBox."""
def __init__(self, owner: "ServerStatusItem"):
super().__init__(owner, width=380, object_name="server_status_card")
@@ -76,7 +76,7 @@ class ServerStatusCard(HoverCard):
class ServerStatusItem(StatusPillItem):
"""
Status-bar pill with the overall state of the BEC server, with the full BECStatusBox on hover.
Status-bar pill with the overall state of the BEC server; a click opens the full BECStatusBox.
The status box in the card is the only source of the state: its model drives both the pill
and the card. The pill is the compact icon style (the state icon and "BEC"); the large size is
@@ -1,6 +1,6 @@
"""
Status-bar pills for the main window: a small state bar that opens a card with its full widget on
hover. A pill item shows a ToolIndicator (severity, summary, badge, progress); subclasses feed the
a click. A pill item shows a ToolIndicator (severity, summary, badge, progress); subclasses feed the
indicator and give the card its content, e.g. the scan pill with the full ScanProgressBar.
The card and its hover handling live in bec_widgets.utils.hover_card.
@@ -32,7 +32,12 @@ from qtpy.QtWidgets import QGraphicsOpacityEffect, QHBoxLayout, QMenu, QSizePoli
from bec_widgets.utils.bec_widget import BECWidget
from bec_widgets.utils.error_popups import SafeSlot
from bec_widgets.utils.hover_card import KEYBOARD_FOCUS_REASONS, HoverCard, HoverCardController
from bec_widgets.utils.hover_card import (
KEYBOARD_FOCUS_REASONS,
CardTrigger,
HoverCard,
HoverCardController,
)
from bec_widgets.utils.theme_utils import DPR_EVENTS, crisp_pixmap, theme_colors
from bec_widgets.widgets.progress.stage_bar import BarMode, Chip, StageBar, Tone
@@ -219,7 +224,10 @@ class Reveal(QObject):
class StatusBarPill(StageBar):
"""The StageBar in the status bar: a hover outline, a hand cursor and a settings menu."""
"""
The StageBar in the status bar: a hand cursor, a settings menu and an outline while hovered,
tabbed to or while its card is open. No tooltip while the card is open.
"""
menu_requested = Signal(QPoint)
double_clicked = Signal()
@@ -232,12 +240,40 @@ class StatusBarPill(StageBar):
self.setAttribute(Qt.WidgetAttribute.WA_Hover)
self._hovered = False
self._keyboard_focus = False
self._expanded = False
self._hint = ""
@property
def hovered(self) -> bool:
"""Whether the hover outline is shown."""
"""Whether the cursor is over the pill (the outline is shown)."""
return self._hovered
@property
def expanded(self) -> bool:
"""Whether the pill's card is open."""
return self._expanded
@property
def outlined(self) -> bool:
"""Whether the outline is drawn: hovered, tabbed to or with its card open."""
return self._hovered or self._keyboard_focus or self._expanded
def set_hint(self, hint: str) -> None:
"""Lines the owner adds to the tooltip, e.g. the state and how to open the card."""
if hint != self._hint:
self._hint = hint
self._sync_tooltip()
def tooltip_text(self) -> str:
"""The cut label (if it is cut) and the owner's hint; kept when the pill resizes."""
return "\n".join(line for line in (super().tooltip_text(), self._hint) if line)
def set_expanded(self, expanded: bool) -> None:
"""Mark the pill's card as open or closed; the controller calls it."""
if expanded != self._expanded:
self._expanded = expanded
self.update()
@property
def keyboard_focus(self) -> bool:
"""
@@ -268,6 +304,9 @@ class StatusBarPill(StageBar):
self.set_hovered(True)
elif event.type() == QEvent.Type.HoverLeave:
self.set_hovered(False)
elif event.type() == QEvent.Type.ToolTip and self._expanded:
event.ignore() # the card shows it all; a tooltip would cover it
return True
return super().event(event)
def contextMenuEvent(self, event): # pylint: disable=invalid-name
@@ -282,7 +321,7 @@ class StatusBarPill(StageBar):
def paintEvent(self, event): # pylint: disable=invalid-name
super().paintEvent(event)
if not (self._hovered or self._keyboard_focus):
if not self.outlined:
return
rect = self._bar_rect()
painter = QPainter(self)
@@ -343,6 +382,10 @@ class StatusIconPill(StatusBarPill):
self._sync_spin()
self.update()
def tooltip_text(self) -> str:
"""The owner's hint; the label is never cut."""
return self._hint
def set_text(self, text: str) -> None:
"""Set the label; the pill resizes to fit it."""
if text != self._text:
@@ -399,7 +442,7 @@ class StatusIconPill(StatusBarPill):
radius = min(self.corner_radius or 5, rect.height() / 2)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
outline = self._hovered or self._keyboard_focus
outline = self.outlined
painter.setPen(QPen(colors["primary"] if outline else with_alpha(accent, 0.45), 1))
painter.setBrush(with_alpha(accent, 0.12))
painter.drawRoundedRect(rect, radius, radius)
@@ -434,8 +477,9 @@ class StatusIconPill(StatusBarPill):
class StatusPillItem(BECWidget, QWidget):
"""
A status-bar pill with a badge chip and optional widgets next to it, and a card with the full
widget on hover. Subclasses set the indicator (set_indicator) and the card content, and call
apply_sizes() once their own widgets exist.
widget that a click on the pill opens and closes (a click elsewhere closes it too). Subclasses
set the indicator (set_indicator) and the card content, and call apply_sizes() once their own
widgets exist.
The pill width (compact, normal, wide, fill) and the large size are chosen in its right-click
menu and saved per user under the settings prefix. An icon-style pill (PILL_STYLE) shows a
@@ -461,6 +505,7 @@ class StatusPillItem(BECWidget, QWidget):
# class name of the widget a double-click on the pill opens in the dock area; None: no docking
DOCK_WIDGET: str | None = None
DOCK_HINT = "Double-click to add it to the current dock area"
EXPAND_HINT = "Click to expand"
def __init__(
self,
@@ -507,10 +552,11 @@ class StatusPillItem(BECWidget, QWidget):
keep_open=self.keep_card_open,
can_open=self._prepare_card,
on_close=self.on_card_closed,
trigger=CardTrigger.CLICK,
)
def create_card(self) -> HoverCard:
"""The hover card; subclasses may return their own, e.g. with a fixed content widget."""
"""The card; subclasses may return their own, e.g. with a fixed content widget."""
return HoverCard(self, self._card_content, width=self._card_width)
################################################################################
@@ -519,7 +565,7 @@ class StatusPillItem(BECWidget, QWidget):
def add_trailing(self, widget: QWidget, reveal: bool = True) -> Reveal | None:
"""
Put a widget between the pill and the badge; it counts as part of the pill for the hover.
Put a widget between the pill and the badge; a click on it does not close the card.
Args:
widget(QWidget): The widget, e.g. a Stop button.
@@ -738,18 +784,18 @@ class StatusPillItem(BECWidget, QWidget):
can_dock = self.can_dock
if self.card.hint is not None:
self.card.hint.setVisible(can_dock)
self.pill.setAccessibleDescription(self.DOCK_HINT if can_dock else "")
self.pill.setAccessibleDescription("\n".join(self._hints()))
self._update_tooltip()
return True
def _hints(self) -> list[str]:
"""How to open the card, and how to dock its widget when a double-click can dock."""
return [self.EXPAND_HINT, self.DOCK_HINT] if self.can_dock else [self.EXPAND_HINT]
def _update_tooltip(self) -> None:
"""The indicator's tooltip, with the docking hint when a double-click can dock."""
"""The indicator's tooltip, with how to open the card and, if possible, to dock."""
lines = [self._indicator.tooltip] if self._indicator.tooltip else []
if self.can_dock:
lines.append(self.DOCK_HINT)
tooltip = "\n".join(lines)
if self.pill.toolTip() != tooltip:
self.pill.setToolTip(tooltip)
self.pill.set_hint("\n".join(lines + self._hints()))
@SafeSlot()
def _request_dock(self) -> None:
@@ -766,7 +812,7 @@ class StatusPillItem(BECWidget, QWidget):
self.hover.open()
def close_card(self) -> None:
"""Hide the card and clear the hover state."""
"""Hide the card."""
self.hover.close()
@property
@@ -784,13 +830,8 @@ class StatusPillItem(BECWidget, QWidget):
super().hideEvent(event)
self.close_card()
def changeEvent(self, event): # pylint: disable=invalid-name
super().changeEvent(event)
if event.type() == QEvent.Type.WindowDeactivate:
self.hover.anchor_window_deactivated()
def cleanup(self):
"""Stop the hover poll and the animations and close the card."""
"""Stop the card controller and the animations and close the card."""
self.hover.cleanup()
for widget_reveal in self._reveals:
widget_reveal.stop()
+7 -3
View File
@@ -293,12 +293,16 @@ class StageBar(QWidget):
return min(rect.width(), self.scale_width) if rect.width() < 1 else self.scale_width
return rect.width()
def _sync_tooltip(self) -> None:
"""Show the full label as a tooltip only while the painted label is cut."""
def tooltip_text(self) -> str:
"""The tooltip: the full label while the painted label is cut, else empty."""
rect = self._bar_rect()
metrics = QFontMetricsF(self.label_font(rect.height(), self._label_width(rect)))
cut = bool(self._text) and metrics.horizontalAdvance(self._text) > rect.width() - 12
tooltip = self._text if cut else ""
return self._text if cut else ""
def _sync_tooltip(self) -> None:
"""Apply tooltip_text, e.g. after the label or the size changed."""
tooltip = self.tooltip_text()
if tooltip != self.toolTip():
self.setToolTip(tooltip)
+42 -36
View File
@@ -176,10 +176,22 @@ def _cursor_at(monkeypatch, point):
monkeypatch.setattr(hover_card.QCursor, "pos", staticmethod(lambda: point))
def test_hover_card_and_outline_clear_without_a_leave_event(item, qtbot, monkeypatch):
from qtpy.QtCore import QEvent, QObject, QPoint
from qtpy.QtGui import QCursor, QEnterEvent
from qtpy.QtWidgets import QApplication
def _show_settled(item, qtbot):
"""
Show the item as a roomy window (room for the Stop to slide in, as in the status bar) and
wait until the window system has settled its size: a resized window closes the card.
"""
item.resize(900, 60)
item.show()
qtbot.waitExposed(item)
window = item.window().windowHandle()
qtbot.waitUntil(lambda: window.size() == item.size(), timeout=2000)
qtbot.wait(50)
def test_outline_clears_without_a_leave_event_once_the_card_closes(item, qtbot, monkeypatch):
from qtpy.QtCore import QEvent, QObject, QPoint, Qt
from qtpy.QtGui import QCursor
class SwallowLeave(QObject):
"""Like macOS with the card shown: the pill never gets its Leave event."""
@@ -187,24 +199,22 @@ def test_hover_card_and_outline_clear_without_a_leave_event(item, qtbot, monkeyp
def eventFilter(self, _obj, event): # pylint: disable=invalid-name
return event.type() in (QEvent.Type.Leave, QEvent.Type.HoverLeave)
item.show()
qtbot.waitExposed(item)
_show_settled(item, qtbot)
swallow = SwallowLeave()
item.pill.installEventFilter(swallow)
inside = item.pill.mapToGlobal(QPoint(5, 5))
_cursor_at(monkeypatch, inside)
local = QPoint(5, 5).toPointF()
QApplication.sendEvent(item.pill, QEnterEvent(local, local, inside.toPointF()))
assert item.pill.hovered and item.card.isVisible() and item._poll.isActive()
qtbot.wait(item.GRACE_MS + 150)
assert item.card.isVisible() # still over the pill
qtbot.mouseClick(item.pill, Qt.MouseButton.LeftButton)
assert item.card.isVisible() and item.pill.outlined
assert not item._poll.isActive() # no cursor poll for a click card
outside = inside + QPoint(2000, 2000)
QCursor.setPos(outside) # so Qt itself does not re-enter the pill when the card hides
QCursor.setPos(outside)
_cursor_at(monkeypatch, outside)
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
assert not item.pill.hovered
assert not item._poll.isActive()
qtbot.wait(item.GRACE_MS + 150)
assert item.card.isVisible() # leaving does not close it
item.close_card() # e.g. a click elsewhere
assert not item.pill.hovered and not item.pill.outlined
item.pill.removeEventFilter(swallow)
@@ -212,8 +222,7 @@ def test_card_stays_while_a_stop_waits_for_confirmation(item, qtbot, monkeypatch
from qtpy.QtCore import QPoint
item.tracker.on_scan_status(*status())
item.show()
qtbot.waitExposed(item)
_show_settled(item, qtbot)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
item.card.progress.confirm_before_stop = True
item.open_card()
@@ -332,7 +341,7 @@ def test_pill_stripes_stop_while_hidden_or_minimized(item, qtbot):
@pytest.mark.parametrize(
"reason, opens",
"reason, outlined",
[
("ActiveWindowFocusReason", False), # the window is activated or the app switched back
("OtherFocusReason", False),
@@ -341,7 +350,7 @@ def test_pill_stripes_stop_while_hidden_or_minimized(item, qtbot):
("BacktabFocusReason", True),
],
)
def test_card_opens_on_focus_only_when_tabbed_to(item, qtbot, monkeypatch, reason, opens):
def test_focus_never_opens_the_card_and_tab_outlines(item, qtbot, monkeypatch, reason, outlined):
from qtpy.QtCore import QEvent, QPoint, Qt
from qtpy.QtGui import QFocusEvent
from qtpy.QtWidgets import QApplication
@@ -352,14 +361,9 @@ def test_card_opens_on_focus_only_when_tabbed_to(item, qtbot, monkeypatch, reaso
QApplication.sendEvent(
item.pill, QFocusEvent(QEvent.Type.FocusIn, getattr(Qt.FocusReason, reason))
)
assert item.card.isVisible() is opens
assert item.pill.keyboard_focus is opens
if opens:
# kept open while tabbed to, wherever the cursor is: the poll never starts the grace
# period (checked directly; the offscreen platform lets the card window take activation)
item._check_cursor()
assert item._outside_since is None and item.card.isVisible()
item.close_card()
assert not item.card.isVisible()
assert item.pill.keyboard_focus is outlined
assert item.pill.outlined is outlined
def test_card_has_no_native_window_shadow(item):
@@ -375,26 +379,28 @@ def test_card_has_no_native_window_shadow(item):
def test_card_stays_while_its_stop_menu_is_open(item, qtbot, monkeypatch):
"""The emergency-stop path: the Stop's menu usually reaches past the card's right edge."""
from qtpy.QtCore import QPoint
from qtpy.QtGui import QCursor
from .test_status_pill import _press_in_window
item.tracker.on_scan_status(*status())
item.show()
qtbot.waitExposed(item)
_show_settled(item, qtbot)
item.open_card()
stop = item.card.progress.stop_button
card = item.card.card
stop.menu.popup(card.mapToGlobal(QPoint(card.width() - 30, card.height() - 40)))
qtbot.waitUntil(stop.menu.isVisible)
on_last_item = stop.menu.geometry().bottomRight() - QPoint(5, 5)
_cursor_at(monkeypatch, on_last_item) # outside the card, the pill and the gap
_cursor_at(monkeypatch, stop.menu.geometry().bottomRight() - QPoint(5, 5))
qtbot.wait(item.GRACE_MS + 300)
assert item.card.isVisible() and stop.menu.isVisible()
elsewhere = item.mapToGlobal(QPoint(item.width() - 2, item.height() // 2))
_press_in_window(item, elsewhere)
assert item.card.isVisible() # a popup of the card is open
stop.menu.close()
away = item.card.frameGeometry().bottomRight() + QPoint(2000, 2000)
QCursor.setPos(away) # so Qt itself does not re-enter the card when the menu closes
_cursor_at(monkeypatch, away)
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
qtbot.waitUntil(lambda: not stop.menu.isVisible())
assert item.card.isVisible() # closing the menu does not close the card
_press_in_window(item, elsewhere)
assert not item.card.isVisible()
def _stored_queue_status(waiting: int):
+3 -1
View File
@@ -57,7 +57,9 @@ def test_pill_follows_the_core_state(item, qtbot):
assert item.indicator.severity == ToolSeverity.OK
assert item.indicator.badge is None
assert (item.pill.icon_name, item.pill.text) == ("check_circle", "BEC")
assert item.pill.toolTip() == "All core services running\n5/5 core services up · 1 other"
assert item.pill.toolTip() == (
f"All core services running\n5/5 core services up · 1 other\n{item.EXPAND_HINT}"
)
assert item.pill.accessibleName() == "All core services running"
item.status_box.update_service_status(*_all_services(skip=["ScanBundler", "SciHub"]))
+288 -30
View File
@@ -90,7 +90,7 @@ def test_generic_item_shows_any_indicator_and_content(generic_item, qtbot):
item.set_indicator(down) # unchanged: no second signal
assert seen == [down]
assert (item.pill.mode, item.pill.text) == (BarMode.ERROR, "2 services down")
assert item.pill.toolTip() == "x"
assert item.pill.toolTip() == f"x\n{item.EXPAND_HINT}"
assert item.badge_chip.text() == "2 down" and item.badge_chip._tone == Tone.BAD
assert item.badge_reveal.shown
@@ -156,9 +156,126 @@ def test_card_stays_on_screen_and_follows_the_pill(generic_item, qtbot, monkeypa
item.close_card()
def _press_in_window(item, global_pos, button=Qt.MouseButton.LeftButton):
"""A mouse press as the platform delivers it: to the window, before any widget."""
from qtpy.QtCore import QEvent, QPointF
from qtpy.QtGui import QMouseEvent
from qtpy.QtWidgets import QApplication
window = item.window().windowHandle()
local = QPointF(window.mapFromGlobal(global_pos))
event = QMouseEvent(
QEvent.Type.MouseButtonPress,
local,
QPointF(global_pos),
button,
button,
Qt.KeyboardModifier.NoModifier,
)
QApplication.sendEvent(window, event)
def test_click_opens_and_closes_the_card_and_hover_only_outlines(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QPoint, QPointF
from qtpy.QtGui import QEnterEvent
from qtpy.QtWidgets import QApplication
item = generic_item
item.show()
qtbot.waitExposed(item)
inside = item.pill.mapToGlobal(QPoint(5, 5))
_cursor_at(monkeypatch, inside)
point = QPointF(5, 5)
QApplication.sendEvent(item.pill, QEnterEvent(point, point, QPointF(inside)))
qtbot.wait(item.GRACE_MS + 150)
assert item.pill.hovered and not item.card.isVisible() # hover alone opens nothing
assert not item._poll.isActive()
qtbot.mouseClick(item.pill, Qt.MouseButton.LeftButton)
assert item.card.isVisible() and item.pill.expanded and item.pill.outlined
_cursor_at(monkeypatch, QPoint(-5000, -5000))
qtbot.wait(item.GRACE_MS + 150)
assert item.card.isVisible() # the cursor leaving does not close it
_cursor_at(monkeypatch, inside)
qtbot.mouseClick(item.pill, Qt.MouseButton.LeftButton) # a second click closes it
assert not item.card.isVisible() and not item.pill.expanded
assert item.pill.hovered # the cursor is still on the pill
qtbot.mouseClick(item.pill, Qt.MouseButton.RightButton)
assert not item.card.isVisible() # the right button is for the settings menu
def test_click_elsewhere_or_esc_closes_the_card_but_not_on_a_trailing_widget(
generic_item, qtbot, monkeypatch
):
from qtpy.QtCore import QEvent, QPoint
from qtpy.QtGui import QKeyEvent
from qtpy.QtWidgets import QApplication, QPushButton
item = generic_item
stop = QPushButton("Stop", item)
item.add_trailing(stop, reveal=False)
other = QPushButton("Elsewhere", item)
item.row.addWidget(other)
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
_press_in_window(item, item.pill.mapToGlobal(QPoint(5, 5)))
assert item.card.isVisible() # the window passes the press on to the pill: it opens
_press_in_window(item, stop.mapToGlobal(stop.rect().center()))
assert item.card.isVisible() # the Stop next to the pill keeps it
_press_in_window(item, item.pill.mapToGlobal(QPoint(5, 5)))
assert not item.card.isVisible() # a second press on the pill closes it
item.open_card()
_press_in_window(item, other.mapToGlobal(other.rect().center()))
assert not item.card.isVisible() # anywhere else in the window closes it
item.open_card()
window = item.window().windowHandle()
esc = QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Escape, Qt.KeyboardModifier.NoModifier)
QApplication.sendEvent(window, esc)
assert not item.card.isVisible()
assert item.hover._click_window is None # stops watching the window once closed
_press_in_window(item, other.mapToGlobal(other.rect().center())) # nothing open: no effect
assert not item.card.isVisible()
def test_resizing_the_window_closes_the_card_and_moving_it_takes_it_along(
generic_item, qtbot, monkeypatch
):
from qtpy.QtCore import QPoint
from qtpy.QtGui import QResizeEvent
from qtpy.QtWidgets import QApplication
item = generic_item
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
window = item.window().windowHandle()
item.open_card()
size = window.size()
QApplication.sendEvent(window, QResizeEvent(size, size))
assert item.card.isVisible() # Qt sends Resize without a change, e.g. on expose
item.resize(item.width() + 40, item.height())
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
assert not item.pill.expanded
item.open_card()
before = item.card.pos()
item.move(item.pos() + QPoint(30, 0))
qtbot.waitUntil(lambda: item.card.pos() == before + QPoint(30, 0), timeout=2000)
assert item.card.isVisible() # dragged: the card goes with the pill
item.close_card()
def test_card_stays_open_while_a_dialog_of_its_content_is_open(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QPoint, Qt
from qtpy.QtGui import QCursor
from qtpy.QtWidgets import QDialog
item = generic_item
@@ -169,18 +286,123 @@ def test_card_stays_open_while_a_dialog_of_its_content_is_open(generic_item, qtb
dialog = QDialog(item.card.content)
dialog.setWindowModality(Qt.WindowModality.ApplicationModal)
dialog.show()
qtbot.waitUntil(dialog.isVisible)
qtbot.wait(item.GRACE_MS + 300)
dialog.activateWindow()
qtbot.waitUntil(dialog.isActiveWindow)
qtbot.wait(20)
assert item.card.isVisible() # the dialog took the focus, but it belongs to the card
elsewhere = item.mapToGlobal(QPoint(item.width() - 2, item.height() // 2))
_press_in_window(item, elsewhere)
assert item.card.isVisible() # e.g. a restart confirmation of the status box
away = item.card.frameGeometry().bottomRight() + QPoint(2000, 2000)
QCursor.setPos(away) # so Qt itself does not re-enter the card when the dialog closes
_cursor_at(monkeypatch, away)
dialog.close()
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
assert item.card.isVisible()
_press_in_window(item, elsewhere)
assert not item.card.isVisible()
dialog.deleteLater()
def test_another_window_taking_the_focus_closes_the_card(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QPoint
from qtpy.QtWidgets import QWidget
item = generic_item
item.show()
item.activateWindow()
qtbot.waitUntil(item.isActiveWindow)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
item.open_card()
qtbot.wait(20)
assert item.card.isVisible()
other = QWidget() # e.g. a floating dock or a second window of the app
qtbot.addWidget(other)
other.show()
other.activateWindow()
qtbot.waitUntil(other.isActiveWindow)
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
other.close()
def test_esc_closes_the_card_before_a_shortcut_of_the_focused_widget(generic_item, qtbot):
from qtpy.QtGui import QKeySequence, QShortcut
from qtpy.QtTest import QTest
from qtpy.QtWidgets import QLineEdit
item = generic_item
edit = QLineEdit(item)
item.row.addWidget(edit)
fired = []
shortcut = QShortcut(QKeySequence(Qt.Key.Key_Escape), edit)
shortcut.setContext(Qt.ShortcutContext.WidgetShortcut) # as in the Log Panel
shortcut.activated.connect(lambda: fired.append(True))
item.show()
qtbot.waitExposed(item)
window = item.window().windowHandle()
def focus_edit(): # offscreen hands the focus to a shown card, real platforms do not
item.activateWindow()
qtbot.waitUntil(item.isActiveWindow)
edit.setFocus()
qtbot.waitUntil(edit.hasFocus)
item.open_card()
focus_edit()
assert item.card.isVisible()
QTest.keyClick(window, Qt.Key.Key_Escape)
assert not item.card.isVisible()
assert not fired # the open card takes the Esc
focus_edit()
QTest.keyClick(window, Qt.Key.Key_Escape)
assert fired # with the card closed the shortcut works again
def test_a_click_just_outside_the_pill_closes_the_card(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QPoint
item = generic_item
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
pill = item.pill
just_outside = pill.mapToGlobal(QPoint(pill.width() + 1, pill.height() // 2))
assert item.rect().contains(item.mapFromGlobal(just_outside))
item.open_card()
_cursor_at(monkeypatch, just_outside)
_press_in_window(item, just_outside)
assert not item.card.isVisible() # hit testing uses the real bounds, not the hover margin
assert not item.pill.outlined # no Leave comes from out there, so no outline is left on
def test_space_or_enter_toggles_the_card_and_tab_only_outlines(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QEvent, QPoint
from qtpy.QtGui import QFocusEvent, QKeyEvent
from qtpy.QtWidgets import QApplication
item = generic_item
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
QApplication.sendEvent(
item.pill, QFocusEvent(QEvent.Type.FocusIn, Qt.FocusReason.TabFocusReason)
)
assert item.pill.keyboard_focus and item.pill.outlined
assert not item.card.isVisible()
qtbot.keyClick(item.pill, Qt.Key.Key_Space)
assert item.card.isVisible()
qtbot.keyClick(item.pill, Qt.Key.Key_Return)
assert not item.card.isVisible()
for key in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter):
qtbot.keyPress(item.pill, key)
for _ in range(3): # holding the key: auto-repeat presses do not toggle again
repeat = QKeyEvent(QEvent.Type.KeyPress, key, Qt.KeyboardModifier.NoModifier, "", True)
QApplication.sendEvent(item.pill, repeat)
assert item.card.isVisible()
qtbot.keyClick(item.pill, key)
assert not item.card.isVisible()
class DockablePill(StatusPillItem):
DOCK_WIDGET = "BECQueue"
@@ -205,12 +427,13 @@ def test_dock_hint_only_with_a_dock_widget_and_a_handler(generic_item, dockable_
assert hint is not None and hint.isHidden() # no handler yet
available = [False]
dockable_item.set_dock_handler(lambda: available[0])
assert hint.isHidden() and dockable_item.pill.accessibleDescription() == ""
expand = dockable_item.EXPAND_HINT
assert hint.isHidden() and dockable_item.pill.accessibleDescription() == expand
available[0] = True
dockable_item._prepare_card() # asked again each time the card opens
assert not hint.isHidden()
assert hint.text() == dockable_item.DOCK_HINT
assert dockable_item.pill.accessibleDescription() == dockable_item.DOCK_HINT
assert dockable_item.pill.accessibleDescription() == f"{expand}\n{dockable_item.DOCK_HINT}"
dockable_item.set_dock_handler(None)
assert hint.isHidden()
@@ -237,17 +460,55 @@ def test_double_click_does_nothing_without_a_dock_area(dockable_item, generic_it
qtbot.mouseDClick(dockable_item.pill, Qt.MouseButton.RightButton)
def test_tooltip_tells_how_to_dock(dockable_item, generic_item):
def test_tooltip_tells_how_to_expand_and_dock(dockable_item, generic_item):
expand, dock = dockable_item.EXPAND_HINT, dockable_item.DOCK_HINT
assert expand == "Click to expand" and "current dock area" in dock
dockable_item.set_indicator(ToolIndicator(summary="ok", tooltip="All good"))
assert dockable_item.pill.toolTip() == "All good" # no dock area yet
assert dockable_item.pill.toolTip() == f"All good\n{expand}" # no dock area yet
dockable_item.set_dock_handler(lambda: True)
assert dockable_item.pill.toolTip() == f"All good\n{dockable_item.DOCK_HINT}"
assert "current dock area" in dockable_item.DOCK_HINT
assert dockable_item.pill.toolTip() == f"All good\n{expand}\n{dock}"
dockable_item.set_indicator(ToolIndicator(summary="ok", tooltip="Still good"))
assert dockable_item.pill.toolTip() == f"Still good\n{dockable_item.DOCK_HINT}"
generic_item.set_dock_handler(lambda: True) # no DOCK_WIDGET: no hint
assert dockable_item.pill.toolTip() == f"Still good\n{expand}\n{dock}"
generic_item.set_dock_handler(lambda: True) # no DOCK_WIDGET: no dock hint
generic_item.set_indicator(ToolIndicator(summary="ok", tooltip="Plain"))
assert generic_item.pill.toolTip() == "Plain"
assert generic_item.pill.toolTip() == f"Plain\n{expand}"
generic_item.set_indicator(ToolIndicator(summary="ok"))
assert generic_item.pill.toolTip() == expand
def test_no_tooltip_over_an_open_card(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QEvent, QPoint
from qtpy.QtGui import QHelpEvent
item = generic_item
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
def tooltip_shown() -> bool:
event = QHelpEvent(QEvent.Type.ToolTip, QPoint(5, 5), item.pill.mapToGlobal(QPoint(5, 5)))
item.pill.event(event)
return event.isAccepted()
assert tooltip_shown()
item.open_card()
assert not tooltip_shown()
item.close_card()
assert tooltip_shown()
def test_tooltip_survives_a_resize_of_the_pill(generic_item, qtbot):
"""The bar's own cut-label tooltip used to replace the pill's tooltip on every resize."""
item = generic_item
item.set_indicator(ToolIndicator(summary="ok", tooltip="All good"))
item.show()
qtbot.waitExposed(item)
item.set_width_mode("wide")
assert item.pill.toolTip() == f"All good\n{item.EXPAND_HINT}"
long = "A very long label that does not fit into the compact pill at all"
item.set_indicator(ToolIndicator(summary=long, tooltip="All good"))
item.set_width_mode("compact")
assert item.pill.toolTip() == f"{long}\nAll good\n{item.EXPAND_HINT}"
def test_hover_cleanup_can_run_twice(generic_item, recwarn):
@@ -256,28 +517,25 @@ def test_hover_cleanup_can_run_twice(generic_item, recwarn):
assert not [w for w in recwarn if "Failed to disconnect" in str(w.message)]
def test_late_enter_opens_no_card_for_a_hidden_or_cleaned_up_pill(generic_item, qtbot):
def test_late_enter_does_not_outline_a_hidden_pill_and_cleanup_stops_clicks(generic_item, qtbot):
from qtpy.QtCore import QPointF
from qtpy.QtGui import QEnterEvent
from qtpy.QtWidgets import QApplication
item = generic_item
def enter():
point = QPointF(5, 5)
QApplication.sendEvent(item.pill, QEnterEvent(point, point, point))
enter() # Qt can still deliver a queued Enter after the window was hidden or closed
assert not item.card.isVisible()
point = QPointF(5, 5)
# Qt can still deliver a queued Enter after the window was hidden or closed
QApplication.sendEvent(item.pill, QEnterEvent(point, point, point))
assert not item.pill.hovered and not item.card.isVisible()
item.show()
qtbot.waitExposed(item)
enter()
assert item.card.isVisible()
item.close_card()
item.open_card()
window = item.hover._click_window
assert window is item.window().windowHandle()
item.hover.cleanup()
enter()
assert item.hover._click_window is None and not item.card.isVisible()
qtbot.mouseClick(item.pill, Qt.MouseButton.LeftButton)
assert not item.card.isVisible()