feat(scan_progressbar): replace the scan progress bar with live scan hook steps, also in the status bar

This commit is contained in:
wyzula_j authored and Jan Wyzula committed 2026-11-09 13:55:29 +01:00
1 parent 8615cd037c
commit ad99f801ee
18 files changed
+3625 -809

No files matched your search

+3 -3
View File
@@ -334,11 +334,11 @@ class BECMainApp(BECMainWindow):
tour_steps.append(client_info_step)
# Register the scan progress bar if available
if hasattr(self, "_scan_progress_hover"):
if hasattr(self, "_scan_status_item"):
progress_step = self.guided_tour.register_widget(
widget=self._scan_progress_hover,
widget=self._scan_status_item,
title="Scan Progress",
text="Monitor the progress of ongoing scans. Hover over the progress bar to see detailed information including elapsed time and estimated completion.",
text="Monitor the running scan. Hover over the bar to see its steps, metadata and Stop; right-click it to change its width.",
)
tour_steps.append(progress_step)
+1 -1
View File
@@ -5356,7 +5356,7 @@ class ScanControl(RPCBase):
class ScanProgressBar(RPCBase):
"""Widget to display a progress bar that is hooked up to the scan progress of a scan."""
"""Live progress of the running scan."""
_IMPORT_MODULE = "bec_widgets.widgets.progress.scan_progressbar.scan_progressbar"
+1 -1
View File
@@ -150,7 +150,7 @@ widget_icons = {
"ScanControl": "tune",
"ScanIndexComboBox": "history",
"ScanMetadata": "list_alt",
"ScanProgressBar": "timelapse",
"ScanProgressBar": "av_timer",
"ScatterWaveform": "scatter_plot",
"SignalComboBox": "list_alt",
"SignalLabel": "scoreboard",
@@ -385,7 +385,7 @@ class BECDockArea(DockAreaWidget):
),
"scan_progress_bar": (
widget_icons["ScanProgressBar"],
"Scan Progress Bar",
"Scan Progress",
"ScanProgressBar",
),
"terminal": (widget_icons["BecConsole"], "Terminal", "BecConsole"),
@@ -1,16 +1,8 @@
import sys
"""A frameless window that behaves like a tooltip, with any content widget."""
from qtpy import QtGui, QtWidgets
from qtpy.QtCore import QPoint, Qt
from qtpy.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QProgressBar,
QVBoxLayout,
QWidget,
)
from qtpy.QtWidgets import QApplication, QFrame, QVBoxLayout, QWidget
class WidgetTooltip(QWidget):
@@ -123,81 +115,3 @@ class WidgetTooltip(QWidget):
self.move(x, y)
self.show()
self.raise_()
class HoverWidget(QWidget):
def __init__(self, parent: QWidget | None = None, *, simple: QWidget, full: QWidget):
super().__init__(parent)
self._simple = simple
self._full = full
self._full.setVisible(False)
self._tooltip = None
lay = QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(simple)
def enterEvent(self, event):
# suppress empty-label tooltips for labels
if isinstance(self._full, QLabel) and not self._full.text():
return
if self._tooltip is None: # first time only
self._tooltip = WidgetTooltip(self._full)
self._full.setVisible(True)
centre = self.mapToGlobal(self.rect().center())
self._tooltip.show_above(centre)
super().enterEvent(event)
def leaveEvent(self, event):
if self._tooltip and self._tooltip.isVisible():
self._tooltip.hide()
super().leaveEvent(event)
def close(self):
if self._tooltip:
self._tooltip.close()
self._tooltip.deleteLater()
self._tooltip = None
super().close()
################################################################################
# Demo
# Just a simple example to show how the HoverWidget can be used to display
# a tooltip with a full widget inside (two different widgets are used
# for the simple and full versions).
################################################################################
class DemoSimpleWidget(QLabel): # pragma: no cover
"""A simple widget to be used as a trigger for the tooltip."""
def __init__(self) -> None:
super().__init__()
self.setText("Hover me for a preview!")
class DemoFullWidget(QProgressBar): # pragma: no cover
"""A full widget to be shown in the tooltip."""
def __init__(self) -> None:
super().__init__()
self.setRange(0, 100)
self.setValue(75)
self.setFixedWidth(320)
self.setFixedHeight(30)
if __name__ == "__main__": # pragma: no cover
app = QApplication(sys.argv)
window = QWidget()
window.layout = QHBoxLayout(window)
hover_widget = HoverWidget(simple=DemoSimpleWidget(), full=DemoFullWidget())
window.layout.addWidget(hover_widget)
window.show()
sys.exit(app.exec_())
@@ -0,0 +1,328 @@
"""
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.
"""
from __future__ import annotations
import time
from typing import Callable
from bec_lib.endpoints import MessageEndpoints
from qtpy.QtCore import QObject, QSettings, QThreadPool, Signal
from qtpy.QtWidgets import QWidget
from bec_widgets.utils.bec_connector import Worker
from bec_widgets.utils.error_popups import SafeSlot
from bec_widgets.widgets.containers.main_window.addons.status_pill import ( # noqa: F401
KEYBOARD_FOCUS_REASONS,
PILL_FILL_MIN,
PILL_MODES,
PILL_WIDTHS,
HoverCard,
Reveal,
StatusPillItem,
ToolIndicator,
ToolSeverity,
)
from bec_widgets.widgets.control.buttons.stop_button.stop_button import StopButton
from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import (
ScanRunState,
format_duration,
hook_label,
)
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import (
ScanProgressBar,
describe_state,
)
from bec_widgets.widgets.progress.stage_bar import BarMode
SETTINGS_PREFIX = "scan_status"
SETTINGS_WIDTH = f"{SETTINGS_PREFIX}/pill_width"
SETTINGS_LARGE = f"{SETTINGS_PREFIX}/large"
def pill_labels(state: ScanRunState | None, now: float | None = None) -> tuple[str, str, str]:
"""
The three label lengths of the status-bar scan pill: (short, medium, long).
short: the step only ("Staging 0:03", "43%", "Done", "Failed").
medium: with the scan number ("#12 · Staging · 0:03", "#12 · 43% · 1:20 left").
long: everything that fits a wide bar, including the instruction and the next step.
Args:
state(ScanRunState | None): The scan state, or None while the queue is idle.
now(float, optional): time.monotonic() to evaluate the timers at.
"""
now = now if now is not None else time.monotonic()
if state is None:
return ("Queue idle",) * 3
number = f"#{state.scan_number}" if state.scan_number is not None else ""
name = state.display_name
title = f"{number} {name}".strip()
def join(*parts: str) -> str:
return " · ".join(p for p in parts if p)
if state.finished:
# the same outcome word, step name and duration as the big widget (describe_state)
info = describe_state(state, now)
outcome, where, took = info["outcome"], info["where"], info["took"]
if where:
medium = f"{number} {outcome.lower()} in {where}".strip()
return outcome, join(medium, took), join(title, f"{outcome} in {where}", took)
return (
outcome,
join(f"{number} {outcome.lower()}".strip(), took),
join(title, outcome, took),
)
nxt = state.next_hook if state.has_hooks else None
next_text = f"next: {nxt}" if nxt else ""
total = state.progress_max or state.num_points
if state.measuring and total:
value = int(state.progress_value or 0)
pct = f"{int(round(value / total * 100))}%"
left = state.remaining(now)
left_text = f"{format_duration(left)} left" if left is not None else ""
if state.status == "paused":
return f"Paused {pct}", join(number, "Paused", pct), join(title, "Paused", pct)
return (
pct,
join(number, pct, left_text),
join(title, f"Point {value} of {int(total)}", pct, left_text, next_text),
)
step = "Paused" if state.status == "paused" else hook_label(state.top_hook) or "Running"
timer = format_duration(state.hook_elapsed(now) if state.has_hooks else state.elapsed(now))
instruction = state.instruction
return (
f"{step} {timer}",
join(number, step, timer),
join(title, step, timer, instruction, next_text),
)
def scan_indicator(state: ScanRunState | None, waiting: int = 0) -> ToolIndicator:
"""
The pill indicator for a scan state: the same step, outcome and progress as the big widget.
Args:
state(ScanRunState | None): The scan state, or None while the queue is idle.
waiting(int): How many scans wait in the queue.
"""
info = describe_state(state)
mode = BarMode(info["bar_mode"]) if state is not None else BarMode.IDLE
severity = {
BarMode.DONE: ToolSeverity.OK,
BarMode.ERROR: ToolSeverity.CRITICAL,
BarMode.PAUSED: ToolSeverity.WARNING,
}.get(mode, ToolSeverity.INFO)
progress = info["bar_fraction"] if mode in (BarMode.PROGRESS, BarMode.PAUSED) else None
return ToolIndicator(
severity=severity,
summary=pill_labels(state)[1],
badge=f"{waiting} waiting" if waiting > 0 else None,
progress=progress,
active=mode == BarMode.BUSY,
)
class _QueueStatusRead(QObject):
"""Carries the queue status read at startup to the GUI thread."""
done = Signal(object)
def _read_queue_status(connector, result: _QueueStatusRead) -> None:
"""Read the stored queue status; runs in the thread pool and touches no widget."""
try:
msg = connector.get(MessageEndpoints.scan_queue_status())
except Exception: # pylint: disable=broad-except
msg = None
try:
result.done.emit(msg)
except RuntimeError:
pass # the pill was deleted meanwhile
class ScanProgressCard(HoverCard):
"""The hover card of the scan pill, with the full ScanProgressBar."""
def __init__(self, owner: "ScanStatusItem"):
super().__init__(owner, width=400, object_name="scan_status_card")
self.progress = ScanProgressBar(
parent=self.card,
client=owner.client,
fill_height=False,
rpc_exposed=False,
rpc_passthrough_children=False,
)
self.progress.layout().setContentsMargins(0, 0, 0, 0) # pylint: disable=no-member
self.set_content(self.progress)
class ScanStatusItem(StatusPillItem):
"""
Status-bar scan pill, Stop button and waiting count, with the full ScanProgressBar on hover.
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
and saved per user.
"""
DOCK_WIDGET = "ScanProgressBar"
def __init__(
self,
parent: QWidget | None = None,
client=None,
settings: Callable[[], QSettings] | None = None,
**kwargs,
):
super().__init__(
parent=parent,
client=client,
settings=settings,
settings_prefix=SETTINGS_PREFIX,
**kwargs,
)
self.get_bec_shortcuts()
self._state: ScanRunState | None = None
self._waiting = 0
# the shared Stop: a click aborts, then offers Emergency Stop; the arrow has Finish / halt
self.stop_button = StopButton(
parent=self, client=self.client, rpc_exposed=False, rpc_passthrough_children=False
)
self.stop_reveal = self.add_trailing(self.stop_button)
self.waiting_chip = self.badge_chip
self.waiting_reveal = self.badge_reveal
self.tracker = self.card.progress.tracker
self.tracker.changed.connect(self._on_state)
self.tracker.tick.connect(self._update_indicator)
self.bec_dispatcher.connect_slot(self.on_queue_status, MessageEndpoints.scan_queue_status())
# the waiting count until the first live queue status: read in the background
self._queue_status_live = False
self._closed = False
self._queue_read = _QueueStatusRead()
self._queue_read.done.connect(self._on_queue_status_read)
self._queue_read_worker: Worker | None = None
self._load_waiting()
self.apply_sizes()
self._on_state(self.tracker.state)
def create_card(self) -> HoverCard:
return ScanProgressCard(self)
################################################################################
# Sizes and theme
################################################################################
def apply_sizes(self) -> None:
"""Apply the pill width mode and the normal/large heights and fonts, Stop included."""
if hasattr(self, "stop_button"):
self._style_stop()
super().apply_sizes()
def _style_stop(self) -> None:
large = self.large
self.stop_button.set_size(
height=34 if large else 22,
font_px=14 if large else 11,
icon_px=16 if large else 12,
radius=5,
pad=8,
)
def apply_theme(self, theme: str):
"""Restyle after a theme change."""
self._style_stop()
super().apply_theme(theme)
################################################################################
# State
################################################################################
@SafeSlot(object)
def _on_state(self, state: ScanRunState | None) -> None:
self._state = state
self._update_indicator()
@SafeSlot()
def _update_indicator(self) -> None:
state = getattr(self, "_state", None)
self.set_indicator(scan_indicator(state, getattr(self, "_waiting", 0)))
if hasattr(self, "stop_button"):
self.stop_button.request_id = state.rid if state is not None else None
self.stop_reveal.set_shown(describe_state(state)["can_stop"])
def pill_text(self) -> str:
"""The label for the current width mode."""
short, medium, long = pill_labels(getattr(self, "_state", None))
return {"compact": short, "normal": medium}.get(self.width_mode, long)
################################################################################
# Waiting count
################################################################################
def _load_waiting(self) -> None:
self._queue_read_worker = Worker(
_read_queue_status, self.client.connector, self._queue_read
)
QThreadPool.globalInstance().start(self._queue_read_worker)
@SafeSlot(object)
def _on_queue_status_read(self, msg) -> None:
self._queue_read_worker = None
# a live update is newer than the stored status; after cleanup nothing is shown
if self._closed or self._queue_status_live:
return
if msg is not None and hasattr(msg, "content"):
self._count_waiting(msg.content)
@SafeSlot(dict, dict)
def on_queue_status(self, content: dict, _metadata: dict) -> None:
"""Count the waiting scans of the primary queue."""
self._queue_status_live = True
self._count_waiting(content)
def _count_waiting(self, content: dict) -> None:
primary = (content.get("queue") or {}).get("primary")
infos = getattr(primary, "info", None) or (
primary.get("info") if isinstance(primary, dict) else []
)
waiting = 0
for info in infos or []:
status = getattr(info, "status", None)
if status is None and isinstance(info, dict):
status = info.get("status")
if str(status) == "PENDING":
waiting += 1
self.set_waiting(waiting)
def set_waiting(self, count: int) -> None:
"""Show how many scans wait in the queue; hidden at zero."""
self._waiting = count
self._update_indicator()
################################################################################
# Card
################################################################################
def keep_card_open(self) -> bool:
"""Keep the card while a stop waits for confirmation."""
return not self.card.progress.confirm_frame.isHidden()
def on_card_closed(self) -> None:
"""Drop a pending stop confirmation."""
self.card.progress.cancel_stop()
def cleanup(self):
"""Unsubscribe and close the card's progress bar, then the pill."""
self._closed = True # a queue status read still in flight is dropped
self.bec_dispatcher.disconnect_slot(
self.on_queue_status, MessageEndpoints.scan_queue_status()
)
self.card.progress.close()
super().cleanup()
@@ -28,12 +28,12 @@ from bec_widgets.widgets.containers.dock_area.profile_utils import (
is_experimental_features_enabled,
set_experimental_features_enabled,
)
from bec_widgets.widgets.containers.main_window.addons.hover_widget import HoverWidget
from bec_widgets.widgets.containers.main_window.addons.notification_center.notification_banner import (
BECNotificationBroker,
NotificationCentre,
NotificationIndicator,
)
from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
from bec_widgets.widgets.containers.main_window.addons.status_pill import (
CardAlign,
@@ -42,7 +42,6 @@ from bec_widgets.widgets.containers.main_window.addons.status_pill import (
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
from bec_widgets.widgets.utility.widget_hierarchy_tree.widget_hierarchy_tree import (
WidgetHierarchyDialog,
@@ -59,8 +58,6 @@ logger = bec_logger.logger
class BECMainWindow(BECWidget, QMainWindow):
RPC = True
PLUGIN = True
SCAN_PROGRESS_WIDTH = 120 # px
SCAN_PROGRESS_HEIGHT = 20 # px
def __init__(self, parent=None, window_title: str = "BEC", **kwargs):
super().__init__(parent=parent, **kwargs)
@@ -218,41 +215,11 @@ class BECMainWindow(BECWidget, QMainWindow):
################################################################################
# Progress‑bar helpers
def _add_scan_progress_bar(self):
# Setting HoverWidget for the scan progress bar - minimal and full version
self._scan_progress_bar_simple = ScanProgressBar(
self,
one_line_design=True,
rpc_exposed=False,
rpc_passthrough_children=False,
enable_dynamic_stylesheet=True,
# Scan pill: live progress, Stop and the waiting count; the full ScanProgressBar on hover
self._scan_status_item = ScanStatusItem(
self, rpc_exposed=False, rpc_passthrough_children=False
)
self._scan_progress_bar_simple.show_elapsed_time = False
self._scan_progress_bar_simple.show_remaining_time = False
self._scan_progress_bar_simple.show_source_label = False
self._scan_progress_bar_simple.progressbar.label_template = ""
self._scan_progress_bar_simple.progressbar.setFixedHeight(self.SCAN_PROGRESS_HEIGHT)
self._scan_progress_bar_simple.progressbar.setFixedWidth(self.SCAN_PROGRESS_WIDTH)
# This one do not need dynamic styling on hover ScanProgressBar since user will hover on it probably later, when progress bar is big enough
self._scan_progress_bar_full = ScanProgressBar(
self, rpc_exposed=False, rpc_passthrough_children=False, enable_dynamic_stylesheet=False
)
self._scan_progress_hover = HoverWidget(
self, simple=self._scan_progress_bar_simple, full=self._scan_progress_bar_full
)
# Bundle the progress bar with a separator
separator = self._add_separator(separate_object=True)
self._scan_progress_bar_with_separator = QWidget()
self._scan_progress_bar_with_separator.layout = QHBoxLayout(
self._scan_progress_bar_with_separator
)
self._scan_progress_bar_with_separator.layout.setContentsMargins(0, 0, 0, 0)
self._scan_progress_bar_with_separator.layout.setSpacing(0)
self._scan_progress_bar_with_separator.layout.addWidget(separator)
self._scan_progress_bar_with_separator.layout.addWidget(self._scan_progress_hover)
self.status_bar.addWidget(self._scan_progress_bar_with_separator)
self._scan_progress_bar_with_separator = self.add_status_item(self._scan_status_item)
def add_status_item(self, item: StatusPillItem) -> QWidget:
"""
@@ -620,13 +587,6 @@ class BECMainWindow(BECWidget, QMainWindow):
self._client_info_hover.cleanup()
self._client_info_card.close()
self._client_info_label.cleanup()
# Scan progress bar cleanup
self._scan_progress_bar_simple.close()
self._scan_progress_bar_simple.deleteLater()
self._scan_progress_bar_full.close()
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()
@@ -0,0 +1,686 @@
"""
Live state of the running scan, built from scan status, scan progress and scan hook messages.
Scan hook messages (``MessageEndpoints.scan_hook``) name the current step, when it started and the
current instruction; the latest one is stored, so a widget opened mid-scan reads it. For a scan
that reports no hooks, the tracker still follows the scan status and the measurement progress,
but cannot name the current step or the current instruction.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Any
from bec_lib.endpoints import MessageEndpoints
from bec_lib.logger import bec_logger
from qtpy.QtCore import QObject, QThreadPool, QTimer, Signal
from bec_widgets.utils.bec_connector import Worker
from bec_widgets.utils.error_popups import SafeSlot
from bec_widgets.widgets.progress.scan_progressbar.scan_ui import scan_display_name
logger = bec_logger.logger
SCAN_SEQUENCE = (
"prepare_scan",
"open_scan",
"stage",
"pre_scan",
"scan_core",
"post_scan",
"unstage",
"close_scan",
)
HOOK_NAMES = {
"prepare_scan": "Preparing",
"open_scan": "Opening scan",
"stage": "Staging",
"pre_scan": "Pre-scan",
"scan_core": "Measuring",
"post_scan": "Completing",
"unstage": "Unstaging",
"close_scan": "Closing",
"on_exception": "Cleaning up",
}
FINISHED_STATUSES = ("closed", "aborted", "halted", "user_completed")
_ACTION_VERBS = {
"set": "Moving",
"stage": "Staging",
"unstage": "Unstaging",
"trigger": "Triggering",
"read": "Reading",
"kickoff": "Kicking off",
"complete": "Completing",
"pre_scan": "Pre-scan on",
"baseline_reading": "Reading baseline",
"open_scan": "Opening scan",
"close_scan": "Closing scan",
"wait": "Waiting",
}
_SILENT_ACTIONS = ("scan_report_instruction", "publish_data_as_read", "broadcast_scan_device_info")
def hook_label(hook: str | None) -> str:
"""Return the friendly name of a scan hook, falling back to the hook name itself."""
if not hook:
return ""
return HOOK_NAMES.get(hook, hook.replace("_", " ").capitalize())
def format_duration(seconds: float | None) -> str:
"""Format seconds as m:ss, or h:mm:ss for an hour or more."""
if seconds is None:
return ""
seconds = max(0, int(round(seconds)))
hours, rest = divmod(seconds, 3600)
minutes, secs = divmod(rest, 60)
if hours:
return f"{hours}:{minutes:02d}:{secs:02d}"
return f"{minutes}:{secs:02d}"
def _get(obj: Any, key: str, default: Any = None) -> Any:
if isinstance(obj, dict):
return obj.get(key, default)
return getattr(obj, key, default)
def queued_scan_ids(content: dict) -> set[str]:
"""The scan ids of all requests in a ScanQueueStatusMessage content, running or waiting."""
ids = set()
for queue in (_get(content, "queue") or {}).values():
for info in _get(queue, "info") or []:
ids.update(scan_id for scan_id in _get(info, "scan_id") or [] if scan_id)
return ids
def queue_entry_status(content: dict, scan_id: str) -> str | None:
"""
The status of the queue entry that runs scan_id, else None. It is the scan worker's own
state: "PAUSED" during a pause, "RUNNING" again after a resume, while the status of the
queue itself stays "RUNNING" during a (hard) pause.
"""
for queue in (_get(content, "queue") or {}).values():
for info in _get(queue, "info") or []:
if scan_id in (_get(info, "scan_id") or []):
return str(_get(info, "status") or "")
return None
def _format_value(value: Any) -> str:
if isinstance(value, float):
return f"{value:.4g}"
return str(value)
def _device_list(device: Any) -> list[str]:
if device is None:
return []
if isinstance(device, (list, tuple)):
return [str(dev) for dev in device]
return [str(device)]
def _join_devices(devices: list[str], limit: int = 3) -> str:
if len(devices) <= limit:
return ", ".join(devices)
return f"{', '.join(devices[:limit])} +{len(devices) - limit}"
def describe_instructions(instructions: list[Any], waiting: bool = False) -> str:
"""
Turn device instructions into one short line, such as "Moving samx to -5".
Args:
instructions(list): DeviceInstructionMessage objects or their dict form.
waiting(bool): Whether the scan waits for these instructions to finish.
Returns:
str: The description, or an empty string if nothing is worth showing.
"""
by_action: dict[str, list[Any]] = {}
for instr in instructions or []:
action = _get(instr, "action")
if not action or action in _SILENT_ACTIONS:
continue
by_action.setdefault(action, []).append(instr)
if not by_action:
return ""
action, items = list(by_action.items())[-1]
devices: list[str] = []
for item in items:
devices.extend(dev for dev in _device_list(_get(item, "device")) if dev not in devices)
parameter = _get(items[-1], "parameter") or {}
if action == "rpc":
func = parameter.get("func", "")
text = f"Calling {_join_devices(devices)}.{func}()" if devices else f"Calling {func}()"
elif action == "set" and len(devices) == 1 and "value" in parameter:
target = _format_value(parameter["value"])
if waiting:
return f"Waiting for {devices[0]} to reach {target}"
text = f"Moving {devices[0]} to {target}"
elif action in ("open_scan", "close_scan", "baseline_reading") or not devices:
text = _ACTION_VERBS.get(action, action.replace("_", " ").capitalize())
else:
verb = _ACTION_VERBS.get(action, action.replace("_", " ").capitalize())
text = f"{verb} {_join_devices(devices)}"
if waiting:
if devices:
return f"Waiting for {_join_devices(devices)} ({action.replace('_', ' ')})"
return f"Waiting · {text}"
return text
@dataclass
class HookTiming:
"""Accumulated time spent in one hook of the running scan."""
hook: str
nested: bool = False
total: float = 0.0
count: int = 0
started_at: float | None = None
status: str = "running"
parent: str | None = None
def duration(self, now: float | None = None) -> float:
"""Total time in this hook, including the current visit when it is still running."""
if self.started_at is not None and now is not None:
return self.total + max(0.0, now - self.started_at)
return self.total
@dataclass
class ScanRunState:
"""Everything the progress widgets show about one scan."""
scan_id: str
rid: str | None = None
scan_number: int | None = None
scan_name: str | None = None
status: str = "open"
user_metadata: dict = field(default_factory=dict)
request_inputs: dict = field(default_factory=dict)
num_points: int | None = None
hook: str | None = None
top_hook: str | None = None
hook_error: str | None = None
hook_started_local: float | None = None
instruction: str = ""
waiting: bool = False
wait_started_local: float | None = None
progress_value: float | None = None
progress_max: float | None = None
measure_started_local: float | None = None
started_local: float = field(default_factory=time.monotonic)
finished_local: float | None = None
has_hooks: bool = False
status_seen: bool = False
progress_seen: bool = False
lost: bool = False
timings: dict[str, HookTiming] = field(default_factory=dict)
_clock_offset: float = 0.0
@property
def display_name(self) -> str:
"""The scan's name: the user's scan_name when set, else the scan type."""
return scan_display_name(self.user_metadata, self.scan_name)
@property
def finished(self) -> bool:
"""Whether the scan has ended, successfully or not."""
return self.status in FINISHED_STATUSES
@property
def measuring(self) -> bool:
"""Whether the scan is in its measurement step (or has progress without hook info)."""
if self.has_hooks:
return self.top_hook == "scan_core"
return self.progress_value is not None
@property
def next_hook(self) -> str | None:
"""The next top-level hook in the scan sequence, or None after the last one."""
if self.top_hook not in SCAN_SEQUENCE:
return SCAN_SEQUENCE[0] if not self.has_hooks else None
index = SCAN_SEQUENCE.index(self.top_hook)
if index + 1 < len(SCAN_SEQUENCE):
return SCAN_SEQUENCE[index + 1]
return None
def elapsed(self, now: float | None = None) -> float:
"""Seconds since the scan started, frozen once it finished."""
end = self.finished_local or (now if now is not None else time.monotonic())
return max(0.0, end - self.started_local)
def hook_elapsed(self, now: float | None = None) -> float:
"""Seconds spent in the current hook."""
if self.hook_started_local is None:
return 0.0
now = now if now is not None else time.monotonic()
return max(0.0, now - self.hook_started_local)
def wait_elapsed(self, now: float | None = None) -> float | None:
"""Seconds the scan has been waiting on the current instructions, if it waits."""
if not self.waiting or self.wait_started_local is None:
return None
now = now if now is not None else time.monotonic()
return max(0.0, now - self.wait_started_local)
def remaining(self, now: float | None = None) -> float | None:
"""Estimated seconds left in the measurement, from the progress so far."""
if not self.progress_value or not self.progress_max or self.measure_started_local is None:
return None
now = now if now is not None else time.monotonic()
spent = max(0.0, now - self.measure_started_local)
left = max(0.0, self.progress_max - self.progress_value)
return spent / self.progress_value * left
def step_times(self) -> list[HookTiming]:
"""
Hook timings in scan order: the steps of the scan sequence, each followed by the hooks
that ran nested inside it.
"""
steps = [t for t in self.timings.values() if not t.nested]
order = {hook: index for index, hook in enumerate(SCAN_SEQUENCE)}
steps.sort(key=lambda t: order.get(t.hook, len(SCAN_SEQUENCE)))
result = [t for t in self.timings.values() if t.nested and t.parent is None]
for step in steps:
result.append(step)
result.extend(t for t in self.timings.values() if t.nested and t.parent == step.hook)
return result
def server_now(self) -> float:
"""Current time on the server clock, estimated from the last live message."""
return time.time() - self._clock_offset
def _local(self, server_time: float) -> float:
"""The time.monotonic() value of a time on the server clock."""
return time.monotonic() - max(0.0, self.server_now() - server_time)
def _enter_hook(self, hook: str, timestamp: float) -> None:
nested = hook not in SCAN_SEQUENCE and hook != "on_exception"
timing = self.timings.get(hook)
if timing is None:
parent = self.top_hook if nested else None
timing = self.timings[hook] = HookTiming(hook=hook, nested=nested, parent=parent)
timing.count += 1
timing.started_at = timestamp
timing.status = "running"
def _leave_hook(self, hook: str, timestamp: float, status: str = "completed") -> None:
timing = self.timings.get(hook)
if timing is None or timing.started_at is None:
return
timing.total += max(0.0, timestamp - timing.started_at)
timing.started_at = None
timing.status = status
@staticmethod
def is_top_hook(hook: str | None) -> bool:
"""Whether a hook is a step of the scan sequence rather than one nested inside a step."""
return hook in SCAN_SEQUENCE or hook == "on_exception"
def _enter_step(self, hook: str, started_at: float) -> None:
"""A new top-level step restarts the step timer and clears the previous instruction."""
if self.hook and not self.is_top_hook(self.hook):
self._leave_hook(self.hook, started_at)
if self.top_hook:
self._leave_hook(self.top_hook, started_at)
self._enter_hook(hook, started_at)
self.top_hook = hook
self.hook_started_local = self._local(started_at)
self.instruction = ""
self.waiting = False
self.wait_started_local = None
if hook == "scan_core":
self.measure_started_local = self.hook_started_local
def apply_hook(self, content: dict, live: bool = True) -> None:
"""
Update the state from one ScanHookMessage content.
A top-level step (prepare_scan ... close_scan, on_exception) is timed from when the server
started it. Nested hooks (scan modifiers) keep the step running; inside scan_core they are
not timed separately, because the measurement progress already covers them.
Args:
content(dict): The message content.
live(bool): False for the stored message read at startup, whose timestamp may be old
and says nothing about the clock offset to the server.
"""
now = time.monotonic()
timestamp = content.get("timestamp") or time.time()
if live:
self._clock_offset = time.time() - timestamp
hook = content.get("hook")
status = content.get("status", "running")
self.has_hooks = True
if self.is_top_hook(hook):
if status == "running":
if hook != self.top_hook:
self._enter_step(hook, content.get("hook_started_at") or timestamp)
elif self.hook and not self.is_top_hook(self.hook):
self._leave_hook(self.hook, timestamp)
self.hook = hook
else:
self._leave_hook(hook, timestamp, status)
if status == "error":
self.hook_error = hook
elif hook:
if status == "running" and hook != self.hook:
if self.hook and not self.is_top_hook(self.hook):
self._leave_hook(self.hook, timestamp)
if self.top_hook != "scan_core":
self._enter_hook(hook, timestamp)
self.hook = hook
elif status in ("completed", "interrupted", "error") and hook == self.hook:
self._leave_hook(hook, timestamp, status)
waiting = bool(content.get("waiting"))
instructions = content.get("instructions") or []
if instructions:
text = describe_instructions(instructions, waiting=waiting)
if text:
self.instruction = text
if waiting:
wait_started_at = content.get("wait_started_at")
if not self.waiting or wait_started_at is not None:
offset = timestamp - wait_started_at if wait_started_at else 0.0
if not live and wait_started_at:
offset = max(0.0, self.server_now() - wait_started_at)
self.wait_started_local = now - max(0.0, offset)
self.waiting = True
else:
self.waiting = False
self.wait_started_local = None
def apply_status(self, content: dict, metadata: dict) -> None:
"""Update the state from one ScanStatusMessage content."""
self.status_seen = True
self.status = content.get("status", self.status)
for attr in ("scan_number", "scan_name", "num_points"):
value = content.get(attr)
if value is not None:
setattr(self, attr, value)
if content.get("user_metadata"):
self.user_metadata = dict(content["user_metadata"])
if content.get("request_inputs"):
self.request_inputs = dict(content["request_inputs"])
self.rid = self.rid or metadata.get("RID")
if self.finished and self.finished_local is None:
self.finished_local = time.monotonic()
# steps still open when an abort or halt ended the scan were interrupted, not failed;
# a step that failed has already reported "error" itself
ended = self.status in ("closed", "user_completed")
end_status = "completed" if ended else "interrupted"
for hook in (self.hook, self.top_hook):
if hook:
self._leave_hook(hook, self.server_now(), end_status)
self.waiting = False
def end_lost(self) -> None:
"""End the scan as aborted: it left the queue without a final status (e.g. a restart)."""
self.lost = True
self.apply_status({"status": "aborted"}, {})
def clear_lost(self, status: str | None) -> None:
"""A real status arrived for a scan ended as lost: it wins over the inferred end."""
self.lost = False
if status not in FINISHED_STATUSES:
self.finished_local = None # it still runs
elif status in ("closed", "user_completed"):
for timing in self.timings.values():
if timing.status == "interrupted":
timing.status = "completed"
def resume(self) -> None:
"""The scan runs again after a pause; BEC sends no new scan status for it."""
if self.status == "paused":
self.status = "open"
def apply_progress(self, content: dict) -> None:
"""Update the measurement progress from one ProgressMessage content."""
self.progress_seen = True
self.progress_value = content.get("value", 0)
self.progress_max = content.get("max_value") or self.num_points
if self.measure_started_local is None:
self.measure_started_local = time.monotonic()
class _InitialRead(QObject):
"""Carries the stored scan messages read at startup to the GUI thread."""
done = Signal(object)
def _read_initial_state(connector, result: _InitialRead) -> None:
"""Read the stored scan status, hook, progress and queue status; runs in the thread pool."""
stored = {}
for name, endpoint in (
("status", MessageEndpoints.scan_status()),
("hook", MessageEndpoints.scan_hook()),
("progress", MessageEndpoints.scan_progress()),
("queue", MessageEndpoints.scan_queue_status()),
):
try:
msg = connector.get(endpoint)
except Exception: # pylint: disable=broad-except
logger.debug(f"Could not read {endpoint.endpoint}")
msg = None
stored[name] = msg if msg is not None and hasattr(msg, "content") else None
try:
result.done.emit(stored)
except RuntimeError:
pass # the tracker was deleted meanwhile
class ScanHookTracker(QObject):
"""
Follow the running scan and emit its state on every change.
Signals:
changed(object): A ScanRunState, or None before any scan was seen.
tick(): Emitted every 250 ms while a scan runs, to refresh live timers.
At start it reads the stored scan status, and the stored scan hook and progress of that scan,
so a widget opened mid-scan shows the current step, its instruction and the real progress at
once. Steps that ended before it was opened are not known and not listed.
The stored messages are read in the thread pool, so creating a widget never waits for Redis;
a live message that arrives meanwhile is newer and wins.
A scan that leaves the queue without a final status, e.g. because the BEC server was
restarted while it ran, is ended as aborted after LOST_SCAN_GRACE_MS, so the views do not
stay on its last progress. A paused scan counts as running again once its queue entry runs
again or it reports its next step.
"""
# a finished scan can leave the queue just before its final status arrives
LOST_SCAN_GRACE_MS = 2000
changed = Signal(object)
tick = Signal()
def __init__(self, client, bec_dispatcher, parent: QObject | None = None):
super().__init__(parent=parent)
self.client = client
self.bec_dispatcher = bec_dispatcher
self.state: ScanRunState | None = None
self._connected = False
self._timer = QTimer(self)
self._timer.setInterval(250)
self._timer.timeout.connect(self.tick.emit)
self._lost_check = QTimer(self)
self._lost_check.setSingleShot(True)
self._lost_check.setInterval(self.LOST_SCAN_GRACE_MS)
self._lost_check.timeout.connect(self._end_lost_scan)
self._queued: set[str] | None = None
self._lost_scan_id: str | None = None
self.loaded = False # the stored state was read (or there was none)
self._closed = False
# parented, so it is deleted with the tracker on the GUI thread, never in the thread pool
self._initial = _InitialRead(self)
self._initial.done.connect(self._on_initial_state)
self._initial_worker: Worker | None = None
def start(self) -> None:
"""Subscribe to the scan endpoints and load the current scan, if any."""
if self._connected:
return
self.bec_dispatcher.connect_slot(self.on_scan_status, MessageEndpoints.scan_status())
self.bec_dispatcher.connect_slot(self.on_scan_progress, MessageEndpoints.scan_progress())
self.bec_dispatcher.connect_slot(self.on_scan_hook, MessageEndpoints.scan_hook())
self.bec_dispatcher.connect_slot(self.on_queue_status, MessageEndpoints.scan_queue_status())
self._connected = True
self._initial_worker = Worker(_read_initial_state, self.client.connector, self._initial)
QThreadPool.globalInstance().start(self._initial_worker)
@SafeSlot(object)
def _on_initial_state(self, stored: dict) -> None:
self._initial_worker = None
if self._closed:
return
self.loaded = True
msg = stored.get("status")
if msg is None:
return # no scan ran yet
state = self.state
if state is not None and (state.status_seen or state.scan_id != msg.content.get("scan_id")):
return # a live status is newer, or the stored one is of an older scan
# a live hook alone leaves the number, name and metadata to the stored status; what came
# in live is newer than what is stored
self.on_scan_status(msg.content, msg.metadata)
state = self.state
if state is None or state.finished:
return
hook = stored.get("hook")
if (
not state.has_hooks
and hook is not None
and hook.content.get("scan_id") == state.scan_id
):
state.apply_hook(hook.content, live=False)
progress = stored.get("progress")
if (
not state.progress_seen
and progress is not None
and progress.metadata.get("scan_id") == state.scan_id
):
state.apply_progress(progress.content)
queue = stored.get("queue")
if queue is not None and self._queued is None:
# a stored "open" of a scan the queue no longer has: ended after the same grace
# period as a live update, as it may just have finished between the two reads
self.on_queue_status(queue.content, queue.metadata)
self._emit()
def _state_for(self, scan_id: str | None, rid: str | None = None) -> ScanRunState | None:
if not scan_id:
return self.state
if self.state is None or self.state.scan_id != scan_id:
self.state = ScanRunState(scan_id=scan_id, rid=rid)
elif rid and not self.state.rid:
self.state.rid = rid
return self.state
def _emit(self) -> None:
if self.state is not None and not self.state.finished:
if not self._timer.isActive():
self._timer.start()
else:
self._timer.stop()
self.changed.emit(self.state)
@SafeSlot(dict, dict)
def on_scan_status(self, content: dict, metadata: dict) -> None:
"""Handle a ScanStatusMessage."""
scan_id = content.get("scan_id")
if not scan_id:
return
if self.state is not None and self.state.scan_id != scan_id:
if content.get("status") != "open":
return
state = self._state_for(scan_id, metadata.get("RID"))
if state.lost:
state.clear_lost(content.get("status"))
state.apply_status(content, metadata)
self._emit()
@SafeSlot(dict, dict)
def on_scan_progress(self, content: dict, metadata: dict) -> None:
"""Handle a scan ProgressMessage."""
scan_id = metadata.get("scan_id")
if self.state is None or (scan_id and scan_id != self.state.scan_id):
return # progress of a scan whose status was not seen
if self.state.finished:
return
self.state.apply_progress(content)
self._emit()
@SafeSlot(dict, dict)
def on_scan_hook(self, content: dict, metadata: dict) -> None:
"""Handle a ScanHookMessage."""
scan_id = content.get("scan_id")
if not scan_id:
return
if self.state is not None and self.state.scan_id == scan_id and self.state.finished:
return
state = self._state_for(scan_id, metadata.get("RID"))
state.resume() # a paused scan reports no step until it runs again
state.apply_hook(content)
self._emit()
@SafeSlot(dict, dict)
def on_queue_status(self, content: dict, _metadata: dict) -> None:
"""Handle a ScanQueueStatusMessage: notice a running scan that left the queue."""
self._queued = queued_scan_ids(content)
state = self.state
if (
state is not None
and state.status == "paused"
and queue_entry_status(content, state.scan_id) == "RUNNING"
):
state.resume()
self._emit()
if state is None or state.finished or state.scan_id in self._queued:
self._lost_check.stop()
elif not self._lost_check.isActive() or self._lost_scan_id != state.scan_id:
self._lost_scan_id = state.scan_id
self._lost_check.start()
def _end_lost_scan(self) -> None:
state = self.state
if state is None or state.finished or state.scan_id != self._lost_scan_id:
return # it ended normally, or another scan started meanwhile
if self._queued is None or state.scan_id in self._queued:
return
state.end_lost()
self._emit()
def cleanup(self) -> None:
"""Stop the timers, drop a startup read still running and disconnect from all endpoints."""
self._closed = True
self._timer.stop()
self._lost_check.stop()
if not self._connected:
return
self.bec_dispatcher.disconnect_slot(self.on_scan_status, MessageEndpoints.scan_status())
self.bec_dispatcher.disconnect_slot(self.on_scan_progress, MessageEndpoints.scan_progress())
self.bec_dispatcher.disconnect_slot(self.on_scan_hook, MessageEndpoints.scan_hook())
self.bec_dispatcher.disconnect_slot(
self.on_queue_status, MessageEndpoints.scan_queue_status()
)
self._connected = False
@@ -1,158 +1,800 @@
"""
Scan progress widget: what the running scan does now, what comes next, and one Stop.
"""
from __future__ import annotations
import os
import time
from bec_lib.logger import bec_logger
from qtpy.QtCore import Signal
from qtpy.QtWidgets import QVBoxLayout, QWidget
from qtpy.QtCore import QPoint, QRectF, Qt, QTimer, Signal
from qtpy.QtGui import QFontInfo, QPainter, QPen
from qtpy.QtWidgets import (
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
from bec_widgets.utils.bec_widget import BECWidget
from bec_widgets.utils.error_popups import SafeProperty
from bec_widgets.utils.ui_loader import UILoader
from bec_widgets.widgets.progress.bec_progressbar.bec_progressbar import ProgressState
from bec_widgets.widgets.progress.progress_backend import BECProgressTracker, ProgressSnapshot
from bec_widgets.utils.error_popups import SafeProperty, SafeSlot
from bec_widgets.utils.flow_layout import FlowLayoutWidget
from bec_widgets.utils.theme_utils import css, theme_colors
from bec_widgets.widgets.control.buttons.stop_button.stop_button import StopAction, StopButton
from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import (
ScanHookTracker,
ScanRunState,
format_duration,
hook_label,
)
from bec_widgets.widgets.progress.scan_progressbar.scan_ui import (
ElidedLabel,
MetaChip,
metadata_items,
request_inputs_summary,
scan_bundle_names,
)
from bec_widgets.widgets.progress.stage_bar import BarMode, Chip, StageBar, Tone, mono_font
logger = bec_logger.logger
BEC_STATUS_TO_PROGRESS_STATE = {
"open": ProgressState.NORMAL,
"paused": ProgressState.PAUSED,
"aborted": ProgressState.WARNING,
"halted": ProgressState.INTERRUPTED,
"closed": ProgressState.COMPLETED,
"user_completed": ProgressState.COMPLETED,
# During the measurement a wait time is only shown once a device has kept the scan waiting this
# long; the per-point waits are short and their timer would only blink.
MEASURE_WAIT_SHOWN_AFTER_S = 2.0
# outcome word and tone of a finished scan, shared by every view of it (bar, chip, status bar)
_FINISHED_CHIPS = {
"closed": ("Done", Tone.OK),
"user_completed": ("Finished early", Tone.OK),
"aborted": ("Aborted", Tone.BAD),
"halted": ("Halted", Tone.BAD),
}
def describe_state(state: ScanRunState | None, now: float | None = None) -> dict:
"""
Compute every text and mode the progress widget shows for a scan state.
Kept free of widgets so other views of the scan and tests can share it.
Args:
state(ScanRunState | None): The scan state, or None before any scan.
now(float, optional): time.monotonic() to evaluate the timers at.
Returns:
dict: title, chip, chip_tone, bar_mode, bar_fraction, bar_text, instruction, next, can_stop.
"""
now = now if now is not None else time.monotonic()
if state is None:
return {
"title": "No scan yet",
"chip": "Idle",
"chip_tone": Tone.NEUTRAL,
"bar_mode": BarMode.IDLE,
"bar_fraction": 0.0,
"bar_text": "Waiting for a scan",
"instruction": "",
"next": "",
"can_stop": False,
}
number = f"#{state.scan_number} " if state.scan_number is not None else ""
title = f"{number}{state.display_name}"
step = hook_label(state.top_hook) if state.top_hook else ""
if state.finished:
chip, tone = _FINISHED_CHIPS.get(state.status, ("Failed", Tone.BAD))
took = format_duration(state.elapsed(now))
# where a scan that did not end normally stopped, as a step display name ("Measuring")
where = hook_label(state.hook_error or state.top_hook) if tone != Tone.OK and step else ""
next_text = f"Took {took}"
if state.lost:
# no final status: the scan server went away (e.g. a restart), so its run time is
# not known either
took = ""
next_text = "The scan server stopped while the scan ran"
detail = took or "scan server stopped"
bar_text = f"{chip} in {where} · {detail}" if where else f"{chip} · {detail}"
return {
"outcome": chip,
"where": where,
"took": took,
"title": title,
"chip": chip,
"chip_tone": tone,
"bar_mode": BarMode.DONE if tone == Tone.OK else BarMode.ERROR,
"bar_fraction": 1.0,
"bar_text": bar_text,
"instruction": "",
"next": next_text,
"can_stop": False,
}
if state.status == "paused":
chip, tone, mode = "Paused", Tone.WARN, BarMode.PAUSED
else:
chip, tone, mode = (step or "Running"), Tone.RUN, BarMode.BUSY
fraction = 0.0
total = state.progress_max or state.num_points
if state.measuring and total:
value = state.progress_value or 0
fraction = value / total
pct = int(round(fraction * 100))
left = state.remaining(now)
left_text = f" · {format_duration(left)} left" if left is not None else ""
bar_text = f"Point {int(value)} of {int(total)} · {pct}%{left_text}"
if mode != BarMode.PAUSED:
mode = BarMode.PROGRESS
elif state.has_hooks:
bar_text = f"{step or 'Running'} · {format_duration(state.hook_elapsed(now))}"
else:
bar_text = f"Running · {format_duration(state.elapsed(now))}"
instruction = state.instruction
wait = state.wait_elapsed(now)
if state.top_hook == "scan_core":
if wait is not None and wait < MEASURE_WAIT_SHOWN_AFTER_S:
wait = None # per-point waits are short; only time a device the scan is stuck on
elif state.hook and state.hook != state.top_hook:
instruction = f"[{state.hook}] {instruction}".strip()
if wait is not None:
instruction = f"{instruction or 'Waiting'} · {format_duration(wait)}"
next_text = ""
if state.has_hooks:
nxt = state.next_hook
next_text = f"Next: {hook_label(nxt)} {nxt}" if nxt else "Last step"
return {
"title": title,
"chip": chip,
"chip_tone": tone,
"bar_mode": mode,
"bar_fraction": fraction,
"bar_text": bar_text,
"instruction": instruction,
"next": next_text,
"can_stop": True,
}
class StepTimesPopup(QFrame):
"""
Hover card listing how long each hook of the scan took.
It refreshes while open, so its rows are updated in place and it never shrinks while shown;
rebuilding or resizing it on every tick makes it flicker.
"""
def __init__(self, parent: QWidget | None = None):
super().__init__(parent, Qt.WindowType.ToolTip | Qt.WindowType.FramelessWindowHint)
self.setObjectName("step_times_popup")
self._layout = QVBoxLayout(self)
self._layout.setContentsMargins(12, 10, 12, 10)
self._layout.setSpacing(6)
self._title = QLabel(self)
self._title.setFont(mono_font(0, bold=True))
self._layout.addWidget(self._title)
self._grid = QGridLayout()
self._grid.setHorizontalSpacing(10)
self._grid.setVerticalSpacing(3)
self._layout.addLayout(self._grid)
self._row_widgets: list[tuple[QLabel, _ShareBar, QLabel]] = []
self._name_styles: dict[QLabel, str] = {}
self.rows: list[tuple[str, str]] = []
self.refresh_style()
def refresh_style(self) -> None:
"""Re-read the theme colours."""
colors = theme_colors()
self.setStyleSheet(
f"#step_times_popup {{ background: {css(colors['card'])};"
f" border: 1px solid {css(colors['border'])}; border-radius: 8px; }}"
f"QLabel {{ color: {css(colors['fg'])}; text-decoration: none; }}"
)
self._name_styles.clear()
def _row(self, index: int) -> tuple[QLabel, _ShareBar, QLabel]:
while len(self._row_widgets) <= index:
row = len(self._row_widgets)
name = QLabel(self)
name.setFont(mono_font(-1))
share = _ShareBar(self)
took = QLabel(self)
took.setFont(mono_font(-1))
took.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
took.setMinimumWidth(took.fontMetrics().horizontalAdvance("0000.0 s ×000"))
self._grid.addWidget(name, row, 0)
self._grid.addWidget(share, row, 1)
self._grid.addWidget(took, row, 2)
self._row_widgets.append((name, share, took))
return self._row_widgets[index]
def set_state(self, state: ScanRunState | None) -> None:
"""Fill the card from a scan state."""
colors = theme_colors()
self.rows = []
timings = state.step_times() if state is not None and state.timings else []
if not timings:
self._title.setText("No step times yet")
else:
number = f" · #{state.scan_number}" if state.scan_number is not None else ""
self._title.setText(f"Step times{number} {format_duration(state.elapsed())}")
server_now = state.server_now() if timings and not state.finished else None
longest = max((t.duration(server_now) for t in timings), default=0) or 1
for index, timing in enumerate(timings):
name, share, took = self._row(index)
seconds = timing.duration(server_now)
name.setText((" " if timing.nested else "") + timing.hook)
if timing.status == "error":
style = f"color: {css(colors['bad'])};"
elif timing.started_at is not None:
style = f"color: {css(colors['run'])}; font-weight: 600;"
else:
style = ""
if self._name_styles.get(name) != style:
self._name_styles[name] = style
name.setStyleSheet(style)
share.set_share(seconds / longest, timing.status)
count = f" ×{timing.count}" if timing.count > 1 else ""
took.setText(f"{seconds:.1f} s{count}")
for widget in (name, share, took):
widget.setVisible(True)
self.rows.append((timing.hook, took.text()))
for name, share, took in self._row_widgets[len(timings) :]:
for widget in (name, share, took):
widget.setVisible(False)
self._fit()
def _fit(self) -> None:
"""Grow to fit the content; only shrink while hidden."""
hint = self.sizeHint()
if self.isVisible():
width = max(hint.width(), self.width())
else:
width = hint.width()
if (width, hint.height()) != (self.width(), self.height()):
right = self.geometry().right()
self.resize(width, hint.height())
if self.isVisible():
self.move(right - width + 1, self.y())
class _ShareBar(QWidget):
def __init__(self, parent: QWidget | None = None):
super().__init__(parent)
self._share = 0.02
self._status = ""
self.setFixedSize(90, 8)
def set_share(self, share: float, status: str) -> None:
"""Set the filled share (0 to 1) and repaint when it changed."""
share = max(0.02, min(1.0, share))
if abs(share - self._share) > 0.002 or status != self._status:
self._share, self._status = share, status
self.update()
def paintEvent(self, _event): # pylint: disable=invalid-name
colors = theme_colors()
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
track = colors["fg"]
track.setAlphaF(0.08)
painter.setBrush(track)
painter.drawRoundedRect(QRectF(0, 0, self.width(), self.height()), 3, 3)
painter.setBrush(colors["bad"] if self._status == "error" else colors["primary"])
painter.drawRoundedRect(QRectF(0, 0, self.width() * self._share, self.height()), 3, 3)
painter.end()
class StepTimesLabel(QLabel):
"""A "Step times" label that shows the StepTimesPopup while hovered or clicked."""
def __init__(self, parent: QWidget | None = None):
super().__init__("Step times", parent)
self.setCursor(Qt.CursorShape.WhatsThisCursor)
self.setToolTip("")
self.popup = StepTimesPopup(self)
self._state: ScanRunState | None = None
def paintEvent(self, event): # pylint: disable=invalid-name
"""Draw the text, then a dotted underline (style sheets cannot style an underline)."""
super().paintEvent(event)
metrics = self.fontMetrics()
width = min(metrics.horizontalAdvance(self.text()), self.contentsRect().width())
rect = self.contentsRect()
if self.alignment() & Qt.AlignmentFlag.AlignRight:
left = rect.right() - width
elif self.alignment() & Qt.AlignmentFlag.AlignHCenter:
left = rect.left() + (rect.width() - width) // 2
else:
left = rect.left()
text_top = rect.top() + (rect.height() - metrics.height()) // 2
y = min(rect.bottom(), text_top + metrics.ascent() + 2)
painter = QPainter(self)
painter.setPen(QPen(theme_colors()["muted"], 1, Qt.PenStyle.DotLine))
painter.drawLine(left, y, left + width, y)
painter.end()
def set_state(self, state: ScanRunState | None) -> None:
"""Remember the state and refresh the card if it is open."""
self._state = state
if self.popup.isVisible():
self.popup.set_state(state)
def show_popup(self) -> None:
"""Open the card next to the label."""
if self.popup.isVisible():
return
self.popup.set_state(self._state)
anchor = self.mapToGlobal(QPoint(self.width(), self.height() + 4))
self.popup.move(anchor.x() - self.popup.width(), anchor.y())
self.popup.show()
def refresh_style(self) -> None:
"""Re-read the theme colours of the card."""
self.popup.refresh_style()
def enterEvent(self, event): # pylint: disable=invalid-name
super().enterEvent(event)
self.show_popup()
def leaveEvent(self, event): # pylint: disable=invalid-name
super().leaveEvent(event)
self.popup.hide()
def mousePressEvent(self, event): # pylint: disable=invalid-name
if self.popup.isVisible():
self.popup.hide()
else:
self.show_popup()
super().mousePressEvent(event)
class ScanProgressBar(BECWidget, QWidget):
"""
Widget to display a progress bar that is hooked up to the scan progress of a scan.
If you want to manually set the progress, it is recommended to use the BECProgressbar or QProgressbar directly.
Live progress of the running scan.
Shows the current step with busy stripes and a step timer, real progress while measuring,
the current device instruction with its wait time, the next step, and a Stop for the
whole scan. Hover "Step times" to see how long each step took.
"""
ICON_NAME = "timelapse"
PLUGIN = True
progress_started = Signal()
progress_finished = Signal()
ICON_NAME = "av_timer"
RPC = True
state_changed = Signal(object)
# share of the bar row the bar label is sized for; the Stop button takes at most
# STOP_ROW_MAX of the row and grows to at most STOP_SCALE_MAX of its normal size
STOP_ROW_SHARE = 0.8
STOP_ROW_MAX = 0.22
STOP_SCALE_MAX = 1.5
# space between the bar and the Stop button, normal and next to a stretched bar
BAR_ROW_SPACING = 8
BAR_ROW_SPACING_STRETCHED = 12
def __init__(
self,
parent=None,
parent: QWidget | None = None,
client=None,
config=None,
gui_id=None,
one_line_design=False,
enable_dynamic_stylesheet: bool = True,
gui_id: str | None = None,
show_details: bool = True,
fill_height: bool = True,
show_stop_button: bool = True,
**kwargs,
):
super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs)
self.get_bec_shortcuts()
ui_file = os.path.join(
os.path.dirname(__file__),
"scan_progressbar_one_line.ui" if one_line_design else "scan_progressbar.ui",
self._show_details = show_details
self._fill_height = fill_height
self._show_stop_button = show_stop_button
self._confirm_before_stop = False
self._pending_action = StopAction.ABORT
self._state: ScanRunState | None = None
self._details_key: tuple | None = None
self._build_ui()
self._confirm_timer = QTimer(self)
self._confirm_timer.setSingleShot(True)
self._confirm_timer.setInterval(6000)
self._confirm_timer.timeout.connect(self.cancel_stop)
self.tracker = ScanHookTracker(self.client, self.bec_dispatcher, parent=self)
self.tracker.changed.connect(self._on_state)
self.tracker.tick.connect(self._refresh_live)
self.tracker.start()
self._render()
################################################################################
# UI
################################################################################
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 8, 10, 8)
layout.setSpacing(6)
# the title row holds the title and the scan parameters, also as a tooltip on it and the
# metadata chips; the elided title shows its own full text when cut
self.header_row = QWidget(self)
header = QHBoxLayout(self.header_row)
header.setContentsMargins(0, 0, 0, 0)
header.setSpacing(8)
self.title_label = ElidedLabel(parent=self.header_row)
self.title_label.setFont(mono_font(0, bold=True))
self.title_label.setMinimumHeight(self.title_label.fontMetrics().height())
# the scan arguments follow the title and take what is left, elided
self.args_label = ElidedLabel(parent=self.header_row)
self.args_label.setFont(mono_font(-1))
self.state_chip = Chip("Idle", Tone.NEUTRAL, self.header_row)
header.addWidget(self.title_label, 1)
header.addWidget(self.args_label, 1)
header.addWidget(self.state_chip)
layout.addWidget(self.header_row)
self.chips = FlowLayoutWidget(self, horizontal_spacing=4, vertical_spacing=4)
layout.addWidget(self.chips)
bar_row = QHBoxLayout()
bar_row.setSpacing(self.BAR_ROW_SPACING)
self.bar = StageBar(self, height=26)
self.stop_button = StopButton(
parent=self, client=self.client, rpc_exposed=False, rpc_passthrough_children=False
)
self.ui = UILoader(self).loader(ui_file)
self.layout = QVBoxLayout(self)
self.layout.setSpacing(0)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.ui)
self.setLayout(self.layout)
self.progressbar = self.ui.progressbar
self.progressbar.enable_dynamic_stylesheet = enable_dynamic_stylesheet
self._show_elapsed_time = self.ui.elapsed_time_label.isVisible()
self._show_remaining_time = self.ui.remaining_time_label.isVisible()
self._show_source_label = self.ui.source_label.isVisible()
self.stop_button.action_handler = self._on_stop_action
self._stop_base_size = QFontInfo(self.stop_button.button.font()).pixelSize()
self._stop_key: tuple | None = None
self.bar.sizing_changed.connect(self._style_stop_button)
bar_row.addWidget(self.bar, 1)
bar_row.addWidget(self.stop_button)
self.stop_button.setVisible(self._show_stop_button)
layout.addLayout(bar_row)
self._layout = layout
self._bar_row = bar_row
self._apply_fill_height()
self.progress_tracker = BECProgressTracker(self.bec_dispatcher, parent=self)
self.progress_tracker.progress_started.connect(self._on_progress_started)
self.progress_tracker.progress_updated.connect(self._on_progress_snapshot)
self.progress_tracker.progress_finished.connect(
lambda _snapshot: self.progress_finished.emit()
self.confirm_frame = QFrame(self)
self.confirm_frame.setObjectName("scan_progress_confirm")
confirm = QHBoxLayout(self.confirm_frame)
confirm.setContentsMargins(8, 4, 4, 4)
confirm.setSpacing(6)
self.confirm_label = ElidedLabel(parent=self.confirm_frame)
self.confirm_label.setMinimumHeight(self.confirm_label.fontMetrics().height())
self.confirm_stop_button = QPushButton("Stop scan", self.confirm_frame)
self.confirm_stop_button.setProperty("variant", "danger")
self.confirm_stop_button.clicked.connect(self.stop_scan)
self.confirm_cancel_button = QPushButton("Cancel", self.confirm_frame)
self.confirm_cancel_button.clicked.connect(self.cancel_stop)
confirm.addWidget(self.confirm_label, 1)
confirm.addWidget(self.confirm_stop_button)
confirm.addWidget(self.confirm_cancel_button)
self.confirm_frame.setVisible(False)
layout.addWidget(self.confirm_frame)
self.instruction_label = ElidedLabel(parent=self)
self.instruction_label.setFont(mono_font(-1))
self.instruction_label.setMinimumHeight(self.instruction_label.fontMetrics().height())
layout.addWidget(self.instruction_label)
self.footer = QFrame(self)
self.footer.setObjectName("scan_progress_footer")
footer = QHBoxLayout(self.footer)
footer.setContentsMargins(0, 6, 0, 0)
footer.setSpacing(8)
self.next_label = ElidedLabel(parent=self.footer)
self.next_label.setMinimumHeight(self.next_label.fontMetrics().height())
self.step_times = StepTimesLabel(self.footer)
footer.addWidget(self.next_label, 1)
footer.addWidget(self.step_times)
layout.addWidget(self.footer)
self._apply_styles()
def _apply_styles(self) -> None:
colors = theme_colors()
muted = css(colors["muted"])
self.args_label.setStyleSheet(f"color: {muted};")
self.instruction_label.setStyleSheet(f"color: {muted};")
self.next_label.setStyleSheet(f"color: {muted};")
self.step_times.setStyleSheet(f"color: {muted};")
self.footer.setStyleSheet(
f"#scan_progress_footer {{ border-top: 1px solid {css(colors['border'], 0.6)}; }}"
)
self.progress_tracker.start()
def update_source_label(self):
scan_number = self.progress_tracker.scan_number
scan_text = f"Scan {scan_number}" if scan_number is not None else "Scan"
if self.ui.source_label.text() == scan_text:
return
logger.info(f"Set progress source to {scan_text}")
self.ui.source_label.setText(scan_text)
def _on_progress_started(self, _snapshot: ProgressSnapshot):
if self.progress_tracker.task is not None:
self.progress_tracker.task.timer.timeout.connect(self.update_labels)
self.progress_started.emit()
def _on_progress_snapshot(self, snapshot: ProgressSnapshot):
self.update_labels()
if snapshot.is_new_scan and self.progress_tracker.task is None:
self.ui.elapsed_time_label.setText("00:00:00")
self.ui.remaining_time_label.setText("00:00:00")
self.update_source_label()
self.progressbar.set_maximum(snapshot.max_value)
self.progressbar.set_value(snapshot.value)
self.progressbar.state = BEC_STATUS_TO_PROGRESS_STATE.get(
snapshot.status.lower(), ProgressState.NORMAL
self._style_stop_button(force=True)
self.confirm_frame.setStyleSheet(
f"#scan_progress_confirm {{ background: {css(colors['bad'], 0.10)};"
f" border: 1px solid {css(colors['bad'], 0.45)}; border-radius: 6px; }}"
)
self.state_chip.refresh_style()
@SafeProperty(bool)
def show_elapsed_time(self):
return self._show_elapsed_time
@show_elapsed_time.setter
def show_elapsed_time(self, value):
self._show_elapsed_time = value
self.ui.elapsed_time_label.setVisible(value)
if hasattr(self.ui, "dash"):
self.ui.dash.setVisible(value)
@SafeProperty(bool)
def show_remaining_time(self):
return self._show_remaining_time
@show_remaining_time.setter
def show_remaining_time(self, value):
self._show_remaining_time = value
self.ui.remaining_time_label.setVisible(value)
if hasattr(self.ui, "dash"):
self.ui.dash.setVisible(value)
@SafeProperty(bool)
def show_source_label(self):
return self._show_source_label
@show_source_label.setter
def show_source_label(self, value):
self._show_source_label = value
self.ui.source_label.setVisible(value)
def update_labels(self):
@SafeSlot()
def _style_stop_button(self, force: bool = False) -> None:
"""
Update the labels based on the progress task.
"""
task = self.progress_tracker.task
if task is None:
return
Size the Stop button with the bar: on a stretched bar it takes the bar's height and its
text grows like the bar label; unstretched it keeps its normal look at the bar's height.
self.ui.elapsed_time_label.setText(task.time_elapsed)
self.ui.remaining_time_label.setText(task.time_remaining)
The scale comes from the bar height and the width of the whole bar row (bar and button),
not from the bar's own width: the button's width changes the bar's width, and following
that would make the two resize each other in a loop.
"""
stretched = self.bar.stretched
row_width = self._bar_row.geometry().width() or self.width()
scale = self.bar.label_scale(self.bar.height(), row_width * self.STOP_ROW_SHARE)
bar_height = self.bar.get_bar_height()
key = (scale, stretched, row_width, bar_height)
if key == self._stop_key and not force:
return
self._stop_key = key
# the button grows more gently than the label and stays a small part of the row
stop = self.stop_button
stop.set_stretch(stretched)
stop.compact_emergency = stretched
self._bar_row.setSpacing(
self.BAR_ROW_SPACING_STRETCHED if stretched else self.BAR_ROW_SPACING
)
target = min(self.STOP_SCALE_MAX, 1.0 + (scale - 1.0) * 0.5)
if not stretched:
# both parts take the bar's exact height, so their outlines line up with the bar
self._size_stop(1.0 if target <= 1.0 else target, height=bar_height)
stop.setMinimumWidth(0)
stop.setMaximumWidth(16777215)
self.bar.scale_width = row_width * self.STOP_ROW_SHARE
return
# fit to the box: the largest scale whose widest label ("Stop" or "E-Stop") fits the
# cap, measured by Qt with the real fonts; at the base scale it takes what it needs
cap = int(row_width * self.STOP_ROW_MAX)
candidate = target
while True:
self._size_stop(candidate)
needed = stop.required_width()
if needed <= cap or candidate <= 1.0:
break
candidate = max(1.0, candidate - 0.1)
width = min(cap, needed) if needed <= cap else needed
stop.setFixedWidth(width)
# the bar label is sized for the room the bar really has next to the button
spacing = self._bar_row.spacing()
self.bar.scale_width = max(80, row_width - width - spacing)
self.bar.update()
def _size_stop(self, stop_scale: float, height: int | None = None) -> None:
self.stop_button.set_size(
height=height,
font_px=self._stop_base_size * stop_scale if stop_scale > 1.0 else None,
radius=6 if stop_scale <= 1.0 else min(10, round(6 * stop_scale)),
pad=round(10 * stop_scale),
)
def resizeEvent(self, event): # pylint: disable=invalid-name
super().resizeEvent(event)
self._style_stop_button()
def apply_theme(self, theme: str):
"""Restyle after a theme change."""
self._apply_styles()
self.step_times.refresh_style()
self._details_key = None
self._render()
################################################################################
# Properties
################################################################################
@SafeProperty(bool)
def show_details(self) -> bool:
"""
Show the scan's user metadata as chips under the title (e.g. "sample LaB6"). Scans
without user metadata show no chips either way; the scan arguments always follow the
title.
"""
return self._show_details
@show_details.setter
def show_details(self, show: bool) -> None:
self._show_details = show
self._details_key = None
self._render()
@SafeProperty(int)
def bar_height(self) -> int:
"""Height of the progress bar in pixels, for large screens."""
return self.bar.get_bar_height()
@bar_height.setter
def bar_height(self, height: int) -> None:
self.bar.set_bar_height(height)
self._style_stop_button()
@SafeProperty(bool)
def fill_height(self) -> bool:
"""Let the bar take all spare vertical space, with its label scaled to the bar."""
return self._fill_height
@fill_height.setter
def fill_height(self, fill: bool) -> None:
self._fill_height = fill
self._apply_fill_height()
def _apply_fill_height(self) -> None:
self.bar.set_fill_height(self._fill_height)
self._layout.setStretchFactor(self._bar_row, 1 if self._fill_height else 0)
@SafeProperty(bool)
def show_stop_button(self) -> bool:
"""Show the Stop button next to the bar; hidden, the bar takes its width."""
return self._show_stop_button
@show_stop_button.setter
def show_stop_button(self, show: bool) -> None:
self._show_stop_button = show
if not show:
self.cancel_stop()
self.stop_button.setVisible(show)
@property
def state(self) -> ScanRunState | None:
"""The scan state currently shown."""
return self._state
################################################################################
# Rendering
################################################################################
@SafeSlot(object)
def _on_state(self, state: ScanRunState | None) -> None:
if self._state is not state:
self.cancel_stop()
self.bar.reset_reserved()
self._state = state
self._render()
self.state_changed.emit(state)
@SafeSlot()
def _refresh_live(self) -> None:
self._render()
def _render(self) -> None:
info = describe_state(self._state)
# as wide as its text, so the arguments start right after it
self.title_label.setMaximumWidth(
self.title_label.fontMetrics().horizontalAdvance(info["title"]) + 2
)
self.title_label.setText(info["title"])
self.state_chip.setText(info["chip"])
self.state_chip.set_tone(info["chip_tone"])
self.bar.set_state(info["bar_mode"], info["bar_fraction"], info["bar_text"])
self.stop_button.setEnabled(info["can_stop"])
self.stop_button.request_id = self._state.rid if self._state is not None else None
if not info["can_stop"] and self.confirm_frame.isVisible():
self.cancel_stop()
self.instruction_label.setText(info["instruction"])
self.next_label.setText(info["next"])
self.step_times.setVisible(bool(self._state and self._state.timings))
self.step_times.set_state(self._state)
# keep the footer while a scan is shown so the widget does not change height mid-scan
self.footer.setVisible(self._state is not None)
self._render_details()
def _render_details(self) -> None:
state = self._state
args = ""
if state is not None:
names = scan_bundle_names(getattr(self.client, "scans", None), state.scan_name)
args = request_inputs_summary(state.request_inputs, names)
self.args_label.setText(args)
if state is not None and state.scan_name and state.display_name != state.scan_name:
# a scan with its own name: the scan type is still one hover away
args = f"{state.scan_name}: {args}" if args else state.scan_name
items = metadata_items(state.user_metadata) if state else []
key = (self._show_details, args, tuple(items))
if key == self._details_key:
return
self._details_key = key
self.header_row.setToolTip(args)
self.chips.setToolTip(args)
flow = self.chips.flow_layout
while flow.count():
item = flow.takeAt(0)
if item.widget() is not None:
item.widget().deleteLater()
for k, v in items:
flow.addWidget(MetaChip(k, v, self.chips))
self.chips.setVisible(self._show_details and bool(items))
################################################################################
# Stop
################################################################################
def _on_stop_action(self, action: StopAction) -> bool:
"""
StopButton hook: with confirm_before_stop, abort and finish ask first. Halt never asks.
Returns:
bool: True when the confirmation row took over the action.
"""
if self._confirm_before_stop and action in (StopAction.ABORT, StopAction.FINISH):
self.ask_stop(action)
return True
return False
@SafeSlot()
def ask_stop(self, action: StopAction | str = StopAction.ABORT) -> None:
"""Ask for confirmation before stopping (abort) or finishing the scan."""
if not self._show_stop_button or self._state is None or self._state.finished:
return
info = describe_state(self._state)
action = StopAction(action)
self._pending_action = action
if action == StopAction.FINISH:
self.confirm_label.setText(f"Finish scan {info['title']} now?")
self.confirm_stop_button.setText("Finish now")
else:
self.confirm_label.setText(f"Stop scan {info['title']}?")
self.confirm_stop_button.setText("Stop scan")
self.confirm_frame.setVisible(True)
self.stop_button.setVisible(False)
self._confirm_timer.start()
@SafeSlot()
def cancel_stop(self) -> None:
"""Close the stop confirmation without stopping."""
self._confirm_timer.stop()
self.confirm_frame.setVisible(False)
self.stop_button.setVisible(self._show_stop_button)
@SafeSlot()
def stop_scan(self) -> None:
"""Run the confirmed action (abort by default) on the scan shown in the widget."""
state = self._state
action = self._pending_action
self.cancel_stop()
if state is None or state.finished:
return
logger.info(f"{action} scan {state.scan_number} ({state.rid})")
self.stop_button.request_id = state.rid
self.stop_button.perform(action)
if action == StopAction.ABORT:
self.state_chip.setText("Stopping…")
self.state_chip.set_tone(Tone.BAD)
@SafeProperty(bool)
def confirm_before_stop(self) -> bool:
"""Ask in a confirmation row before aborting or finishing (off: act at once)."""
return self._confirm_before_stop
@confirm_before_stop.setter
def confirm_before_stop(self, confirm: bool) -> None:
self._confirm_before_stop = confirm
if not confirm:
self.cancel_stop()
def cleanup(self):
self.progress_tracker.cleanup()
self.progressbar.close()
self.progressbar.deleteLater()
"""Stop the timers and disconnect the tracker."""
self._confirm_timer.stop()
self.tracker.cleanup()
self.bar.cleanup()
self.step_times.popup.close()
super().cleanup()
if __name__ == "__main__": # pragma: no cover
import sys
from qtpy.QtWidgets import QApplication
bec_logger.disabled_modules = ["bec_lib"]
app = QApplication([])
from bec_widgets.utils.colors import apply_theme
app = QApplication(sys.argv)
apply_theme("dark")
widget = ScanProgressBar()
widget.resize(460, 220)
widget.show()
app.exec_()
sys.exit(app.exec_())
@@ -1,141 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>211</width>
<height>60</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>60</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>1</number>
</property>
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="source_layout">
<item>
<widget class="QLabel" name="source_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>Scan</string>
</property>
</widget>
</item>
<item>
<spacer name="source_spacer">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="BECProgressBar" name="progressbar">
<property name="padding_left_right" stdset="0">
<double>2.000000000000000</double>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="timer_layout">
<item>
<widget class="QLabel" name="remaining_time_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>0:00:00</string>
</property>
</widget>
</item>
<item>
<spacer name="timer_spacer">
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="elapsed_time_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>0:00:00</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>BECProgressBar</class>
<extends>QWidget</extends>
<header>bec_progress_bar</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,124 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>328</width>
<height>24</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>24</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>24</height>
</size>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,1,0">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QLabel" name="source_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>Scan</string>
</property>
</widget>
</item>
<item>
<widget class="BECProgressBar" name="progressbar">
<property name="minimumSize">
<size>
<width>30</width>
<height>0</height>
</size>
</property>
<property name="padding_left_right" stdset="0">
<double>5.000000000000000</double>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="remaining_time_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>0:00:00</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="dash">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignmentFlag::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="elapsed_time_label">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>0:00:00</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>BECProgressBar</class>
<extends>QWidget</extends>
<header>bec_progress_bar</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -0,0 +1,273 @@
"""
Small visual building blocks of the scan widgets: labels, chips and the stage bar.
"""
from __future__ import annotations
from typing import Any
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QLabel, QSizePolicy, QWidget
from bec_widgets.utils.theme_utils import css, theme_colors
from bec_widgets.widgets.progress.stage_bar import Chip, Tone
# Keyword arguments that every scan request carries and that say nothing about the scan itself.
_HIDDEN_KWARGS = {
"system_config",
"user_metadata",
"scan_queue",
"metadata",
"file_suffix",
"file_directory",
"monitored",
"readout_priority",
"optim_trajectory",
}
def scan_display_name(
user_metadata: dict | None, scan_type: str | None, fallback: str = "scan"
) -> str:
"""
The name a scan is shown with everywhere: the scan_name the user gave in its metadata
("My Scan"), else the scan type ("line_scan").
Args:
user_metadata(dict): The scan's user metadata.
scan_type(str): The scan type, e.g. "line_scan".
fallback(str): Shown when neither is known.
"""
name = (user_metadata or {}).get("scan_name")
return str(name) if name else (scan_type or fallback)
def format_value(value: Any) -> str:
"""Format one argument or metadata value compactly."""
if isinstance(value, float):
return f"{value:.4g}"
if isinstance(value, (list, tuple)):
return " → ".join(format_value(v) for v in value) if len(value) <= 3 else f"[{len(value)}]"
return str(value)
def _kwargs_parts(kwargs: dict) -> list[str]:
parts = []
for key, value in (kwargs or {}).items():
if key in _HIDDEN_KWARGS or value is None or isinstance(value, dict) or value is False:
continue
parts.append(key if value is True else f"{key} {format_value(value)}")
return parts
def scan_bundle_names(scans: Any, scan_type: str | None) -> list[str]:
"""
The names of the values of one argument bundle of a scan, after its device, as the scan
server publishes them, e.g. ["start", "stop", "steps"] for a grid scan.
Args:
scans(Any): The client's scans object.
scan_type(str): The scan type, e.g. "grid_scan".
Returns:
list[str]: The names; empty for a scan without bundles or when the scan is not known.
"""
info = getattr(getattr(scans, scan_type or "", None), "scan_info", None)
arg_input = info.get("arg_input") if isinstance(info, dict) else None
return list(arg_input)[1:] if isinstance(arg_input, dict) else []
def _bundle_values(values: Any, names: list[str] | None) -> str:
"""
Format the values of one argument bundle: start → stop for a range, any other value with its
name ("-5 → 5 steps 10"). Without names only a pair is taken for a range.
"""
values = list(values) if isinstance(values, (list, tuple)) else [values]
if not names or len(names) != len(values):
separator = " → " if len(values) == 2 else " "
return separator.join(format_value(v) for v in values)
named = dict(zip(names, values))
parts = []
if "start" in named and "stop" in named:
parts.append(f"{format_value(named.pop('start'))} → {format_value(named.pop('stop'))}")
elif len(named) == 1:
return format_value(values[0]) # the one value of a move or a list of positions
parts.extend(f"{name} {format_value(value)}" for name, value in named.items())
return " ".join(parts)
def _rpc_value(value: Any) -> str:
return f"{value:.4g}" if isinstance(value, float) else repr(value)
def rpc_call(kwargs: dict | None) -> str:
"""
The call of a device_rpc request as it reads in code, e.g. "samx.set(5, wait=True)".
Args:
kwargs(dict): The request's keyword arguments, with device, func and its arguments.
Returns:
str: The call; empty when this is not a device RPC.
"""
kwargs = kwargs or {}
device, func = kwargs.get("device"), kwargs.get("func")
if not device or not func:
return ""
call_args = [_rpc_value(arg) for arg in kwargs.get("func_args") or []]
func_kwargs = kwargs.get("func_kwargs") or {}
call_args += [f"{key}={_rpc_value(value)}" for key, value in func_kwargs.items()]
return f"{device}.{func}({', '.join(call_args)})"
def args_summary(parameter: dict | None, names: list[str] | None = None) -> str:
"""
Summarise the arguments of a scan request ("samx -5 → 5 · steps 50 · exp_time 0.1").
Args:
parameter(dict): ScanQueueMessage.parameter, with "args" and "kwargs".
names(list[str]): The names of a bundle's values, from scan_bundle_names.
"""
parameter = parameter or {}
call = rpc_call(parameter.get("kwargs"))
if call:
return call
parts: list[str] = []
args = parameter.get("args")
if isinstance(args, dict):
for device, values in args.items():
parts.append(f"{device} {_bundle_values(values, names)}".strip())
elif isinstance(args, (list, tuple)):
parts.extend(format_value(a) for a in args)
parts.extend(_kwargs_parts(parameter.get("kwargs", {})))
return " · ".join(p for p in parts if p)
def args_items(parameter: dict | None, names: list[str] | None = None) -> list[tuple[str, str]]:
"""
Every argument of a scan request as its own (name, value) row, for detail views.
Args:
parameter(dict): ScanQueueMessage.parameter, with "args" and "kwargs".
names(list[str]): The names of a bundle's values, from scan_bundle_names.
"""
parameter = parameter or {}
call = rpc_call(parameter.get("kwargs"))
if call:
return [("call", call)]
items: list[tuple[str, str]] = []
args = parameter.get("args")
if isinstance(args, dict):
for device, values in args.items():
items.append((str(device), _bundle_values(values, names)))
elif isinstance(args, (list, tuple)) and args:
items.append(("args", " ".join(format_value(a) for a in args)))
for key, value in (parameter.get("kwargs") or {}).items():
if key in _HIDDEN_KWARGS or value is None or isinstance(value, dict):
continue
items.append((str(key), format_value(value)))
return items
def request_inputs_summary(request_inputs: dict | None, names: list[str] | None = None) -> str:
"""
Summarise ScanStatusMessage.request_inputs the same way as args_summary.
Args:
request_inputs(dict): The request inputs, with "arg_bundle", "inputs" and "kwargs".
names(list[str]): The names of a bundle's values, from scan_bundle_names.
"""
request_inputs = request_inputs or {}
inputs = request_inputs.get("inputs") or {}
call = rpc_call({**inputs, **(request_inputs.get("kwargs") or {})})
if call:
return call
parts: list[str] = []
bundle = list(request_inputs.get("arg_bundle") or [])
if bundle and names and len(bundle) % (len(names) + 1) == 0:
size = len(names) + 1
for index in range(0, len(bundle), size):
device, values = bundle[index], bundle[index + 1 : index + size]
parts.append(f"{device} {_bundle_values(values, names)}")
elif bundle:
parts.append(" ".join(format_value(a) for a in bundle))
for key, value in inputs.items():
parts.append(f"{key} {format_value(value)}")
parts.extend(_kwargs_parts(request_inputs.get("kwargs", {})))
return " · ".join(p for p in parts if p)
def metadata_items(user_metadata: dict | None) -> list[tuple[str, str]]:
"""Return user metadata as (key, value) pairs worth showing, scan_name excluded."""
items = []
for key, value in (user_metadata or {}).items():
if key == "scan_name" or str(key).startswith("_") or value in (None, "", {}, []):
continue
items.append((str(key), format_value(value)))
return items
class ElidedLabel(QLabel):
"""
A single-line label that elides its text instead of growing or clipping. When the text is
cut, its tooltip shows the full text; otherwise the tooltip is left free for the parent.
Setting the same text again does nothing, so a widget that re-renders several times a second
neither re-elides nor touches the tooltip, and an open tooltip does not flicker.
"""
def __init__(self, text: str = "", parent: QWidget | None = None):
super().__init__(parent)
self._full = ""
self._tooltip = ""
self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed)
self.setMinimumWidth(10)
self._elide()
self.setText(text)
def setText(self, text: str) -> None: # pylint: disable=invalid-name
"""Set the full text; the shown text is elided to fit."""
text = text or ""
if text == self._full:
return
self._full = text
self._elide()
def full_text(self) -> str:
"""The text before eliding."""
return self._full
def resizeEvent(self, event): # pylint: disable=invalid-name
super().resizeEvent(event)
self._elide()
def _elide(self) -> None:
width = max(10, self.width())
shown = self.fontMetrics().elidedText(self._full, Qt.TextElideMode.ElideRight, width)
if shown != super().text():
super().setText(shown)
tooltip = self._full if shown != self._full else ""
if tooltip != self._tooltip:
self._tooltip = tooltip
self.setToolTip(tooltip)
class MetaChip(Chip):
"""A metadata chip showing a muted key and its value."""
def __init__(self, key: str, value: str, parent: QWidget | None = None):
self._key = key
self._value = value
super().__init__("", Tone.NEUTRAL, parent)
self.setToolTip(f"{key}: {value}")
self._update_text()
def _update_text(self) -> None:
muted = css(theme_colors()["muted"])
value = self._value if len(self._value) <= 28 else f"{self._value[:27]}…"
self.setText(f"<span style='color:{muted}'>{self._key}</span>&nbsp;{value}")
def refresh_style(self) -> None:
super().refresh_style()
if hasattr(self, "_key"):
self._update_text()
+2 -2
View File
@@ -12,8 +12,8 @@ dependencies = [
"PyJWT~=2.9",
"PySide6==6.11.1",
"PySide6-QtAds==5.0.0",
"bec_ipython_client>=4.0", # needed for jupyter console
"bec_lib>=4.0",
"bec_ipython_client>=4.5", # needed for jupyter console
"bec_lib>=4.5",
"bec_qthemes~=1.0, >=1.3.7",
"black>=26,<27", # needed for bw-generate-cli
"copier~=9.7",
+2 -2
View File
@@ -74,8 +74,8 @@ def test_available_widgets(qtbot, connected_client_gui_obj):
"""This test checks that all widgets that are available via gui.available_widgets can be created and removed."""
gui = connected_client_gui_obj
dock_area = gui.bec
# Number of top level widgets, should be 4
top_level_widgets_count = 6
# Only the dock area and the launcher; the status bar pills register no RPC widgets
top_level_widgets_count = 2
assert len(gui._server_registry) == top_level_widgets_count
names = set(list(gui._server_registry.keys()))
# Number of widgets with parent_id == None, should be 2
+23
View File
@@ -399,3 +399,26 @@ def test_guided_tour_can_start_and_stop(app_with_spies, qtbot):
# Check that tour is stopped
assert not app.guided_tour._active
def test_status_pill_opens_its_widget_in_the_dock_area_view(
qtbot, mocked_client, monkeypatch, tmp_path
):
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar
monkeypatch.setenv("BECWIDGETS_PROFILE_DIR", str(tmp_path))
app = create_widget(qtbot, BECMainApp, client=mocked_client)
dock_area = app.dock_area.dock_area
assert app.status_dock_area() is dock_area
item = app._scan_status_item
item._prepare_card()
assert not item.card.hint.isHidden()
switched = []
monkeypatch.setattr(app, "set_current", lambda view_id: switched.append(view_id))
before = [w for w in dock_area.widget_list() if isinstance(w, ScanProgressBar)]
qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton)
after = [w for w in dock_area.widget_list() if isinstance(w, ScanProgressBar)]
assert len(after) == len(before) + 1
assert switched == ["dock_area"]
qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton)
assert [w for w in dock_area.widget_list() if isinstance(w, ScanProgressBar)] == after
+33 -84
View File
@@ -4,17 +4,14 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, PropertyMock, patch
import pytest
from qtpy.QtCore import QEvent, QPoint, QPointF, QSettings, Qt
from qtpy.QtGui import QEnterEvent, QIcon
from qtpy.QtCore import QEvent, QPoint, QSettings, Qt
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QApplication, QFrame, QLabel, QMessageBox
from bec_widgets.applications.companion_app import GUIServer
from bec_widgets.tests.client_mocks import mocked_client
from bec_widgets.widgets.containers.dock_area.profile_utils import SETTINGS_KEYS
from bec_widgets.widgets.containers.main_window.addons.hover_widget import (
HoverWidget,
WidgetTooltip,
)
from bec_widgets.widgets.containers.main_window.addons.hover_widget import WidgetTooltip
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin
from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow
@@ -160,11 +157,11 @@ def test_show_launcher_creates_launcher_when_missing(bec_main_window):
def test_hidden_scan_progress_parent_blocks_children_namespace(bec_main_window):
hidden_progress = bec_main_window._scan_progress_bar_full
nested_progress = hidden_progress.progressbar
item = bec_main_window._scan_status_item
hidden_progress = item.card.progress
assert item.rpc_exposed is False
assert hidden_progress.rpc_exposed is False
assert nested_progress.parent_id == hidden_progress.gui_id
def test_experimental_features_menu_action_persists_flag(
@@ -338,19 +335,6 @@ def test_bec_weblinks(monkeypatch):
# Tests for hover widget and tooltip behaviour
def test_hover_widget_tooltip(qtbot):
"""
After a HoverWidget is closed, its WidgetTooltip must be gone.
"""
simple = QLabel("Hover me")
full = QLabel("Full details")
hover = create_widget(qtbot, HoverWidget, simple=simple, full=full)
assert hover._simple is simple
assert hover._full is full
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
@@ -396,91 +380,56 @@ def test_widget_tooltip_show_and_hide(qtbot):
assert not tooltip.isVisible()
def test_hover_widget_mouse_events(qtbot):
"""
Verify that HoverWidget responds correctly to Enter, MouseMove, and Leave
events, keeping the tooltip visible only while the pointer is inside.
"""
simple = QLabel("Hover‑target")
full = QLabel("Full‑view")
hover = create_widget(qtbot, HoverWidget, simple=simple, full=full)
local = QPointF(hover.rect().center()) # inside widget
scene = QPointF(hover.mapTo(hover.window(), local.toPoint()))
global_ = QPointF(hover.mapToGlobal(local.toPoint()))
enter_event = QEnterEvent(local, scene, global_)
hover.enterEvent(event=enter_event)
qtbot.wait(200)
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)
second = StatusPillItem(
bec_main_window,
client=bec_main_window.client,
settings=lambda: QSettings(str(tmp_path / "second.ini"), QSettings.Format.IniFormat),
settings_prefix="second_pill",
card_content=QLabel("details"),
)
second.apply_sizes()
holder = bec_main_window.add_status_item(second)
items = [item for item, _ in bec_main_window._status_items]
assert items == [first, second]
assert items == [bec_main_window._scan_status_item, second]
scan_holder = bec_main_window._scan_progress_bar_with_separator
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()
qtbot.waitUntil(
lambda: holder.width() == holder.sizeHint().width()
and scan_holder.width() == scan_holder.sizeHint().width(),
timeout=2000,
)
width = 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
second.set_width_mode("fill") # stays in place with its stretch
qtbot.waitUntil(lambda: holder.width() > width, timeout=2000)
assert holder.isVisible() and holder.x() > first_holder.x()
assert first_holder.width() == first_width
assert holder.isVisible() and holder.x() > scan_holder.x()
# the scan pill takes none of the room: it keeps its own width, whatever it shows meanwhile
qtbot.waitUntil(lambda: scan_holder.width() == scan_holder.sizeHint().width(), timeout=2000)
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
def test_open_in_dock_area_adds_one_dock_then_raises_it(bec_main_window, qtbot):
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
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar
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 = bec_main_window._scan_status_item
assert item.DOCK_WIDGET == "ScanProgressBar"
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
assert bec_main_window.open_in_dock_area("ScanProgressBar") is None
dock_area = BECDockArea(parent=bec_main_window, client=bec_main_window.client)
bec_main_window.setCentralWidget(dock_area)
@@ -488,7 +437,7 @@ def test_open_in_dock_area_adds_one_dock_then_raises_it(bec_main_window, qtbot,
assert not item.card.hint.isHidden()
def docked():
return [w for w in dock_area.widget_list() if isinstance(w, BECQueue)]
return [w for w in dock_area.widget_list() if isinstance(w, ScanProgressBar)]
with qtbot.waitSignal(item.dock_requested):
qtbot.mouseDClick(item.pill, Qt.MouseButton.LeftButton)
@@ -497,4 +446,4 @@ def test_open_in_dock_area_adds_one_dock_then_raises_it(bec_main_window, qtbot,
# 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
assert bec_main_window.open_in_dock_area("ScanProgressBar") is first
File diff suppressed because it is too large. Load diff
+470
View File
@@ -0,0 +1,470 @@
from unittest import mock
import pytest
from bec_lib.endpoints import MessageEndpoints
from qtpy.QtCore import QSettings
from bec_widgets.tests.utils import create_widget
from bec_widgets.widgets.containers.main_window.addons.scan_status_item import (
PILL_FILL_MIN,
PILL_WIDTHS,
Reveal,
ScanStatusItem,
pill_labels,
)
from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import ScanRunState
def status(state="open", **kwargs):
content = {"scan_id": "s1", "status": state, "scan_number": 12, "scan_name": "line_scan"}
content.update(kwargs)
return content, {"RID": "rid-12", "scan_id": "s1"}
def hook(name, ts, hook_status="running"):
content = {
"scan_id": "s1",
"hook": name,
"status": hook_status,
"instructions": [],
"hook_started_at": ts,
"timestamp": ts,
}
return content, {"RID": "rid-12", "scan_id": "s1"}
@pytest.fixture
def settings_path(tmp_path):
return str(tmp_path / "scan_status.ini")
@pytest.fixture
def item(qtbot, mocked_client, settings_path):
widget = create_widget(
qtbot,
ScanStatusItem,
client=mocked_client,
settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat),
)
yield widget
def test_pill_labels_for_every_state():
assert pill_labels(None) == ("Queue idle",) * 3
state = ScanRunState(scan_id="s", scan_number=12, scan_name="line_scan")
state.apply_hook(
{"hook": "stage", "status": "running", "hook_started_at": 1.0, "timestamp": 1.0}
)
short, medium, long = pill_labels(state, now=state.hook_started_local + 3)
assert short == "Staging 0:03"
assert medium == "#12 · Staging · 0:03"
assert long.startswith("#12 line_scan · Staging · 0:03") and long.endswith("next: pre_scan")
state.apply_hook(
{"hook": "scan_core", "status": "running", "hook_started_at": 2.0, "timestamp": 2.0}
)
state.apply_progress({"value": 20, "max_value": 50})
short, medium, long = pill_labels(state)
assert short == "40%"
assert medium.startswith("#12 · 40%")
assert "Point 20 of 50 · 40%" in long and long.endswith("next: post_scan")
state.apply_status({"status": "closed"}, {})
short, medium, long = pill_labels(state)
assert short == "Done" and medium.startswith("#12 done · ")
failed = ScanRunState(scan_id="f", scan_number=13, scan_name="grid_scan")
failed.apply_hook(
{"hook": "stage", "status": "running", "hook_started_at": 1.0, "timestamp": 1.0}
)
failed.apply_hook(
{"hook": "stage", "status": "error", "hook_started_at": 2.0, "timestamp": 2.0}
)
failed.apply_status({"status": "aborted"}, {})
short, medium, long = pill_labels(failed)
assert short == "Aborted" and medium.startswith("#13 aborted in Staging")
assert long.startswith("#13 grid_scan · Aborted in Staging")
def test_pill_without_a_step_uses_the_big_bar_shape():
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import describe_state
state = ScanRunState(scan_id="s", scan_number=79, scan_name="line_scan")
state.apply_status({"status": "aborted"}, {})
short, medium, long = pill_labels(state)
assert describe_state(state)["bar_text"].startswith("Aborted · ")
assert short == "Aborted"
assert medium.startswith("#79 aborted · ") and " in " not in medium
assert long.startswith("#79 line_scan · Aborted · ")
@pytest.mark.parametrize(
"status_word, outcome, mode",
[
("closed", "Done", "done"),
("user_completed", "Finished early", "done"),
("aborted", "Aborted", "error"),
("halted", "Halted", "error"),
],
)
def test_pill_and_big_widget_share_the_end_state(status_word, outcome, mode):
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import describe_state
state = ScanRunState(scan_id="s", scan_number=75, scan_name="line_scan")
state.apply_hook(
{"hook": "scan_core", "status": "running", "hook_started_at": 1.0, "timestamp": 1.0}
)
state.apply_status({"status": status_word}, {})
info = describe_state(state)
short, medium, long = pill_labels(state)
assert info["outcome"] == outcome == short
assert info["bar_mode"] == mode
for text in (medium, long, info["bar_text"]):
assert "scan_core" not in text
assert outcome.lower() in text.lower()
if mode == "error":
assert "Measuring" in medium and "Measuring" in info["bar_text"]
def test_abort_shows_the_same_words_in_pill_and_big_widget(item):
item.tracker.on_scan_status(*status())
item.tracker.on_scan_hook(*hook("scan_core", 1.0))
item.tracker.on_scan_status(*status(state="aborted"))
big = item.card.progress
assert big.bar.text.startswith("Aborted in Measuring")
assert item.pill.text.startswith("#12 aborted in Measuring")
assert big.bar.mode == item.pill.mode == "error"
def test_pill_follows_hooks_and_width_mode(item):
assert item.pill.mode == "idle" and item.pill.text == "Queue idle"
item.tracker.on_scan_status(*status())
item.tracker.on_scan_hook(*hook("stage", 1.0))
assert item.pill.mode == "busy"
assert item.pill.text.startswith("#12 · Staging")
item.tracker.on_scan_hook(*hook("scan_core", 2.0))
item.tracker.on_scan_progress({"value": 10, "max_value": 40}, {"scan_id": "s1"})
assert item.pill.mode == "progress"
assert item.pill.fraction == pytest.approx(0.25)
item.set_width_mode("compact")
assert item.pill.text == "25%"
assert item.pill.width() == PILL_WIDTHS["compact"][0]
item.set_width_mode("wide")
assert "Point 10 of 40" in item.pill.text
def test_stop_only_when_stoppable_and_uses_the_shared_stop(item, qtbot):
from bec_widgets.widgets.control.buttons.stop_button.stop_button import StopButton
assert isinstance(item.stop_button, StopButton)
assert item.stop_button.isHidden()
item.tracker.on_scan_status(*status())
assert not item.stop_button.isHidden()
with mock.patch.object(item.stop_button.queue, "request_scan_abortion") as abort:
item.stop_button.click()
abort.assert_called_once_with(request_id="rid-12")
assert item.stop_button.button.text() == "Emergency Stop"
item.tracker.on_scan_status(*status(state="closed"))
qtbot.waitUntil(item.stop_button.isHidden, timeout=2000)
item.close_card()
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 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
class SwallowLeave(QObject):
"""Like macOS with the card shown: the pill never gets its Leave event."""
def eventFilter(self, _obj, event): # pylint: disable=invalid-name
return event.type() in (QEvent.Type.Leave, QEvent.Type.HoverLeave)
item.show()
qtbot.waitExposed(item)
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
outside = inside + QPoint(2000, 2000)
QCursor.setPos(outside) # so Qt itself does not re-enter the pill when the card hides
_cursor_at(monkeypatch, outside)
qtbot.waitUntil(lambda: not item.card.isVisible(), timeout=2000)
assert not item.pill.hovered
assert not item._poll.isActive()
item.pill.removeEventFilter(swallow)
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)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
item.card.progress.confirm_before_stop = True
item.open_card()
item.card.progress.ask_stop()
qtbot.wait(item.GRACE_MS + 300)
assert item.card.isVisible()
item.close_card()
assert not item.card.isVisible() and not item._poll.isActive()
def test_menu_changes_width_and_persists(item, qtbot, mocked_client, settings_path):
fills = []
item.fill_changed.connect(fills.append)
menu = item.build_menu()
wide = next(a for a in menu.actions() if a.data() == "wide")
wide.trigger()
assert item.width_mode == "wide"
fill = next(a for a in menu.actions() if a.data() == "fill")
fill.trigger()
assert fills == [True]
assert item.pill.minimumWidth() == PILL_FILL_MIN
large = next(a for a in menu.actions() if a.text() == "Large status bar")
large.trigger()
assert item.large and item.pill.height() == 34
menu.deleteLater()
again = create_widget(
qtbot,
ScanStatusItem,
client=mocked_client,
settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat),
)
assert again.width_mode == "fill" and again.large
def test_waiting_chip_starts_hidden_without_a_queue_status(qtbot, mocked_client, settings_path):
with mock.patch.object(mocked_client.connector, "get", return_value=None):
widget = create_widget(
qtbot,
ScanStatusItem,
client=mocked_client,
settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat),
)
assert widget.waiting_chip.isHidden()
def test_waiting_chip_counts_pending_scans(item, qtbot):
item.on_queue_status({"queue": {"primary": {"info": []}}}, {})
qtbot.waitUntil(item.waiting_chip.isHidden, timeout=2000)
infos = [{"status": "RUNNING"}, {"status": "PENDING"}, {"status": "PENDING"}]
item.on_queue_status({"queue": {"primary": {"info": infos}}}, {})
assert not item.waiting_chip.isHidden()
assert item.waiting_chip.text() == "2 waiting"
item.on_queue_status({"queue": {"primary": {"info": infos[:1]}}}, {})
qtbot.waitUntil(item.waiting_chip.isHidden, timeout=2000)
qtbot.waitUntil(lambda: not item.waiting_reveal.active, timeout=2000)
def test_stop_slides_in_and_does_not_blink(item, qtbot):
item.show()
qtbot.waitExposed(item)
assert item.stop_button.isHidden() and item.stop_button.maximumWidth() == 0
item.tracker.on_scan_status(*status())
assert not item.stop_button.isHidden()
widths = []
qtbot.waitUntil(
lambda: widths.append(item.stop_button.maximumWidth()) or not item.stop_reveal.active,
timeout=2000,
)
assert widths[0] < item.stop_button.sizeHint().width() <= max(widths)
# a short flip (e.g. scan closed and the next one opened) never hides it
item.tracker.on_scan_status(*status(state="closed"))
qtbot.wait(200)
item.tracker.on_scan_status(*status(scan_id="s2", state="open"))
qtbot.wait(Reveal.HIDE_DELAY_MS + Reveal.DURATION_MS + 100)
assert not item.stop_button.isHidden() and item.stop_button.isEnabled()
# not stoppable for longer than the delay: it slides out
item.tracker.on_scan_status(*status(scan_id="s2", state="closed"))
qtbot.waitUntil(item.stop_button.isHidden, timeout=2000)
assert item.stop_button.maximumWidth() == 0
assert not item.stop_reveal.active
def test_pill_shows_the_scan_by_its_own_name():
state = ScanRunState(scan_id="s", scan_number=12, scan_name="line_scan")
state.user_metadata = {"scan_name": "My Scan"}
short, medium, long = pill_labels(state)
assert long.startswith("#12 My Scan")
def test_pill_stripes_stop_while_hidden_or_minimized(item, qtbot):
item.show()
qtbot.waitExposed(item)
timer = item.pill._stripe_timer
item.tracker.on_scan_status(*status())
item.tracker.on_scan_hook(*hook("stage", 1.0))
assert item.pill.mode == "busy"
assert timer.isActive() and timer.interval() == 100
item.hide()
assert not timer.isActive()
item.tracker.on_scan_hook(*hook("pre_scan", 2.0)) # an update while hidden
assert not timer.isActive()
item.show()
qtbot.waitExposed(item)
assert timer.isActive()
item.showMinimized()
qtbot.waitUntil(lambda: not timer.isActive())
item.tracker.on_scan_hook(*hook("open_scan", 3.0))
assert not timer.isActive()
item.showNormal()
qtbot.waitUntil(timer.isActive)
@pytest.mark.parametrize(
"reason, opens",
[
("ActiveWindowFocusReason", False), # the window is activated or the app switched back
("OtherFocusReason", False),
("MouseFocusReason", False),
("TabFocusReason", True), # the user tabbed to the pill
("BacktabFocusReason", True),
],
)
def test_card_opens_on_focus_only_when_tabbed_to(item, qtbot, monkeypatch, reason, opens):
from qtpy.QtCore import QEvent, QPoint, Qt
from qtpy.QtGui import QFocusEvent
from qtpy.QtWidgets import QApplication
item.show()
qtbot.waitExposed(item)
_cursor_at(monkeypatch, QPoint(-5000, -5000))
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()
def test_card_has_no_native_window_shadow(item):
"""Only the card's own rounded shadow; macOS would add a square one for the whole window."""
from qtpy.QtCore import Qt
flags = item.card.windowFlags()
assert flags & Qt.WindowType.NoDropShadowWindowHint
assert flags & Qt.WindowType.FramelessWindowHint
assert item.card.card.graphicsEffect() is not None
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
item.tracker.on_scan_status(*status())
item.show()
qtbot.waitExposed(item)
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
qtbot.wait(item.GRACE_MS + 300)
assert item.card.isVisible() and stop.menu.isVisible()
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)
def _stored_queue_status(waiting: int):
infos = [{"status": "RUNNING"}] + [{"status": "PENDING"}] * waiting
return mock.MagicMock(content={"queue": {"primary": {"info": infos}}}, metadata={})
def _blocking_get(msg):
"""A connector.get that waits for release in the thread pool, recording its thread."""
import threading
started, release, threads = threading.Event(), threading.Event(), []
def get(endpoint, *args, **kwargs):
if endpoint != MessageEndpoints.scan_queue_status():
return None # the card's progress bar reads the scan status itself
threads.append(threading.get_ident())
started.set()
release.wait(5)
return msg
return get, started, release, threads
def _make_item(qtbot, mocked_client, settings_path):
return create_widget(
qtbot,
ScanStatusItem,
client=mocked_client,
settings=lambda: QSettings(settings_path, QSettings.Format.IniFormat),
)
def test_stored_queue_status_is_read_off_the_gui_thread(qtbot, mocked_client, settings_path):
import threading
get, started, release, threads = _blocking_get(_stored_queue_status(2))
with mock.patch.object(mocked_client.connector, "get", side_effect=get):
widget = _make_item(qtbot, mocked_client, settings_path)
assert started.wait(5) # the pill is built while the read still blocks
assert widget.waiting_chip.isHidden()
release.set()
qtbot.waitUntil(lambda: not widget.waiting_chip.isHidden(), timeout=2000)
assert widget.waiting_chip.text() == "2 waiting"
assert threads and threading.main_thread().ident not in threads
def test_a_live_queue_status_wins_over_the_stored_one(qtbot, mocked_client, settings_path):
from qtpy.QtCore import QThreadPool
get, started, release, _threads = _blocking_get(_stored_queue_status(3))
with mock.patch.object(mocked_client.connector, "get", side_effect=get):
widget = _make_item(qtbot, mocked_client, settings_path)
assert started.wait(5)
widget.on_queue_status({"queue": {"primary": {"info": [{"status": "PENDING"}]}}}, {})
release.set()
qtbot.waitUntil(lambda: QThreadPool.globalInstance().activeThreadCount() == 0, timeout=5000)
qtbot.wait(50) # the stored status arrives after the live one and is dropped
assert widget.waiting_chip.text() == "1 waiting"
def test_closing_while_the_queue_status_is_read_is_safe(qtbot, mocked_client, settings_path):
from qtpy.QtCore import QThreadPool
get, started, release, _threads = _blocking_get(_stored_queue_status(2))
with mock.patch.object(mocked_client.connector, "get", side_effect=get):
widget = _make_item(qtbot, mocked_client, settings_path)
assert started.wait(5)
widget.close() # cleanup while the read is still running
release.set()
qtbot.waitUntil(lambda: QThreadPool.globalInstance().activeThreadCount() == 0, timeout=5000)
qtbot.wait(50) # the queued result is delivered and dropped
assert widget._waiting == 0