feat(main_window): add generic status bar pills with an interactive hover card

This commit is contained in:
wyzula_j authored and Jan Wyzula committed 2026-11-09 13:55:29 +01:00
1 parent 9a01751246
commit 8615cd037c
7 files changed
+1849 -19

No files matched your search

+11 -2
View File
@@ -155,6 +155,15 @@ class BECMainApp(BECMainWindow):
# Add guided tour to Help menu
self._add_guided_tour_to_menu()
def status_dock_area(self):
"""The status pills open their widgets in the dock area view."""
view = getattr(self, "dock_area", None) # None while the main window builds its status bar
return view.dock_area if view is not None else None
def show_dock_area(self) -> None:
"""Switch to the dock area view."""
self.set_current("dock_area")
# --- Public API ------------------------------------------------------
def add_section(self, title: str, id: str, position: int | None = None):
return self.sidebar.add_section(title, id, position)
@@ -316,9 +325,9 @@ class BECMainApp(BECMainWindow):
tour_steps.append(dark_mode_step)
# Register the client info label
if hasattr(self, "_client_info_hover"):
if hasattr(self, "_client_info_label"):
client_info_step = self.guided_tour.register_widget(
widget=self._client_info_hover,
widget=self._client_info_label,
title="Client Status",
text="Displays status messages and information from the BEC Server.",
)
@@ -0,0 +1,934 @@
"""
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
indicator and give the card its content, e.g. the scan pill with the full ScanProgressBar.
The hover handling lives in HoverCardController, which works for any trigger widget, also a plain
label (the client info in the status bar).
"""
from __future__ import annotations
import time
from dataclasses import dataclass
from enum import StrEnum
from typing import Callable
from bec_lib.logger import bec_logger
from qtpy.QtCore import (
QEasingCurve,
QEvent,
QObject,
QParallelAnimationGroup,
QPoint,
QPropertyAnimation,
QRect,
QRectF,
QSettings,
Qt,
QTimer,
Signal,
)
from qtpy.QtGui import QAction, QActionGroup, QColor, QCursor, QGuiApplication, QPainter, QPen
from qtpy.QtWidgets import (
QApplication,
QFrame,
QGraphicsDropShadowEffect,
QGraphicsOpacityEffect,
QHBoxLayout,
QLabel,
QMenu,
QSizePolicy,
QVBoxLayout,
QWidget,
)
from bec_widgets.utils.bec_widget import BECWidget
from bec_widgets.utils.error_popups import SafeSlot
from bec_widgets.utils.theme_utils import css, theme_colors
from bec_widgets.widgets.progress.stage_bar import BarMode, Chip, StageBar, Tone
logger = bec_logger.logger
# (normal, large) pill widths in pixels; "fill" stretches with a minimum width
PILL_WIDTHS = {"compact": (150, 200), "normal": (280, 380), "wide": (480, 620)}
PILL_FILL_MIN = 220
PILL_MODES = ("compact", "normal", "wide", "fill")
# focus the user gave the pill on purpose, as opposed to Qt focusing it on window activation
KEYBOARD_FOCUS_REASONS = (Qt.FocusReason.TabFocusReason, Qt.FocusReason.BacktabFocusReason)
class CardAlign(StrEnum):
"""Where a hover card opens relative to its anchor."""
LEFT = "left" # left edges aligned
CENTER = "center" # centred on the anchor, e.g. a wide label
class ToolSeverity(StrEnum):
"""How a status-bar pill rates what it reports."""
OK = "ok"
INFO = "info"
WARNING = "warning"
CRITICAL = "critical"
@dataclass(frozen=True)
class ToolIndicator:
"""
What a status-bar pill shows.
Args:
severity(ToolSeverity): ok, info, warning or critical; sets the colour of the bar.
summary(str): The pill label.
badge(str | None): Short text in a chip next to the pill, e.g. "3 waiting"; None hides it.
progress(float | None): Filled share 0..1 of something that runs, or None.
attention(bool): Whether the badge asks for attention (shown in the danger colour).
tooltip(str): Tooltip of the pill.
active(bool): Something runs without a known progress; shows the moving stripes. Only
while it runs, so a long-lived state (a busy server) does not animate all the time.
"""
severity: ToolSeverity = ToolSeverity.INFO
summary: str = ""
badge: str | None = None
progress: float | None = None
attention: bool = False
tooltip: str = ""
active: bool = False
def stage_mode(indicator: ToolIndicator) -> tuple[BarMode, float]:
"""
The StageBar mode and filled share for an indicator.
Returns:
tuple[BarMode, float]: (mode, fraction).
"""
severity = ToolSeverity(indicator.severity)
if severity == ToolSeverity.CRITICAL:
return BarMode.ERROR, 1.0
if severity == ToolSeverity.WARNING:
return BarMode.PAUSED, indicator.progress or 0.0
if indicator.progress is not None:
return BarMode.PROGRESS, indicator.progress
if indicator.active:
return BarMode.BUSY, 0.0
if severity == ToolSeverity.OK:
return BarMode.DONE, 1.0
return BarMode.IDLE, 0.0
def _default_settings() -> QSettings:
# pylint: disable=import-outside-toplevel
from bec_widgets.widgets.containers.dock_area.profile_utils import _app_settings
return _app_settings()
class Reveal(QObject):
"""
Slides a widget in and out of a row: its maximum width animates between 0 and its natural
width while it fades, so the row never jumps. Showing is immediate; hiding waits until the
widget has not been wanted for HIDE_DELAY_MS, so a state that flips back and forth (e.g. at
the start of a scan) does not make it blink.
"""
DURATION_MS = 180
HIDE_DELAY_MS = 600
MAX_WIDTH = 16777215
def __init__(self, widget: QWidget, parent: QObject | None = None):
super().__init__(parent)
self.widget = widget
self._shown = False
self._effect = QGraphicsOpacityEffect(widget)
self._effect.setOpacity(0.0)
widget.setGraphicsEffect(self._effect)
self._width = QPropertyAnimation(widget, b"maximumWidth", self)
self._fade = QPropertyAnimation(self._effect, b"opacity", self)
self._group = QParallelAnimationGroup(self)
for anim in (self._width, self._fade):
anim.setDuration(self.DURATION_MS)
anim.setEasingCurve(QEasingCurve.Type.OutCubic)
self._group.addAnimation(anim)
self._group.finished.connect(self._on_finished)
self._hide_timer = QTimer(self)
self._hide_timer.setSingleShot(True)
self._hide_timer.setInterval(self.HIDE_DELAY_MS)
self._hide_timer.timeout.connect(self._animate_out)
widget.setMaximumWidth(0)
widget.setVisible(False)
@property
def shown(self) -> bool:
"""Whether the widget is (being) shown."""
return self._shown
@property
def active(self) -> bool:
"""Whether an animation or the hide delay is running."""
running = self._group.state() == QParallelAnimationGroup.State.Running
return running or self._hide_timer.isActive()
def set_shown(self, shown: bool) -> None:
"""Ask for the widget to be shown or hidden; cheap to call on every update."""
if shown:
self._hide_timer.stop()
if not self._shown:
self._animate_in()
elif self._shown and not self._hide_timer.isActive():
self._hide_timer.start()
def _animate(self, width: int, opacity: float) -> None:
self._group.stop()
self._width.setStartValue(min(self.widget.maximumWidth(), self.widget.sizeHint().width()))
self._width.setEndValue(width)
self._fade.setStartValue(self._effect.opacity())
self._fade.setEndValue(opacity)
self._group.start()
def _animate_in(self) -> None:
self._shown = True
self.widget.setVisible(True)
self.widget.setEnabled(True)
self._animate(self.widget.sizeHint().width(), 1.0)
def _animate_out(self) -> None:
self._shown = False
self.widget.setEnabled(False)
self._animate(0, 0.0)
def _on_finished(self) -> None:
if self._shown:
self.widget.setMaximumWidth(self.MAX_WIDTH)
else:
self.widget.setVisible(False)
def stop(self) -> None:
"""Stop the animations and the hide delay (before deletion)."""
self._hide_timer.stop()
self._group.stop()
class StatusBarPill(StageBar):
"""The StageBar in the status bar: a hover outline, a hand cursor and a settings menu."""
menu_requested = Signal(QPoint)
double_clicked = Signal()
def __init__(self, parent: QWidget | None = None):
super().__init__(parent, height=22)
self.corner_radius = 5
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
self.setAttribute(Qt.WidgetAttribute.WA_Hover)
self._hovered = False
self._keyboard_focus = False
@property
def hovered(self) -> bool:
"""Whether the hover outline is shown."""
return self._hovered
@property
def keyboard_focus(self) -> bool:
"""
Whether the user tabbed to the pill. Qt also gives it focus when the window is activated
(it is often the only Tab widget there), which must not open the card or draw the outline.
"""
return self._keyboard_focus
def focusInEvent(self, event): # pylint: disable=invalid-name
self._keyboard_focus = event.reason() in KEYBOARD_FOCUS_REASONS
super().focusInEvent(event)
self.update()
def focusOutEvent(self, event): # pylint: disable=invalid-name
self._keyboard_focus = False
super().focusOutEvent(event)
self.update()
def set_hovered(self, hovered: bool) -> None:
"""Show or clear the hover outline. The owner clears it when the cursor has left, since
a Leave event does not always arrive (e.g. on macOS while the card window is shown)."""
if hovered != self._hovered:
self._hovered = hovered
self.update()
def event(self, event): # pylint: disable=invalid-name
if event.type() == QEvent.Type.HoverEnter:
self.set_hovered(True)
elif event.type() == QEvent.Type.HoverLeave:
self.set_hovered(False)
return super().event(event)
def contextMenuEvent(self, event): # pylint: disable=invalid-name
self.menu_requested.emit(event.globalPos())
def mouseDoubleClickEvent(self, event): # pylint: disable=invalid-name
if event.button() == Qt.MouseButton.LeftButton:
event.accept()
self.double_clicked.emit()
return
super().mouseDoubleClickEvent(event)
def paintEvent(self, event): # pylint: disable=invalid-name
super().paintEvent(event)
if not (self._hovered or self._keyboard_focus):
return
rect = self._bar_rect()
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QPen(theme_colors()["primary"], 1))
painter.setBrush(Qt.BrushStyle.NoBrush)
radius = min(self.corner_radius or 5, rect.height() / 2)
painter.drawRoundedRect(QRectF(rect), radius, radius)
painter.end()
class HoverCard(QWidget):
"""
The frameless card that opens above a status-bar widget, with any content widget. It never
takes keyboard focus from the main window; a HoverCardController opens and closes it. A
non-activating Tool window rather than a ToolTip one, so its buttons take clicks on every
platform.
Args:
owner(QWidget): The widget the card belongs to (its parent).
content(QWidget | None): The widget shown in the card; can be set later with set_content.
width(int | None): Fixed width of the card frame; None follows the content.
object_name(str): Object name of the card frame, for its style sheet.
"""
def __init__(
self,
owner: QWidget,
content: QWidget | None = None,
width: int | None = None,
object_name: str = "status_hover_card",
):
super().__init__(
owner,
Qt.WindowType.Tool
| Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowDoesNotAcceptFocus
# the card draws its own rounded shadow; the native one (macOS) is computed for the
# whole translucent window and shows as a square-cornered band around the card
| Qt.WindowType.NoDropShadowWindowHint,
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
outer = self.outer_layout = QVBoxLayout(self)
outer.setContentsMargins(12, 12, 12, 12) # room for the shadow
self.card = QFrame(self)
self.card.setObjectName(object_name)
if width is not None:
self.card.setFixedWidth(width)
shadow = QGraphicsDropShadowEffect(self.card)
shadow.setBlurRadius(24)
shadow.setOffset(0, 4)
shadow.setColor(QColor(0, 0, 0, 70))
self.card.setGraphicsEffect(shadow)
self.inner_layout = QVBoxLayout(self.card)
self.inner_layout.setContentsMargins(14, 14, 14, 14)
outer.addWidget(self.card)
self.content: QWidget | None = None
self.hint: QLabel | None = None
if content is not None:
self.set_content(content)
self.refresh_style()
def set_content(self, content: QWidget) -> None:
"""Show a widget in the card, in place of the previous content."""
if self.content is not None:
self.inner_layout.removeWidget(self.content)
self.content = content
content.setParent(self.card)
self.inner_layout.insertWidget(0, content)
def add_hint(self, text: str) -> QLabel:
"""Add a small muted line below the content, e.g. how to dock the widget."""
if self.hint is None:
self.hint = QLabel(self.card)
self.hint.setObjectName("status_card_hint")
self.inner_layout.addWidget(self.hint)
self.refresh_style()
self.hint.setText(text)
return self.hint
def refresh_style(self) -> None:
"""Re-read the theme colours."""
colors = theme_colors()
self.card.setStyleSheet(
f"#{self.card.objectName()} {{ background: {css(colors['card'])};"
f" border: 1px solid {css(colors['border'])}; border-radius: 8px; }}"
f"#status_card_hint {{ color: {css(colors['muted'])}; font-size: 11px; }}"
)
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.
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).
Args:
anchor(QWidget): The widget the card opens above; its Enter 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).
"""
GRACE_MS = 250 # how long the cursor may be outside before the card closes
POLL_MS = 90 # cursor check while hovered or open
HOVER_TOLERANCE = 4 # px around anchor, extras and card that still count as inside
GAP = 8 # px between the anchor and the card
def __init__(
self,
anchor: QWidget,
card: HoverCard,
keep_open: Callable[[], bool] | None = None,
can_open: Callable[[], bool] | None = None,
on_close: Callable[[], None] | None = None,
align: CardAlign | str = CardAlign.LEFT,
):
super().__init__(anchor)
self.anchor = anchor
self.card = card
self.align = CardAlign(align)
self._keep_open = keep_open
self._can_open = can_open
self._on_close = on_close
self._extras: list[QWidget] = []
self._outside_since: float | None = None
self.poll = QTimer(self)
self.poll.setInterval(self.POLL_MS)
self.poll.timeout.connect(self.check_cursor)
for widget in (anchor, card):
widget.installEventFilter(self)
app = QGuiApplication.instance()
self._app_connected = app is not None
if app is not None:
app.applicationStateChanged.connect(self._on_application_state)
@property
def outside_since(self) -> float | None:
"""time.monotonic() when the cursor left, or None while it is inside."""
return self._outside_since
def add_extra(self, widget: QWidget) -> None:
"""Count a widget next to the anchor as inside, e.g. a Stop button; it does not open it."""
self._extras.append(widget)
widget.installEventFilter(self)
def start_watching(self) -> None:
"""Start the cursor poll; repeated (sometimes synthetic) Enter events do not restart it."""
if not self.poll.isActive():
self._outside_since = None
self.poll.start()
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.card.isVisible():
return
self.card.refresh_style() # the theme may have changed while it was closed
self.card.adjustSize()
self.place()
self.card.show()
def close(self) -> None:
"""Hide the card and stop watching the cursor."""
if self._on_close is not None:
self._on_close()
self.leave()
def leave(self) -> None:
"""Hide the card without the on_close hook (the cursor left)."""
self.poll.stop()
self._outside_since = None
self.card.hide()
set_hovered = getattr(self.anchor, "set_hovered", None)
if callable(set_hovered):
set_hovered(False)
def place(self) -> None:
"""
Put the card above the anchor, left-aligned to it (or centred), with its bottom at the
anchor, and keep it inside the available geometry of the anchor's screen.
"""
margin = self.card.outer_layout.contentsMargins()
top_left = self.anchor.mapToGlobal(QPoint(0, 0))
if self.align == CardAlign.CENTER:
x = top_left.x() + (self.anchor.width() - self.card.width()) // 2
else:
x = top_left.x() - margin.left()
y = top_left.y() - self.card.height() + margin.bottom() - self.GAP
screen = self.anchor.screen() or QGuiApplication.primaryScreen()
if screen is not None:
area = screen.availableGeometry()
x = max(area.left(), min(x, area.right() - self.card.width() + 1))
y = max(area.top(), min(y, area.bottom() - self.card.height() + 1))
self.card.move(x, y)
def _global_rect(self, widget: QWidget) -> QRect:
rect = QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
tol = self.HOVER_TOLERANCE
return rect.adjusted(-tol, -tol, tol, tol)
def hovered(self) -> bool:
"""Whether the cursor is over the anchor, an extra, the card, or the gap to the card."""
pos = QCursor.pos()
widgets = [self.anchor, *self._extras]
rects = [self._global_rect(w) for w in widgets if w.isVisible()]
if self.card.isVisible():
card = self._global_rect(self.card.card)
anchor = self._global_rect(self.anchor)
rects.append(card)
rects.append(
QRect(anchor.left(), card.bottom(), anchor.width(), anchor.top() - card.bottom())
)
return any(rect.contains(pos) for rect in rects)
def _owns(self, widget: QWidget | None) -> bool:
owner = widget.parentWidget() if widget is not None else None
if owner is None:
return False
roots = [self.card, self.anchor, *self._extras]
host = self.anchor.parentWidget()
if host is not None:
roots.append(host)
return any(owner is root or root.isAncestorOf(owner) for root in roots)
def own_window_open(self) -> bool:
"""
Whether a popup or a modal dialog of the card or the anchor is open, e.g. the arrow menu
of a Stop in the card or a confirmation dialog of its content.
"""
return self._owns(QApplication.activePopupWidget()) or self._owns(
QApplication.activeModalWidget()
)
def _anchor_has_keyboard_focus(self) -> bool:
return bool(getattr(self.anchor, "keyboard_focus", False))
@SafeSlot()
def check_cursor(self) -> None:
"""The poll: close the card GRACE_MS after the cursor has left."""
if self.hovered() or self._anchor_has_keyboard_focus() or self.own_window_open():
self._outside_since = None
return
if self._keep_open is not None and self._keep_open():
return
now = time.monotonic()
if self._outside_since is None:
self._outside_since = now
elif now - self._outside_since >= self.GRACE_MS / 1000:
self.leave()
@SafeSlot(object)
def _on_application_state(self, state) -> None:
if state != Qt.ApplicationState.ApplicationActive:
self.close()
def eventFilter(self, obj, event): # pylint: disable=invalid-name
kind = event.type()
if kind == QEvent.Type.Enter and obj is self.anchor:
set_hovered = getattr(self.anchor, "set_hovered", None)
if callable(set_hovered):
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)
elif (
kind == QEvent.Type.FocusIn
and obj is self.anchor
and event.reason() in KEYBOARD_FOCUS_REASONS
):
self.open()
elif kind == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
self.close()
return True
elif kind in (QEvent.Type.Move, QEvent.Type.Resize) and self.card.isVisible():
# the card grows with its content, and the anchor moves when a widget next to it
# slides in: keep the card bottom-anchored above the anchor
if obj is self.anchor or obj is self.card:
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()
def cleanup(self) -> None:
"""Stop the poll, close the card and disconnect from the application."""
self.poll.stop()
app = QGuiApplication.instance()
if app is not None and self._app_connected:
self._app_connected = False
try:
app.applicationStateChanged.disconnect(self._on_application_state)
except (TypeError, RuntimeError):
pass
self.card.hide()
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.
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.
Signals:
fill_changed(bool): The pill switched to or from filling the status bar.
indicator_changed(object): A new ToolIndicator is shown.
"""
RPC = False
PLUGIN = False
GRACE_MS = HoverCardController.GRACE_MS
fill_changed = Signal(bool)
indicator_changed = Signal(object)
dock_requested = Signal(str)
# 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"
def __init__(
self,
parent: QWidget | None = None,
client=None,
settings: Callable[[], QSettings] | None = None,
settings_prefix: str = "status_pill",
card_content: QWidget | None = None,
card_width: int | None = None,
**kwargs,
):
super().__init__(parent=parent, client=client, **kwargs)
self._settings_factory = settings or _default_settings
self._settings_prefix = settings_prefix
self._width_mode = "normal"
self._large = False
self._indicator = ToolIndicator()
self._load_settings()
self.row = QHBoxLayout(self)
self.row.setContentsMargins(6, 0, 6, 0)
self.row.setSpacing(6)
self.pill = StatusBarPill(self)
self.pill.menu_requested.connect(self._show_menu)
self.badge_chip = Chip("", Tone.NEUTRAL, self)
self.row.addWidget(self.pill, 1)
self.row.addWidget(self.badge_chip)
self.badge_reveal = Reveal(self.badge_chip, self)
self._reveals: list[Reveal] = [self.badge_reveal]
self._card_content = card_content
self._card_width = card_width
self.card = self.create_card()
self.card.hide()
self._dock_available: Callable[[], bool] | None = None
if self.DOCK_WIDGET:
self.card.add_hint(self.DOCK_HINT).setVisible(False)
self.pill.double_clicked.connect(self._request_dock)
self.hover = HoverCardController(
self.pill,
self.card,
keep_open=self.keep_card_open,
can_open=self._prepare_card,
on_close=self.on_card_closed,
)
def create_card(self) -> HoverCard:
"""The hover card; subclasses may return their own, e.g. with a fixed content widget."""
return HoverCard(self, self._card_content, width=self._card_width)
################################################################################
# Layout
################################################################################
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.
Args:
widget(QWidget): The widget, e.g. a Stop button.
reveal(bool): Slide it in and out with a Reveal instead of keeping it shown.
Returns:
Reveal | None: The Reveal that shows and hides it, if requested.
"""
self.row.insertWidget(self.row.indexOf(self.badge_chip), widget)
self.hover.add_extra(widget)
if not reveal:
return None
widget_reveal = Reveal(widget, self)
self._reveals.append(widget_reveal)
return widget_reveal
################################################################################
# Settings
################################################################################
def _settings_key(self, name: str) -> str:
return f"{self._settings_prefix}/{name}"
def _load_settings(self) -> None:
try:
settings = self._settings_factory()
mode = str(settings.value(self._settings_key("pill_width"), "normal"))
self._large = settings.value(self._settings_key("large"), False, type=bool)
except Exception: # pylint: disable=broad-except
logger.debug(f"Could not read the {self._settings_prefix} pill settings")
return
self._width_mode = mode if mode in PILL_MODES else "normal"
def _save_settings(self) -> None:
try:
settings = self._settings_factory()
settings.setValue(self._settings_key("pill_width"), self._width_mode)
settings.setValue(self._settings_key("large"), self._large)
settings.sync()
except Exception: # pylint: disable=broad-except
logger.debug(f"Could not save the {self._settings_prefix} pill settings")
@property
def width_mode(self) -> str:
"""compact, normal, wide or fill."""
return self._width_mode
def set_width_mode(self, mode: str) -> None:
"""Choose the pill width and save it."""
if mode not in PILL_MODES or mode == self._width_mode:
return
was_fill = self._width_mode == "fill"
self._width_mode = mode
self._save_settings()
self.apply_sizes()
if was_fill != (mode == "fill"):
self.fill_changed.emit(mode == "fill")
@property
def large(self) -> bool:
"""Whether the large status bar sizes are used."""
return self._large
def set_large(self, large: bool) -> None:
"""Switch between the normal and the large status bar sizes, and save it."""
if large == self._large:
return
self._large = large
self._save_settings()
self.apply_sizes()
def build_menu(self) -> QMenu:
"""The pill's right-click menu: width choice and the large size."""
menu = QMenu(self)
menu.addSection("Pill width")
group = QActionGroup(menu)
group.setExclusive(True)
for mode in PILL_MODES:
action = QAction(mode.capitalize(), menu)
action.setCheckable(True)
action.setChecked(mode == self._width_mode)
action.setData(mode)
action.triggered.connect(lambda _checked=False, m=mode: self.set_width_mode(m))
group.addAction(action)
menu.addAction(action)
menu.addSeparator()
large = QAction("Large status bar", menu)
large.setCheckable(True)
large.setChecked(self._large)
large.toggled.connect(self.set_large)
menu.addAction(large)
return menu
@SafeSlot(QPoint)
def _show_menu(self, pos: QPoint) -> None:
self.close_card()
menu = self.build_menu()
menu.exec(pos)
menu.deleteLater()
################################################################################
# Sizes and theme
################################################################################
@property
def bar_height(self) -> int:
"""Height of the pill and the widgets next to it."""
return 34 if self._large else 22
def apply_sizes(self) -> None:
"""Apply the pill width mode and the normal/large heights and fonts."""
height = self.bar_height
self.pill.set_bar_height(height)
self.pill.setFixedHeight(height)
self.pill.label_pixel_size = 15 if self._large else 12
if self._width_mode == "fill":
self.pill.setMinimumWidth(PILL_FILL_MIN)
self.pill.setMaximumWidth(16777215)
self.pill.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
else:
width = PILL_WIDTHS[self._width_mode][1 if self._large else 0]
self.pill.setFixedWidth(width)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.badge_chip.setFixedHeight(height)
self.pill.update()
self.render_indicator()
def apply_theme(self, theme: str):
"""Restyle after a theme change."""
self.card.refresh_style()
self.badge_chip.refresh_style()
self.pill.update()
################################################################################
# Indicator
################################################################################
@property
def indicator(self) -> ToolIndicator:
"""The indicator shown by the pill."""
return self._indicator
def set_indicator(self, indicator: ToolIndicator) -> None:
"""Show an indicator; cheap to call on every update."""
changed = indicator != self._indicator
self._indicator = indicator
self.render_indicator()
if changed:
self.indicator_changed.emit(indicator)
def pill_text(self) -> str:
"""The pill label; subclasses may vary it with the width mode."""
return self._indicator.summary
@SafeSlot()
def render_indicator(self) -> None:
"""Draw the current indicator on the pill and the badge."""
indicator = self._indicator
mode, fraction = stage_mode(indicator)
self.pill.set_state(mode, fraction, self.pill_text())
self._update_tooltip()
if indicator.badge:
self.badge_chip.setText(indicator.badge)
self.badge_chip.set_tone(Tone.BAD if indicator.attention else Tone.NEUTRAL)
self.badge_reveal.set_shown(bool(indicator.badge))
################################################################################
# Card
################################################################################
def keep_card_open(self) -> bool:
"""Whether the card stays open although the cursor has left; for subclasses."""
return False
def set_dock_handler(self, available: Callable[[], bool] | None) -> None:
"""
Let a double-click on the pill request its DOCK_WIDGET (dock_requested) while
``available()`` is True; the window that hosts the pill handles the request.
Args:
available(Callable[[], bool] | None): Whether a dock area can take the widget now;
None hides the button.
"""
self._dock_available = available
self._prepare_card()
@property
def can_dock(self) -> bool:
"""Whether a double-click on the pill opens its widget in a dock area now."""
available = self._dock_available
return bool(self.DOCK_WIDGET) and available is not None and available()
def _prepare_card(self) -> bool:
"""Show the docking hint before the card opens, if docking works; the card always opens."""
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._update_tooltip()
return True
def _update_tooltip(self) -> None:
"""The indicator's tooltip, with the docking hint when a double-click can 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)
@SafeSlot()
def _request_dock(self) -> None:
if not self.can_dock:
return
self.close_card()
self.dock_requested.emit(self.DOCK_WIDGET)
def on_card_closed(self) -> None:
"""Called when the card closes, e.g. to drop a pending confirmation; for subclasses."""
def open_card(self) -> None:
"""Show the card above the pill."""
self.hover.open()
def close_card(self) -> None:
"""Hide the card and clear the hover state."""
self.hover.close()
@property
def _poll(self) -> QTimer:
return self.hover.poll
@property
def _outside_since(self) -> float | None:
return self.hover.outside_since
def _check_cursor(self) -> None:
self.hover.check_cursor()
def hideEvent(self, event): # pylint: disable=invalid-name
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."""
self.hover.cleanup()
for widget_reveal in self._reveals:
widget_reveal.stop()
self.card.close()
super().cleanup()
@@ -13,6 +13,7 @@ from qtpy.QtWidgets import (
QLabel,
QMainWindow,
QMessageBox,
QSizePolicy,
QStyle,
QVBoxLayout,
QWidget,
@@ -34,6 +35,12 @@ from bec_widgets.widgets.containers.main_window.addons.notification_center.notif
NotificationIndicator,
)
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
from bec_widgets.widgets.containers.main_window.addons.status_pill import (
CardAlign,
HoverCard,
HoverCardController,
StatusPillItem,
)
from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar
from bec_widgets.widgets.utility.feedback_dialog.feedback_dialog import FeedbackDialog
@@ -70,6 +77,7 @@ class BECMainWindow(BECWidget, QMainWindow):
self._nc_margin = 16
self._position_notification_centre()
self._widget_hierarchy_dialog: WidgetHierarchyDialog | None = None
self._status_items: list[tuple[StatusPillItem, QWidget]] = []
# Init ui
self._init_ui()
@@ -182,16 +190,22 @@ class BECMainWindow(BECWidget, QMainWindow):
self._client_info_label.setAlignment(
Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter
)
# Full label used in the hover widget
self._client_info_label_full = QLabel(self)
# Full label shown in a card above the scrolling one on hover
self._client_info_label_full = QLabel()
self._client_info_label_full.setAlignment(
Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter
)
# Hover widget to show the full client info label
self._client_info_hover = HoverWidget(
self, simple=self._client_info_label, full=self._client_info_label_full
self._client_info_card = HoverCard(
self._client_info_label, self._client_info_label_full, object_name="client_info_card"
)
self.status_bar.addWidget(self._client_info_hover, 1)
self._client_info_card.hide()
self._client_info_hover = HoverCardController(
self._client_info_label,
self._client_info_card,
can_open=lambda: bool(self._client_info_label_full.text()),
align=CardAlign.CENTER,
)
self.status_bar.addWidget(self._client_info_label, 1)
# Timer to automatically clear client messages once they expire
self._client_info_expire_timer = QTimer(self)
@@ -240,6 +254,80 @@ class BECMainWindow(BECWidget, QMainWindow):
self.status_bar.addWidget(self._scan_progress_bar_with_separator)
def add_status_item(self, item: StatusPillItem) -> QWidget:
"""
Add a status pill to the status bar, after a separator. Every pill has a stretch, but only
one in the "fill" width mode uses it: the width mode sets the size policy of its holder.
Args:
item(StatusPillItem): The pill, e.g. the scan pill.
Returns:
QWidget: The status bar widget holding the separator and the pill.
"""
holder = QWidget()
holder.layout = QHBoxLayout(holder)
holder.layout.setContentsMargins(0, 0, 0, 0)
holder.layout.setSpacing(0)
holder.layout.addWidget(self._add_separator(separate_object=True))
holder.layout.addWidget(item)
self._set_status_holder_fill(holder, item.width_mode == "fill")
self.status_bar.addWidget(holder, 1)
item.fill_changed.connect(
lambda fill, holder=holder: self._set_status_holder_fill(holder, fill)
)
item.dock_requested.connect(self.open_in_dock_area)
item.set_dock_handler(lambda: self.status_dock_area() is not None)
self._status_items.append((item, holder))
return holder
def status_dock_area(self):
"""
The dock area the status pills open their widgets in: the central widget if it is a dock
area, else None (a double-click on a pill then does nothing).
Returns:
BECDockArea | None: The dock area.
"""
# pylint: disable=import-outside-toplevel
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
central = self.centralWidget()
return central if isinstance(central, BECDockArea) else None
def show_dock_area(self) -> None:
"""Bring the dock area of status_dock_area into view; for windows with several views."""
@SafeSlot(str)
def open_in_dock_area(self, widget: str) -> QWidget | None:
"""
Show a widget in the dock area: raise the dock of one that is already there, else add a
new one.
Args:
widget(str): Class name of the widget, e.g. "ScanProgressBar".
Returns:
QWidget | None: The docked widget, or None without a dock area.
"""
dock_area = self.status_dock_area()
if dock_area is None:
return None
self.show_dock_area()
for dock in dock_area.dock_list():
existing = dock.widget()
if type(existing).__name__ == widget:
dock.toggleView(True)
dock.raise_()
return existing
return dock_area.new(widget)
@staticmethod
def _set_status_holder_fill(holder: QWidget, fill: bool) -> None:
"""Let a pill use its stretch in the status bar, or keep it at the width of the pill."""
policy = QSizePolicy.Policy.Expanding if fill else QSizePolicy.Policy.Fixed
holder.setSizePolicy(policy, holder.sizePolicy().verticalPolicy())
def _add_separator(self, separate_object: bool = False) -> QWidget | None:
"""
Add a vertically centred separator to the status bar or just return it as a separate object.
@@ -529,9 +617,9 @@ class BECMainWindow(BECWidget, QMainWindow):
# Status bar widgets cleanup
# Client info label cleanup
self._client_info_hover.cleanup()
self._client_info_card.close()
self._client_info_label.cleanup()
self._client_info_hover.close()
self._client_info_hover.deleteLater()
# Scan progress bar cleanup
self._scan_progress_bar_simple.close()
self._scan_progress_bar_simple.deleteLater()
@@ -539,6 +627,11 @@ class BECMainWindow(BECWidget, QMainWindow):
self._scan_progress_bar_full.deleteLater()
self._scan_progress_hover.close()
self._scan_progress_hover.deleteLater()
# Status pills cleanup
for item, _holder in self._status_items:
item.close()
item.deleteLater()
self._status_items.clear()
super().cleanup()
+433
View File
@@ -0,0 +1,433 @@
"""
Shared painted building blocks of the status widgets: tone colours, a tone chip and the stage bar
(a painted progress bar with a centred label), used by the scan progress bar, the scan queue and
the status bar pills.
"""
from __future__ import annotations
from enum import StrEnum
from qtpy.QtCore import Property, QPointF, QRectF, QSize, Qt, QTimer, Signal
from qtpy.QtGui import QColor, QFont, QFontDatabase, QFontMetricsF, QPainter, QPainterPath, QPen
from qtpy.QtWidgets import QApplication, QLabel, QSizePolicy, QWidget
from bec_widgets.utils.theme_utils import css, theme_colors
class Tone(StrEnum):
"""Colour roles of chips, icons and row flashes."""
NEUTRAL = "neutral"
RUN = "run"
OK = "ok"
WARN = "warn"
BAD = "bad"
ACCENT = "accent"
class BarMode(StrEnum):
"""What a StageBar shows."""
IDLE = "idle" # empty track, muted label
BUSY = "busy" # something runs without a known progress: moving stripes
PROGRESS = "progress" # filled to the fraction
DONE = "done" # full, ok colour
ERROR = "error" # full, danger colour
PAUSED = "paused" # filled to the fraction, warning colour
def mono_font(point_delta: float = 0, bold: bool = False) -> QFont:
"""Return the system fixed-width font, optionally resized and bold."""
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
base = QApplication.font().pointSizeF() if QApplication.instance() else 10
font.setPointSizeF(max(6.0, base + point_delta))
font.setBold(bold)
return font
class Chip(QLabel):
"""A small rounded label with a tone colour, used for states and metadata."""
TONES = tuple(Tone)
def __init__(
self, text: str = "", tone: Tone | str = Tone.NEUTRAL, parent: QWidget | None = None
):
super().__init__(text, parent)
self._tone = Tone(tone)
self.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed)
self.setTextFormat(Qt.TextFormat.RichText)
self.refresh_style()
def set_tone(self, tone: Tone | str) -> None:
"""Change the tone and restyle."""
tone = Tone(tone)
if tone != self._tone:
self._tone = tone
self.refresh_style()
def refresh_style(self) -> None:
"""Re-read the theme colours."""
colors = theme_colors()
tone_color = {
Tone.NEUTRAL: colors["muted"],
Tone.RUN: colors["run"],
Tone.OK: colors["ok"],
Tone.WARN: colors["warn"],
Tone.BAD: colors["bad"],
Tone.ACCENT: colors["primary"],
}.get(self._tone, colors["muted"])
if self._tone == Tone.NEUTRAL:
bg, fg, border = css(colors["fg"], 0.06), css(colors["fg"]), css(colors["border"])
else:
bg, fg, border = css(tone_color, 0.16), css(tone_color), css(tone_color, 0.45)
self.setStyleSheet(
f"QLabel {{ background: {bg}; color: {fg}; border: 1px solid {border};"
f" border-radius: 9px; padding: 1px 7px; }}"
)
class StageBar(QWidget):
"""
A painted progress bar with a centred label.
Modes:
busy: animated stripes, for steps without measurable progress.
progress: a filled share of the bar.
done / error / paused / idle: a full or empty bar in the matching colour.
With fill_height the bar grows into all the vertical space it is given and its label grows
with it; the bar height is then the minimum.
"""
# How the label grows on a bar taller than its minimum: the text height grows by TEXT_GROWTH
# per pixel of extra bar height, up to TEXT_MAX_SHARE of the bar height, and the text may use
# at most TEXT_WIDTH_SHARE of the bar width (minus TEXT_PADDING). Sizes snap to TEXT_STEP
# points. The width cap is computed for a reserved number of characters rather than the live
# text: the longest label seen in this scan, rounded up to RESERVE_STEP (at least
# RESERVE_MIN). A label that changes length on a tick ("0:59" -> "1:00") keeps its size; the
# reservation only grows within a scan and is reset when a new scan starts.
TEXT_GROWTH = 0.45
TEXT_MAX_SHARE = 0.50
TEXT_WIDTH_SHARE = 0.85
TEXT_PADDING = 12
TEXT_STEP = 0.5
RESERVE_MIN = 16
RESERVE_STEP = 4
# emitted when the text scale or the stretched state changes, for controls next to the bar
sizing_changed = Signal()
def __init__(self, parent: QWidget | None = None, height: int = 24):
super().__init__(parent)
self._mode = BarMode.IDLE
self._fraction = 0.0
self._text = ""
self._phase = 0.0
self._bar_height = height
self._fill_height = False
self._scale = 1.0
self._stretched = False
self._reserved = self.RESERVE_MIN
self._reserve_text = ""
self.corner_radius: float | None = None # fixed corner radius, else scaled with height
self.label_pixel_size: int | None = None # fixed label size in pixels, else scaled
# width the label is scaled for on a stretched bar, set by the host from its whole row:
# the bar's own width changes with the controls next to it (e.g. a Stop button that
# scales with the label), and following it would make the two resize each other
self.scale_width: float | None = None
self._font_key: tuple | None = None
self._font: QFont | None = None
self._stripe_timer = QTimer(self)
self._stripe_timer.setInterval(100) # 10 Hz is enough for the stripes to read as moving
self._stripe_timer.timeout.connect(self._advance_stripes)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setMinimumWidth(80)
def sizeHint(self) -> QSize:
return QSize(240, self._bar_height)
def minimumSizeHint(self) -> QSize:
return QSize(80, self._bar_height)
def set_bar_height(self, height: int) -> None:
"""Set the bar height in pixels."""
self._bar_height = max(10, height)
self.updateGeometry()
self.update()
def get_bar_height(self) -> int:
"""The bar height in pixels."""
return self._bar_height
bar_height = Property(int, get_bar_height, set_bar_height)
def set_fill_height(self, fill: bool) -> None:
"""Grow into all the vertical space the layout gives, with the label scaled to match."""
self._fill_height = fill
vertical = QSizePolicy.Policy.Expanding if fill else QSizePolicy.Policy.Fixed
self.setSizePolicy(QSizePolicy.Policy.Expanding, vertical)
self.updateGeometry()
self._sync_sizing()
self.update()
def get_fill_height(self) -> bool:
"""Whether the bar fills the vertical space it is given."""
return self._fill_height
fill_height = Property(bool, get_fill_height, set_fill_height)
def text_scale(self, height: float) -> float:
"""
How much larger than normal text should be on a bar of this height. Shared with
controls next to the bar, such as a Stop button, so they read as one control.
"""
if not self._fill_height or height <= self._bar_height:
return 1.0
base = QFontMetricsF(mono_font(-1)).height()
target = base + self.TEXT_GROWTH * (height - self._bar_height)
target = min(target, height * self.TEXT_MAX_SHARE)
return max(1.0, target / base)
def _reserve_for(self, text: str) -> int:
step = self.RESERVE_STEP
return max(self.RESERVE_MIN, -(-len(text) // step) * step)
def reserve(self, text: str) -> None:
"""
Reserve room for a label at least this long. The reference text only changes when the
rounded reservation grows, so labels of the same length never change the size.
"""
reserved = self._reserve_for(text)
if reserved > self._reserved:
self._reserved, self._reserve_text = reserved, text
self._sync_sizing()
def reset_reserved(self) -> None:
"""Size for the current text again, e.g. when a new scan starts."""
reserved = self._reserve_for(self._text)
if (reserved, self._text) != (self._reserved, self._reserve_text):
self._reserved, self._reserve_text = reserved, self._text
self._sync_sizing()
def _reference_text(self) -> str:
# the reserved label padded to the reserved length; measuring real characters keeps the
# estimate right for a proportional fallback font as well as for a monospace one
return self._reserve_text.ljust(self._reserved, "0")
def label_scale(self, height: float, width: float) -> float:
"""
The label scale for a bar of this size: 1 at the minimum height, growing gently on a
taller bar, capped so the reserved number of characters fits the width. It does not
depend on the live text, so it stays put while the text changes.
"""
scale = self.text_scale(height)
if scale <= 1.0:
return 1.0
base_font = mono_font(-1)
reserved_width = QFontMetricsF(base_font).horizontalAdvance(self._reference_text())
room = (width - self.TEXT_PADDING) * self.TEXT_WIDTH_SHARE
scale = min(scale, max(1.0, room / reserved_width))
base = base_font.pointSizeF()
size = max(base, round(base * scale / self.TEXT_STEP) * self.TEXT_STEP)
return size / base
def label_font(self, height: float, width: float) -> QFont:
"""The label font for a bar of this size (see label_scale), cached per size."""
key = (round(height), round(width), self._reference_text(), self._fill_height)
key += (self.label_pixel_size,)
if key != self._font_key or self._font is None:
font = mono_font(-1)
if self.label_pixel_size:
font.setPixelSize(self.label_pixel_size)
else:
font.setPointSizeF(font.pointSizeF() * self.label_scale(height, width))
self._font_key, self._font = key, font
return self._font
@property
def mode(self) -> BarMode:
"""The current display mode."""
return self._mode
@property
def text(self) -> str:
"""The label drawn on the bar."""
return self._text
@property
def fraction(self) -> float:
"""The filled share of the bar, 0..1."""
return self._fraction
def set_state(self, mode: BarMode | str, fraction: float = 0.0, text: str = "") -> None:
"""
Update what the bar shows.
Args:
mode(BarMode | str): busy, progress, done, error, paused or idle.
fraction(float): Filled share for the progress mode, 0..1.
text(str): Label drawn in the middle of the bar.
"""
mode = BarMode(mode)
fraction = min(1.0, max(0.0, fraction))
if (mode, fraction, text) == (self._mode, self._fraction, self._text):
return
text_changed = text != self._text
self._mode, self._fraction, self._text = mode, fraction, text
self._sync_timer()
if text_changed:
self.reserve(text) # grows within a scan, never shrinks per tick
self._sync_tooltip()
self.update()
def _bar_rect(self) -> QRectF:
bar_height = max(self._bar_height, self.height()) if self._fill_height else self._bar_height
rect = QRectF(0.5, 0.5, self.width() - 1, bar_height - 1)
rect.moveTop((self.height() - bar_height) / 2 + 0.5)
return rect
def _label_width(self, rect: QRectF) -> float:
if self._fill_height and self.scale_width:
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."""
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 ""
if tooltip != self.toolTip():
self.setToolTip(tooltip)
def resizeEvent(self, event): # pylint: disable=invalid-name
super().resizeEvent(event)
self._sync_tooltip()
self._sync_sizing()
def _sync_sizing(self) -> None:
rect = self._bar_rect()
scale = self.label_scale(rect.height(), self._label_width(rect))
stretched = self._fill_height and self.height() > self._bar_height
if (scale, stretched) != (self._scale, self._stretched):
self._scale, self._stretched = scale, stretched
self.sizing_changed.emit()
@property
def scale(self) -> float:
"""The label's current scale (1.0 at the minimum height)."""
return self._scale
@property
def stretched(self) -> bool:
"""Whether the bar fills more than its minimum height."""
return self._stretched
def _sync_timer(self) -> None:
# a minimized window keeps its widgets "visible"; Qt sends them a spontaneous hide and,
# on restore, a show event, but a state update while minimized must not restart the timer
if self._mode == BarMode.BUSY and self.isVisible() and not self.window().isMinimized():
if not self._stripe_timer.isActive():
self._stripe_timer.start()
else:
self._stripe_timer.stop()
def showEvent(self, event): # pylint: disable=invalid-name
super().showEvent(event)
self._sync_timer()
def hideEvent(self, event): # pylint: disable=invalid-name
super().hideEvent(event)
self._stripe_timer.stop()
def _advance_stripes(self) -> None:
self._phase = (self._phase + 2.4) % 16
self.update()
def cleanup(self) -> None:
"""Stop the stripe animation."""
self._stripe_timer.stop()
def paintEvent(self, _event): # pylint: disable=invalid-name
colors = theme_colors()
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = self._bar_rect()
if self.corner_radius is not None:
radius = min(self.corner_radius, rect.height() / 2)
else:
radius = min(10.0, max(6.0, rect.height() * 0.12), rect.height() / 2)
track = QPainterPath()
track.addRoundedRect(rect, radius, radius)
tone = {
BarMode.BUSY: colors["run"],
BarMode.PROGRESS: colors["primary"],
BarMode.DONE: colors["ok"],
BarMode.ERROR: colors["bad"],
BarMode.PAUSED: colors["warn"],
}.get(self._mode, colors["muted"])
painter.fillPath(track, _with_alpha(colors["fg"], 0.08))
fill_rect = QRectF(rect)
if self._mode in (BarMode.PROGRESS, BarMode.PAUSED):
fill_rect.setWidth(rect.width() * self._fraction)
elif self._mode == BarMode.IDLE:
fill_rect.setWidth(0)
painter.save()
painter.setClipPath(track)
if self._mode == BarMode.BUSY:
painter.fillRect(rect, _with_alpha(tone, 0.22))
stripe = _with_alpha(tone, 0.38)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(stripe)
h = rect.height()
x = rect.left() - h - 16 + self._phase
while x < rect.right() + h:
poly = QPainterPath()
poly.moveTo(QPointF(x, rect.bottom()))
poly.lineTo(QPointF(x + 8, rect.bottom()))
poly.lineTo(QPointF(x + 8 + h, rect.top()))
poly.lineTo(QPointF(x + h, rect.top()))
poly.closeSubpath()
painter.drawPath(poly)
x += 16
elif fill_rect.width() > 0:
painter.fillRect(
fill_rect, tone if self._mode != BarMode.PAUSED else _with_alpha(tone, 0.8)
)
painter.restore()
painter.setPen(QPen(_with_alpha(colors["border"], 0.9), 1))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawPath(track)
if self._text:
font = self.label_font(rect.height(), self._label_width(rect))
painter.setFont(font)
flags = Qt.AlignmentFlag.AlignCenter
text_rect = QRectF(rect.toAlignedRect()) # both passes on whole pixels
text = painter.fontMetrics().elidedText(
self._text, Qt.TextElideMode.ElideRight, int(rect.width() - 12)
)
filled = self._mode in (BarMode.DONE, BarMode.ERROR) or (
self._mode == BarMode.PROGRESS and self._fraction > 0
)
painter.setPen(colors["muted"] if self._mode == BarMode.IDLE else colors["fg"])
painter.drawText(text_rect, flags, text)
if filled:
painter.save()
painter.setClipRect(fill_rect)
painter.setPen(colors["on_primary"])
painter.drawText(text_rect, flags, text)
painter.restore()
painter.end()
def _with_alpha(color: QColor, alpha: float) -> QColor:
c = QColor(color)
c.setAlphaF(alpha)
return c
+8 -8
View File
@@ -155,7 +155,7 @@ def test_launch_window_notifies_launcher_ready(qtbot, bec_launch_window, monkeyp
(["launcher", "dock_area", "scan_progress"], False),
(["launcher", "dock_area", "scan_progress_simple", "scan_progress_full"], False),
(
["launcher", "dock_area", "scan_progress_simple", "scan_progress_full", "hover_widget"],
["launcher", "dock_area", "scan_progress_simple", "scan_progress_full", "status_card"],
False,
),
(["launcher", "external_window"], True),
@@ -164,8 +164,8 @@ def test_launch_window_notifies_launcher_ready(qtbot, bec_launch_window, monkeyp
def test_gui_server_turns_off_the_lights(bec_launch_window, qtbot, connection_names, hide):
connections = {}
for name in connection_names:
if name == "hover_widget":
conn = _unparented_connection("HoverWidget")
if name == "status_card":
conn = _unparented_connection("HoverCard")
elif name == "external_window":
conn = _top_level_connection(qtbot, "external_window")
else:
@@ -199,14 +199,14 @@ def test_launcher_detects_external_main_window(bec_launch_window, qtbot):
def test_launcher_logs_unparented_non_window_connection_once(bec_launch_window):
connection = _unparented_connection("HoverWidget")
connection = _unparented_connection("HoverCard")
with mock.patch("bec_widgets.applications.launch_window.logger.warning") as mock_warning:
bec_launch_window._turn_off_the_lights({"window": connection})
bec_launch_window._turn_off_the_lights({"window": connection})
mock_warning.assert_called_once()
assert "HoverWidget" in mock_warning.call_args.args[0]
assert "HoverCard" in mock_warning.call_args.args[0]
@pytest.mark.parametrize(
@@ -218,7 +218,7 @@ def test_launcher_logs_unparented_non_window_connection_once(bec_launch_window):
(["launcher", "dock_area", "scan_progress"], True),
(["launcher", "dock_area", "scan_progress_simple", "scan_progress_full"], True),
(
["launcher", "dock_area", "scan_progress_simple", "scan_progress_full", "hover_widget"],
["launcher", "dock_area", "scan_progress_simple", "scan_progress_full", "status_card"],
True,
),
(["launcher", "external_window"], False),
@@ -232,8 +232,8 @@ def test_launch_window_closes(bec_launch_window, qtbot, connection_names, close_
"""
connections = {}
for name in connection_names:
if name == "hover_widget":
conn = _unparented_connection("HoverWidget")
if name == "status_card":
conn = _unparented_connection("HoverCard")
elif name == "external_window":
conn = _top_level_connection(qtbot, "external_window")
else:
+110 -1
View File
@@ -4,7 +4,7 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, PropertyMock, patch
import pytest
from qtpy.QtCore import QEvent, QPoint, QPointF, QSettings
from qtpy.QtCore import QEvent, QPoint, QPointF, QSettings, Qt
from qtpy.QtGui import QEnterEvent, QIcon
from qtpy.QtWidgets import QApplication, QFrame, QLabel, QMessageBox
@@ -351,6 +351,33 @@ def test_hover_widget_tooltip(qtbot):
assert hover._tooltip is None
def test_client_info_opens_a_card_with_the_full_message(bec_main_window, qtbot, monkeypatch):
"""The scrolling client info shows the full message in a card on hover; empty: no card."""
from bec_widgets.widgets.containers.main_window.addons import status_pill
label = bec_main_window._client_info_label
card = bec_main_window._client_info_card
hover = bec_main_window._client_info_hover
centre = label.mapToGlobal(label.rect().center())
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: centre))
hover.open()
assert not card.isVisible() # nothing to show yet
message = "Scan 12 needs the shutter open before it can continue"
bec_main_window.display_client_message({"message": message, "expire": 0}, {})
hover.open()
assert card.isVisible() and card.content.text() == message
card_centre = card.frameGeometry().center().x()
assert abs(card_centre - centre.x()) <= 2 or not card.screen().availableGeometry().contains(
card.frameGeometry().adjusted(-60, 0, 60, 0)
) # centred on the label unless clamped at a screen edge
far = QPoint(-5000, -5000)
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: far))
qtbot.waitUntil(lambda: not card.isVisible(), timeout=2000)
def test_widget_tooltip_show_and_hide(qtbot):
"""
WidgetTooltip should appear when show_above is called and hide on Leave.
@@ -389,3 +416,85 @@ def test_hover_widget_mouse_events(qtbot):
assert hover._tooltip is not None
assert hover._tooltip.isVisible()
assert hover._tooltip.content is full
def test_status_bar_holds_several_pills_each_with_its_own_fill(bec_main_window, qtbot, tmp_path):
from qtpy.QtCore import QSettings
from qtpy.QtWidgets import QLabel
from bec_widgets.widgets.containers.main_window.addons.status_pill import StatusPillItem
def pill(name):
item = StatusPillItem(
bec_main_window,
client=bec_main_window.client,
settings=lambda: QSettings(str(tmp_path / f"{name}.ini"), QSettings.Format.IniFormat),
settings_prefix=name,
card_content=QLabel("details"),
)
item.apply_sizes()
return item
first, second = pill("first_pill"), pill("second_pill")
first_holder = bec_main_window.add_status_item(first)
holder = bec_main_window.add_status_item(second)
items = [item for item, _ in bec_main_window._status_items]
assert items == [first, second]
bec_main_window.resize(1400, 300)
bec_main_window.show()
qtbot.waitExposed(bec_main_window)
qtbot.waitUntil(lambda: holder.width() == holder.sizeHint().width(), timeout=2000)
width, first_width = holder.width(), first_holder.width()
label = bec_main_window._client_info_label
assert label.width() > width # the client info label takes the spare room
second.set_width_mode("fill") # stays in place with its stretch; the other pill is untouched
qtbot.waitUntil(lambda: holder.width() > width, timeout=2000)
assert holder.isVisible() and holder.x() > first_holder.x()
assert first_holder.width() == first_width
shared_width = label.width() # the pill and the label share the spare room
second.set_width_mode("normal")
qtbot.waitUntil(lambda: holder.width() == width and label.width() > shared_width, timeout=2000)
def test_open_in_dock_area_adds_one_dock_then_raises_it(bec_main_window, qtbot, tmp_path):
from qtpy.QtCore import QSettings
from qtpy.QtWidgets import QLabel
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
from bec_widgets.widgets.containers.main_window.addons.status_pill import StatusPillItem
from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue
class QueuePill(StatusPillItem):
DOCK_WIDGET = "BECQueue"
item = QueuePill(
bec_main_window,
client=bec_main_window.client,
settings=lambda: QSettings(str(tmp_path / "queue.ini"), QSettings.Format.IniFormat),
settings_prefix="queue_pill",
card_content=QLabel("queue"),
)
item.apply_sizes()
bec_main_window.add_status_item(item)
item._prepare_card()
assert item.card.hint.isHidden() # no dock area as central widget yet
assert bec_main_window.open_in_dock_area("BECQueue") is None
dock_area = BECDockArea(parent=bec_main_window, client=bec_main_window.client)
bec_main_window.setCentralWidget(dock_area)
item._prepare_card()
assert not item.card.hint.isHidden()
def docked():
return [w for w in dock_area.widget_list() if isinstance(w, BECQueue)]
with qtbot.waitSignal(item.dock_requested):
qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton)
assert len(docked()) == 1
first = docked()[0]
# a second double-click raises the docked one instead of adding another
qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton)
assert len(docked()) == 1
assert bec_main_window.open_in_dock_area("BECQueue") is first
+252
View File
@@ -0,0 +1,252 @@
import pytest
from qtpy.QtCore import QSettings, Qt
from qtpy.QtWidgets import QLabel
from bec_widgets.tests.utils import create_widget
from bec_widgets.widgets.containers.main_window.addons.status_pill import (
StatusPillItem,
ToolIndicator,
ToolSeverity,
stage_mode,
)
from bec_widgets.widgets.progress.stage_bar import BarMode, Tone
@pytest.mark.parametrize(
"indicator, expected",
[
(ToolIndicator(), (BarMode.IDLE, 0.0)),
(ToolIndicator(severity=ToolSeverity.OK), (BarMode.DONE, 1.0)),
(ToolIndicator(severity=ToolSeverity.INFO, active=True), (BarMode.BUSY, 0.0)),
(ToolIndicator(severity=ToolSeverity.INFO, progress=0.25), (BarMode.PROGRESS, 0.25)),
(ToolIndicator(severity=ToolSeverity.OK, progress=0.5), (BarMode.PROGRESS, 0.5)),
(ToolIndicator(severity=ToolSeverity.WARNING, progress=0.4), (BarMode.PAUSED, 0.4)),
(ToolIndicator(severity=ToolSeverity.WARNING, active=True), (BarMode.PAUSED, 0.0)),
(ToolIndicator(severity=ToolSeverity.CRITICAL, progress=0.3), (BarMode.ERROR, 1.0)),
],
)
def test_indicator_maps_to_a_bar_mode(indicator, expected):
assert stage_mode(indicator) == expected
def test_a_paused_bar_is_filled_to_its_fraction(qtbot):
from qtpy.QtGui import QColor
from bec_widgets.widgets.progress.stage_bar import StageBar
bar = StageBar()
qtbot.addWidget(bar)
bar.resize(200, 20)
def filled_columns(fraction):
bar.set_state(BarMode.PAUSED, fraction)
image = bar.grab().toImage()
row = image.height() // 2
track = QColor(image.pixel(image.width() - 3, row))
return sum(
1 for x in range(image.width()) if QColor(image.pixel(x, row)).rgb() != track.rgb()
)
quarter, three_quarters = filled_columns(0.25), filled_columns(0.75)
assert quarter < three_quarters
assert three_quarters == pytest.approx(3 * quarter, rel=0.25)
@pytest.fixture
def generic_item(qtbot, mocked_client, tmp_path):
content = QLabel("All good")
widget = create_widget(
qtbot,
StatusPillItem,
client=mocked_client,
settings=lambda: QSettings(str(tmp_path / "pill.ini"), QSettings.Format.IniFormat),
settings_prefix="demo_pill",
card_content=content,
card_width=260,
)
widget.apply_sizes()
yield widget
def test_generic_item_shows_any_indicator_and_content(generic_item, qtbot):
item = generic_item
assert item.card.content.text() == "All good"
assert item.card.card.width() == 260
seen = []
item.indicator_changed.connect(seen.append)
down = ToolIndicator(
severity=ToolSeverity.CRITICAL,
summary="2 services down",
badge="2 down",
attention=True,
tooltip="x",
)
item.set_indicator(down)
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.badge_chip.text() == "2 down" and item.badge_chip._tone == Tone.BAD
assert item.badge_reveal.shown
item.set_indicator(ToolIndicator(severity=ToolSeverity.OK, summary="BEC running"))
assert item.pill.mode == BarMode.DONE
qtbot.waitUntil(lambda: not item.badge_reveal.shown, timeout=2000) # after the hide delay
qtbot.waitUntil(lambda: not item.badge_reveal.active, timeout=2000)
def test_generic_item_saves_its_choices_under_its_prefix(generic_item, tmp_path):
generic_item.set_width_mode("wide")
generic_item.set_large(True)
settings = QSettings(str(tmp_path / "pill.ini"), QSettings.Format.IniFormat)
assert settings.value("demo_pill/pill_width") == "wide"
assert settings.value("demo_pill/large", type=bool) is True
assert settings.value("scan_status/pill_width") is None
def _cursor_at(monkeypatch, point):
from bec_widgets.widgets.containers.main_window.addons import status_pill
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: point))
def _outer_rect(item):
from qtpy.QtCore import QPoint, QRect
return QRect(item.card.card.mapToGlobal(QPoint(0, 0)), item.card.card.size())
def test_card_stays_on_screen_and_follows_the_pill(generic_item, qtbot, monkeypatch):
from qtpy.QtCore import QPoint
from qtpy.QtWidgets import QPushButton
item = generic_item
button = QPushButton("Stop", item)
reveal = item.add_trailing(button)
area = item.screen().availableGeometry()
item.move(area.right() - item.sizeHint().width() + 1, area.bottom() - 60)
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
item.open_card()
window = item.card.frameGeometry()
assert area.contains(window), (area, window) # clamped at the right edge of the screen
# the content grows: the card stays bottom-anchored above the pill
pill_top = item.pill.mapToGlobal(QPoint(0, 0)).y()
item.card.content.setText("All good\nbut a much longer\nexplanation\nover four lines")
qtbot.waitUntil(lambda: item.card.height() > window.height(), timeout=2000)
qtbot.waitUntil(lambda: _outer_rect(item).bottom() < pill_top, timeout=2000)
# a widget slides in next to the pill and moves it: the card follows
item.move(area.left() + 40, area.bottom() - 60)
qtbot.wait(50)
item.close_card()
item.open_card()
before = item.pill.mapToGlobal(QPoint(0, 0)).x() - item.card.x()
reveal.set_shown(True)
qtbot.waitUntil(lambda: not reveal.active, timeout=2000)
after = item.pill.mapToGlobal(QPoint(0, 0)).x() - item.card.x()
assert after == before
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
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
item.open_card()
dialog = QDialog(item.card.content)
dialog.setWindowModality(Qt.WindowModality.ApplicationModal)
dialog.show()
qtbot.waitUntil(dialog.isVisible)
qtbot.wait(item.GRACE_MS + 300)
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)
dialog.deleteLater()
class DockablePill(StatusPillItem):
DOCK_WIDGET = "BECQueue"
@pytest.fixture
def dockable_item(qtbot, mocked_client, tmp_path):
widget = create_widget(
qtbot,
DockablePill,
client=mocked_client,
settings=lambda: QSettings(str(tmp_path / "dock.ini"), QSettings.Format.IniFormat),
settings_prefix="dock_pill",
card_content=QLabel("details"),
)
widget.apply_sizes()
yield widget
def test_dock_hint_only_with_a_dock_widget_and_a_handler(generic_item, dockable_item):
assert generic_item.card.hint is None # no DOCK_WIDGET, no hint
hint = dockable_item.card.hint
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() == ""
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
dockable_item.set_dock_handler(None)
assert hint.isHidden()
def test_double_click_requests_its_widget_and_closes_the_card(dockable_item, qtbot):
dockable_item.set_dock_handler(lambda: True)
dockable_item.open_card()
qtbot.waitUntil(dockable_item.card.isVisible)
with qtbot.waitSignal(dockable_item.dock_requested) as blocker:
qtbot.mouseDClick(dockable_item.pill, Qt.MouseButton.LeftButton)
assert blocker.args == ["BECQueue"]
assert not dockable_item.card.isVisible()
assert not dockable_item.pill.hasFocus() # a double-click does not focus the pill
def test_double_click_does_nothing_without_a_dock_area(dockable_item, generic_item, qtbot):
dockable_item.set_dock_handler(lambda: False)
with qtbot.assertNotEmitted(dockable_item.dock_requested):
qtbot.mouseDClick(dockable_item.pill, Qt.MouseButton.LeftButton)
with qtbot.assertNotEmitted(generic_item.dock_requested):
qtbot.mouseDClick(generic_item.pill, Qt.MouseButton.LeftButton)
with qtbot.assertNotEmitted(dockable_item.dock_requested):
dockable_item.set_dock_handler(lambda: True)
qtbot.mouseDClick(dockable_item.pill, Qt.MouseButton.RightButton)
def test_tooltip_tells_how_to_dock(dockable_item, generic_item):
dockable_item.set_indicator(ToolIndicator(summary="ok", tooltip="All good"))
assert dockable_item.pill.toolTip() == "All good" # 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
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
generic_item.set_indicator(ToolIndicator(summary="ok", tooltip="Plain"))
assert generic_item.pill.toolTip() == "Plain"
def test_hover_cleanup_can_run_twice(generic_item, recwarn):
generic_item.hover.cleanup()
generic_item.hover.cleanup()
assert not [w for w in recwarn if "Failed to disconnect" in str(w.message)]