diff --git a/bec_widgets/applications/main_app.py b/bec_widgets/applications/main_app.py index a9600cf1..89d0cbaa 100644 --- a/bec_widgets/applications/main_app.py +++ b/bec_widgets/applications/main_app.py @@ -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) diff --git a/bec_widgets/cli/client.py b/bec_widgets/cli/client.py index f04deac4..6f48a5e9 100644 --- a/bec_widgets/cli/client.py +++ b/bec_widgets/cli/client.py @@ -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" diff --git a/bec_widgets/cli/designer_plugins.py b/bec_widgets/cli/designer_plugins.py index 6cd651ba..14e1dc65 100644 --- a/bec_widgets/cli/designer_plugins.py +++ b/bec_widgets/cli/designer_plugins.py @@ -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", diff --git a/bec_widgets/widgets/containers/dock_area/dock_area.py b/bec_widgets/widgets/containers/dock_area/dock_area.py index 8d7e5f54..54d7f258 100644 --- a/bec_widgets/widgets/containers/dock_area/dock_area.py +++ b/bec_widgets/widgets/containers/dock_area/dock_area.py @@ -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"), diff --git a/bec_widgets/widgets/containers/main_window/addons/hover_widget.py b/bec_widgets/widgets/containers/main_window/addons/hover_widget.py index d380c566..726b9b33 100644 --- a/bec_widgets/widgets/containers/main_window/addons/hover_widget.py +++ b/bec_widgets/widgets/containers/main_window/addons/hover_widget.py @@ -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_()) diff --git a/bec_widgets/widgets/containers/main_window/addons/scan_status_item.py b/bec_widgets/widgets/containers/main_window/addons/scan_status_item.py new file mode 100644 index 00000000..c250ca76 --- /dev/null +++ b/bec_widgets/widgets/containers/main_window/addons/scan_status_item.py @@ -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() diff --git a/bec_widgets/widgets/containers/main_window/main_window.py b/bec_widgets/widgets/containers/main_window/main_window.py index 98ff4b8e..4f7a6929 100644 --- a/bec_widgets/widgets/containers/main_window/main_window.py +++ b/bec_widgets/widgets/containers/main_window/main_window.py @@ -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() diff --git a/bec_widgets/widgets/progress/scan_progressbar/scan_hook_tracker.py b/bec_widgets/widgets/progress/scan_progressbar/scan_hook_tracker.py new file mode 100644 index 00000000..b1134676 --- /dev/null +++ b/bec_widgets/widgets/progress/scan_progressbar/scan_hook_tracker.py @@ -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 diff --git a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.py b/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.py index bfcd9250..af309c15 100644 --- a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.py +++ b/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.py @@ -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_()) diff --git a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.ui b/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.ui deleted file mode 100644 index a6b959e9..00000000 --- a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar.ui +++ /dev/null @@ -1,141 +0,0 @@ - - - Form - - - - 0 - 0 - 211 - 60 - - - - - 0 - 0 - - - - - 0 - 60 - - - - - 16777215 - 16777215 - - - - Form - - - - 1 - - - 2 - - - 0 - - - 2 - - - 0 - - - - - - - - 16777215 - 20 - - - - Scan - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 10 - - - - - - - - - - 2.000000000000000 - - - - - - - - - - 16777215 - 20 - - - - 0:00:00 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 0 - - - - - - - - - 16777215 - 20 - - - - 0:00:00 - - - - - - - - - - BECProgressBar - QWidget -
bec_progress_bar
-
-
- - -
diff --git a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar_one_line.ui b/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar_one_line.ui deleted file mode 100644 index e2043513..00000000 --- a/bec_widgets/widgets/progress/scan_progressbar/scan_progressbar_one_line.ui +++ /dev/null @@ -1,124 +0,0 @@ - - - Form - - - - 0 - 0 - 328 - 24 - - - - - 0 - 0 - - - - - 0 - 24 - - - - - 16777215 - 24 - - - - Form - - - - 0 - - - 2 - - - 2 - - - 2 - - - - - - 16777215 - 20 - - - - Scan - - - - - - - - 30 - 0 - - - - 5.000000000000000 - - - - - - - - - - 16777215 - 20 - - - - 0:00:00 - - - - - - - - - - - Qt::AlignmentFlag::AlignCenter - - - - - - - - 16777215 - 20 - - - - 0:00:00 - - - - - - - - - - BECProgressBar - QWidget -
bec_progress_bar
-
-
- - -
diff --git a/bec_widgets/widgets/progress/scan_progressbar/scan_ui.py b/bec_widgets/widgets/progress/scan_progressbar/scan_ui.py new file mode 100644 index 00000000..405d3dd6 --- /dev/null +++ b/bec_widgets/widgets/progress/scan_progressbar/scan_ui.py @@ -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"{self._key} {value}") + + def refresh_style(self) -> None: + super().refresh_style() + if hasattr(self, "_key"): + self._update_text() diff --git a/pyproject.toml b/pyproject.toml index c206fa41..fb388678 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/tests/end-2-end/test_rpc_widgets_e2e.py b/tests/end-2-end/test_rpc_widgets_e2e.py index 19e8109f..a824e9a1 100644 --- a/tests/end-2-end/test_rpc_widgets_e2e.py +++ b/tests/end-2-end/test_rpc_widgets_e2e.py @@ -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 diff --git a/tests/unit_tests/test_main_app.py b/tests/unit_tests/test_main_app.py index f771de12..a1371251 100644 --- a/tests/unit_tests/test_main_app.py +++ b/tests/unit_tests/test_main_app.py @@ -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 diff --git a/tests/unit_tests/test_main_widnow.py b/tests/unit_tests/test_main_widnow.py index ca4cb74f..ae756259 100644 --- a/tests/unit_tests/test_main_widnow.py +++ b/tests/unit_tests/test_main_widnow.py @@ -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 diff --git a/tests/unit_tests/test_scan_progress_bar.py b/tests/unit_tests/test_scan_progress_bar.py index 2b8a4daf..76032450 100644 --- a/tests/unit_tests/test_scan_progress_bar.py +++ b/tests/unit_tests/test_scan_progress_bar.py @@ -1,258 +1,1094 @@ +from types import SimpleNamespace from unittest import mock -import numpy as np import pytest -from bec_lib.endpoints import MessageEndpoints +from qtpy.QtGui import QFontMetricsF -from bec_widgets.tests.client_mocks import mocked_client -from bec_widgets.utils.bec_widget import BECWidget -from bec_widgets.widgets.progress.bec_progressbar.bec_progressbar import ( - BECProgressBar, - ProgressState, +from bec_widgets.tests.utils import create_widget +from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import ( + ScanRunState, + describe_instructions, + format_duration, ) -from bec_widgets.widgets.progress.progress_backend import ProgressTask -from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar +from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ( + ScanProgressBar, + describe_state, +) +from bec_widgets.widgets.progress.scan_progressbar.scan_ui import ( + args_summary, + request_inputs_summary, + scan_bundle_names, +) +from bec_widgets.widgets.progress.stage_bar import BarMode + + +def status(scan_id="s1", state="open", **kwargs): + content = { + "scan_id": scan_id, + "status": state, + "scan_number": 12, + "scan_name": "line_scan", + "user_metadata": {"sample": "LiFePO4"}, + "request_inputs": { + "arg_bundle": ["samx", -5, 5], + "inputs": {}, + "kwargs": {"steps": 50, "exp_time": 0.1}, + }, + } + content.update(kwargs) + return content, {"RID": "rid-1", "scan_id": scan_id} + + +def hook(name, ts, scan_id="s1", hook_status="running", instructions=None, **kwargs): + content = { + "scan_id": scan_id, + "hook": name, + "status": hook_status, + "instructions": instructions or [], + "timestamp": ts, + "waiting": False, + "wait_started_at": None, + } + content.update(kwargs) + return content, {"RID": "rid-1", "scan_id": scan_id} + + +def step(tracker, name, ts, scan_id="s1", **hook_kwargs): + """A new top-level step as the server reports it, with the time it started.""" + tracker.on_scan_hook(*hook(name, ts, scan_id=scan_id, hook_started_at=ts, **hook_kwargs)) @pytest.fixture -def scan_progressbar(qtbot, mocked_client): - widget = ScanProgressBar(client=mocked_client) - qtbot.addWidget(widget) - qtbot.waitExposed(widget) +def progress(qtbot, mocked_client): + widget = create_widget(qtbot, ScanProgressBar, client=mocked_client) yield widget -def test_progress_task_basic(): - """percentage, remaining, and formatted time helpers behave as expected.""" - task = ProgressTask(parent=None, value=50, max_value=100, done=False) - task.timer.stop() # we don’t want the timer ticking in tests - task._elapsed_time = 10 # simulate 10 s elapsed - - # 50 / 100 ⇒ 50 % - assert task.percentage == 50 - - # speed = value / elapsed = 5 steps / s - assert np.isclose(task.speed, 5) - - # remaining steps = 50 ; time_remaining ≈ 10 s - assert task.remaining == 50 - assert task.time_remaining == "00:00:10" - - # time_elapsed formatting - assert task.time_elapsed == "00:00:10" +def test_idle_widget(progress): + assert progress.title_label.full_text() == "No scan yet" + assert not progress.stop_button.isEnabled() + assert progress.bar.mode == BarMode.IDLE -def test_progress_task_elapsed_time_uses_monotonic_clock(monkeypatch): - times = iter([100.0, 102.5]) - monkeypatch.setattr( - "bec_widgets.widgets.progress.progress_backend.time.monotonic", lambda: next(times) +def test_busy_steps_then_measurement(progress): + step(progress.tracker, "prepare_scan", 100.0) + assert progress.bar.mode == BarMode.BUSY + assert progress.bar.text.startswith("Preparing") + assert progress.next_label.full_text().startswith("Next: Opening scan") + + progress.tracker.on_scan_status(*status()) + assert progress.title_label.full_text() == "#12 line_scan" + assert "samx -5 5" in progress.header_row.toolTip() + assert "samx -5 5" in progress.chips.toolTip() + + stage = [{"device": ["samx", "eiger"], "action": "stage", "parameter": {}}] + step(progress.tracker, "stage", 101.0, instructions=stage) + assert progress.state_chip.text() == "Staging" + assert progress.instruction_label.full_text() == "Staging samx, eiger" + + step(progress.tracker, "scan_core", 104.0) + progress.tracker.on_scan_progress( + {"value": 10, "max_value": 50, "done": False}, {"scan_id": "s1"} ) - task = ProgressTask(parent=None) - task.timer.stop() + assert progress.bar.mode == BarMode.PROGRESS + assert progress.bar.text.startswith("Point 10 of 50 · 20%") + assert progress.bar.fraction == pytest.approx(0.2) - task.update_elapsed_time() - - assert task._elapsed_time == 2.5 - assert task.time_elapsed == "00:00:02" + timings = {t.hook: t for t in progress.state.step_times()} + assert timings["prepare_scan"].total == pytest.approx(1.0) + assert timings["stage"].total == pytest.approx(3.0) -def test_scan_progressbar_initialization(scan_progressbar): - assert isinstance(scan_progressbar, ScanProgressBar) - assert isinstance(scan_progressbar.progressbar, BECProgressBar) - - -def test_scan_progressbar_passes_dynamic_stylesheet_setting(qtbot, mocked_client): - widget = ScanProgressBar(client=mocked_client, enable_dynamic_stylesheet=False) - qtbot.addWidget(widget) - - assert widget.progressbar.enable_dynamic_stylesheet is False - - -def test_scan_progressbar_starts_from_scan_progress_before_queue_update(scan_progressbar): - scan_progressbar.progress_tracker.clear_task(emit_finished=False) - - scan_progressbar.progress_tracker.process_progress_message( - {"value": 3, "max_value": 10, "done": False}, metadata={"RID": "live-rid"} +def test_waiting_instruction_shows_wait_time(progress): + move = [{"device": "samx", "action": "set", "parameter": {"value": -5.0}}] + step( + progress.tracker, "pre_scan", 200.0, instructions=move, waiting=True, wait_started_at=197.0 ) - - assert scan_progressbar.progress_tracker.task is not None - assert scan_progressbar.progress_tracker._active_scan_id == "live-rid" - assert scan_progressbar.progressbar._user_value == 3 - assert scan_progressbar.progressbar._user_maximum == 10 + text = progress.instruction_label.full_text() + assert text.startswith("Waiting for samx to reach -5") + assert text.endswith("0:03") -def test_update_labels_content(scan_progressbar): - """update_labels() reflects ProgressTask time strings on the UI.""" - # fabricate a task with known timings - task = ProgressTask(parent=scan_progressbar, value=30, max_value=100, done=False) - task.timer.stop() - task._elapsed_time = 50 - scan_progressbar.progress_tracker.task = task - - scan_progressbar.update_labels() - - assert scan_progressbar.ui.elapsed_time_label.text() == "00:00:50" - assert scan_progressbar.ui.remaining_time_label.text() == "00:01:57" +def test_nested_hook_keeps_parent_step(progress): + step(progress.tracker, "pre_scan", 10.0) + progress.tracker.on_scan_hook(*hook("before_pre_scan", 10.5)) + state = progress.state + assert state.top_hook == "pre_scan" + assert progress.instruction_label.full_text().startswith("[before_pre_scan]") + assert state.timings["before_pre_scan"].nested + progress.tracker.on_scan_hook(*hook("before_pre_scan", 11.0, hook_status="completed")) + progress.tracker.on_scan_hook(*hook("pre_scan", 11.0)) + assert state.timings["before_pre_scan"].total == pytest.approx(0.5) + assert state.timings["pre_scan"].count == 1 + assert state.timings["pre_scan"].started_at == 10.0 -def test_progress_update(qtbot, scan_progressbar): - """ - Scan progress updates should update the embedded BECProgressBar - and keep ProgressTask in sync. - """ - task = ProgressTask(parent=scan_progressbar, value=0, max_value=100, done=False) - task.timer.stop() - scan_progressbar.progress_tracker.task = task - - msg = {"value": 20, "max_value": 100, "done": False} - scan_progressbar.progress_tracker.process_progress_message(msg, metadata={"status": "open"}) - - qtbot.wait(200) - bar = scan_progressbar.progressbar - assert bar._user_value == 20 - assert bar._user_maximum == 100 - # state reflects BEC status - assert bar.state is ProgressState.NORMAL +def test_finished_scan(progress): + step(progress.tracker, "stage", 10.0) + progress.tracker.on_scan_status(*status(state="aborted")) + assert progress.state_chip.text() == "Aborted" + assert progress.bar.mode == BarMode.ERROR + assert progress.bar.text.startswith("Aborted in Staging") + assert not progress.stop_button.isEnabled() + assert not progress.tracker._timer.isActive() -def test_scan_status_open_resets_progress_before_first_progress_update(scan_progressbar): - scan_progressbar.progressbar.set_maximum(50) - scan_progressbar.progressbar.set_value(25) - scan_progressbar.progressbar.state = ProgressState.INTERRUPTED - scan_progressbar.ui.elapsed_time_label.setText("00:00:12") - scan_progressbar.ui.remaining_time_label.setText("00:00:34") - - scan_progressbar.progress_tracker.process_scan_status_message( - {"scan_id": "scan-1", "scan_number": 7, "status": "open"}, {"RID": "rid-1"} - ) - - assert scan_progressbar.progressbar._user_value == 0 - assert scan_progressbar.progressbar._user_maximum == 100 - assert scan_progressbar.progressbar.state is ProgressState.NORMAL - assert scan_progressbar.ui.elapsed_time_label.text() == "00:00:00" - assert scan_progressbar.ui.remaining_time_label.text() == "00:00:00" - assert scan_progressbar.ui.source_label.text() == "Scan 7" +def test_stop_aborts_by_rid_then_offers_emergency_stop(progress, qtbot): + progress.tracker.on_scan_status(*status()) + stop = progress.stop_button + queue = stop.queue + with mock.patch.object(queue, "request_scan_abortion") as abort: + stop.click() + abort.assert_called_once_with(request_id="rid-1") + assert progress.confirm_frame.isHidden() # no confirmation row by default + # a stretched bar keeps the Stop width: the short label then says the same + assert stop.button.text() in (stop.EMERGENCY_STOP_LABEL, stop.EMERGENCY_STOP_SHORT_LABEL) + with mock.patch.object(queue, "request_scan_halt") as halt: + stop.click() + halt.assert_called_once_with(request_id="rid-1") + stop._reset_timer.setInterval(50) + stop._reset_timer.start() + qtbot.waitUntil(lambda: stop.button.text() == "Stop", timeout=2000) -def test_scan_status_open_reset_ignores_same_scan(scan_progressbar): - scan_progressbar.progress_tracker.process_scan_status_message( - {"scan_id": "scan-1", "status": "open"}, {} - ) - scan_progressbar.progressbar.set_value(20) - - scan_progressbar.progress_tracker.process_scan_status_message( - {"scan_id": "scan-1", "status": "open"}, {} - ) - - assert scan_progressbar.progressbar._user_value == 20 +def test_stop_menu_finishes_or_halts(progress): + progress.tracker.on_scan_status(*status()) + stop = progress.stop_button + with mock.patch.object(stop.queue, "request_set_completed") as finish: + stop.finish_action.trigger() + finish.assert_called_once_with(request_id="rid-1") + assert stop.button.text() == "Stop" # finishing is not an abort: no emergency step + with mock.patch.object(stop.queue, "request_scan_halt") as halt: + stop.halt_action.trigger() + halt.assert_called_once_with(request_id="rid-1") -def test_scan_status_non_open_does_not_reset_progress(scan_progressbar): - scan_progressbar.progressbar.set_value(25) +def test_confirm_before_stop_asks_first(progress): + progress.confirm_before_stop = True + progress.tracker.on_scan_status(*status()) + with mock.patch.object(progress.stop_button.queue, "request_scan_abortion") as abort: + progress.stop_button.click() + abort.assert_not_called() + assert not progress.confirm_frame.isHidden() + assert "#12 line_scan" in progress.confirm_label.full_text() + progress.confirm_stop_button.click() + abort.assert_called_once_with(request_id="rid-1") + with mock.patch.object(progress.stop_button.queue, "request_set_completed") as finish: + progress.stop_button.finish_action.trigger() + assert progress.confirm_stop_button.text() == "Finish now" + progress.confirm_cancel_button.click() + finish.assert_not_called() - scan_progressbar.progress_tracker.process_scan_status_message( - {"scan_id": "scan-1", "status": "closed"}, {} - ) - assert scan_progressbar.progressbar._user_value == 25 +def test_step_times_popup_lists_hooks(progress): + step(progress.tracker, "prepare_scan", 9.0) + step(progress.tracker, "open_scan", 9.5) + step(progress.tracker, "stage", 10.0) + step(progress.tracker, "pre_scan", 12.5) + progress.step_times.show_popup() + hooks = [row[0] for row in progress.step_times.popup.rows] + assert hooks == ["prepare_scan", "open_scan", "stage", "pre_scan"] + assert progress.step_times.popup.rows[0][1] == "0.5 s" + assert progress.step_times.popup.rows[2][1] == "2.5 s" + progress.step_times.popup.hide() + + +def test_step_times_popup_updates_rows_in_place(progress, qtbot): + step(progress.tracker, "stage", 10.0) + popup = progress.step_times.popup + progress.step_times.show_popup() + qtbot.waitExposed(popup) + first = popup._row(0) + size = popup.size() + for ts in (11.0, 12.0, 13.0): + step(progress.tracker, "pre_scan", ts) + progress.tracker.on_scan_hook(*hook("pre_scan", ts + 0.5, hook_status="completed")) + step(progress.tracker, "stage", ts + 0.5) + progress._render() + assert popup._row(0) is first + assert [row[0] for row in popup.rows] == ["stage", "pre_scan"] + assert popup.width() >= size.width() + popup.hide() + + +def test_old_scan_messages_are_ignored(progress): + progress.tracker.on_scan_status(*status(scan_id="s2")) + progress.tracker.on_scan_status(*status(scan_id="s1", state="closed")) + assert progress.state.scan_id == "s2" + + +def test_without_hooks_progress_still_shows(): + state = ScanRunState(scan_id="x", scan_number=3, scan_name="grid_scan") + assert describe_state(state)["bar_text"].startswith("Running") + state.apply_progress({"value": 5, "max_value": 10}) + info = describe_state(state) + assert info["bar_mode"] == BarMode.PROGRESS + assert info["next"] == "" @pytest.mark.parametrize( - "status, value, max_val, expected_state", + "instructions, waiting, expected", [ - ("open", 10, 100, ProgressState.NORMAL), - ("paused", 25, 100, ProgressState.PAUSED), - ("aborted", 30, 100, ProgressState.WARNING), - ("halted", 40, 100, ProgressState.INTERRUPTED), - ("closed", 100, 100, ProgressState.COMPLETED), - ("user_completed", 40, 100, ProgressState.COMPLETED), - ("UNKNOWN", 10, 100, ProgressState.NORMAL), + ( + [{"device": "samx", "action": "set", "parameter": {"value": 1.5}}], + False, + "Moving samx to 1.5", + ), + ( + [{"device": "eiger", "action": "trigger", "parameter": {}}], + True, + "Waiting for eiger (trigger)", + ), + ( + [{"device": "dev", "action": "rpc", "parameter": {"func": "reset"}}], + False, + "Calling dev.reset()", + ), + ( + [{"device": None, "action": "baseline_reading", "parameter": {}}], + False, + "Reading baseline", + ), + ([{"device": "a", "action": "scan_report_instruction", "parameter": {}}], False, ""), + ( + [{"device": ["a", "b", "c", "d", "e"], "action": "read", "parameter": {}}], + False, + "Reading a, b, c +2", + ), ], ) -def test_state_mapping_during_updates( - qtbot, scan_progressbar, status, value, max_val, expected_state -): - """ScanProgressBar should translate BEC status → ProgressState consistently.""" - task = ProgressTask(parent=scan_progressbar, value=0, max_value=max_val, done=False) - task.timer.stop() - scan_progressbar.progress_tracker.task = task +def test_describe_instructions(instructions, waiting, expected): + assert describe_instructions(instructions, waiting) == expected - scan_progressbar.progress_tracker.process_progress_message( - {"value": value, "max_value": max_val, "done": status == "closed"}, - metadata={"status": status}, + +def test_format_duration(): + assert format_duration(5) == "0:05" + assert format_duration(3725) == "1:02:05" + assert format_duration(None) == "" + + +def test_points_inside_scan_core_do_not_flicker(progress): + tracker = progress.tracker + step(tracker, "scan_core", 50.0) + tracker.on_scan_progress({"value": 3, "max_value": 50, "done": False}, {"scan_id": "s1"}) + started = progress.state.hook_started_local + texts = set() + shown = [] + for point in range(5): + move = [{"device": "samx", "action": "set", "parameter": {"value": point}}] + tracker.on_scan_hook(*hook("at_each_point", 51.0 + point, instructions=move)) + shown.append(progress.instruction_label.full_text()) + texts.add( + (progress.bar.mode, progress.state_chip.text(), progress.instruction_label.full_text()) + ) + tracker.on_scan_hook(*hook("at_each_point", 51.5 + point, hook_status="completed")) + tracker.on_scan_hook(*hook("scan_core", 51.5 + point)) + texts.add( + (progress.bar.mode, progress.state_chip.text(), progress.instruction_label.full_text()) + ) + # the step and the bar stay put; the instruction line shows every broadcast at once + assert {(mode, chip) for mode, chip, _ in texts} == {("progress", "Measuring")} + assert shown == [f"Moving samx to {point}" for point in range(5)] + assert progress.state.hook_started_local == started + assert [t.hook for t in progress.state.step_times()] == ["scan_core"] + assert progress.state.timings["scan_core"].count == 1 + + +def test_long_wait_inside_scan_core_is_shown(progress): + step(progress.tracker, "scan_core", 50.0) + trigger = [{"device": "eiger", "action": "trigger", "parameter": {}}] + progress.tracker.on_scan_hook( + *hook("at_each_point", 60.0, instructions=trigger, waiting=True, wait_started_at=55.0) ) - - assert scan_progressbar.progressbar.state is expected_state + assert progress.instruction_label.full_text() == "Waiting for eiger (trigger) · 0:05" -def test_aborted_done_scan_keeps_partial_progress(scan_progressbar): - scan_progressbar.progress_tracker.process_progress_message( - {"value": 4, "max_value": 10, "done": True}, - metadata={"scan_id": "scan-1", "RID": "rid-1", "status": "aborted"}, +def test_scan_core_shows_points_before_the_first_progress(progress): + progress.tracker.on_scan_status(*status(num_points=50)) + step(progress.tracker, "scan_core", 50.0) + assert progress.bar.mode == BarMode.PROGRESS + assert progress.bar.text.startswith("Point 0 of 50 · 0%") + + +def test_every_step_is_listed_in_order(progress): + progress.tracker.on_scan_status(*status()) + for index, name in enumerate(("prepare_scan", "open_scan", "stage")): + step(progress.tracker, name, 9.0 + index * 0.01) + step(progress.tracker, "pre_scan", 10.0) + progress.tracker.on_scan_hook(*hook("before_pre_scan", 10.2)) + step(progress.tracker, "scan_core", 11.0) + step(progress.tracker, "post_scan", 15.0) + for index, name in enumerate(("unstage", "close_scan")): + step(progress.tracker, name, 15.5 + index * 0.01) + progress.tracker.on_scan_status(*status(state="closed")) + steps = progress.state.step_times() + assert [t.hook for t in steps] == [ + "prepare_scan", + "open_scan", + "stage", + "pre_scan", + "before_pre_scan", + "scan_core", + "post_scan", + "unstage", + "close_scan", + ] + assert progress.state.timings["scan_core"].total == pytest.approx(4.0) + assert progress.state.timings["stage"].total == pytest.approx(0.98) + + +def test_only_the_reported_steps_are_listed(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "scan_core", 11.0) + step(progress.tracker, "post_scan", 15.0) + assert [t.hook for t in progress.state.step_times()] == ["scan_core", "post_scan"] + + +def test_step_completion_and_error_come_from_the_hook(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "stage", 10.0) + progress.tracker.on_scan_hook(*hook("stage", 12.0, hook_status="completed")) + assert progress.state.timings["stage"].total == pytest.approx(2.0) + step(progress.tracker, "pre_scan", 12.0) + progress.tracker.on_scan_hook(*hook("pre_scan", 13.0, hook_status="error")) + assert progress.state.hook_error == "pre_scan" + assert progress.state.timings["pre_scan"].status == "error" + progress.tracker.on_scan_status(*status(state="aborted")) + info = describe_state(progress.state) + assert info["bar_mode"] == BarMode.ERROR + assert info["bar_text"].startswith("Aborted in Pre-scan") + + +def test_an_interrupted_step_is_not_shown_as_failed(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "scan_core", 10.0) + progress.tracker.on_scan_hook(*hook("scan_core", 14.0, hook_status="interrupted")) + timing = progress.state.timings["scan_core"] + assert timing.status == "interrupted" and timing.started_at is None + assert progress.state.hook_error is None + progress.tracker.on_scan_status(*status(state="user_completed")) + info = describe_state(progress.state) + assert info["outcome"] == "Finished early" # the outcome comes from the scan status + assert info["bar_mode"] == BarMode.DONE + + +def test_an_interrupted_nested_hook_closes_without_an_error(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "stage", 10.0) + progress.tracker.on_scan_hook(*hook("before_stage_modifier", 11.0)) + progress.tracker.on_scan_hook(*hook("before_stage_modifier", 12.0, hook_status="interrupted")) + timing = progress.state.timings["before_stage_modifier"] + assert timing.status == "interrupted" and timing.started_at is None + assert progress.state.hook_error is None + + +def test_an_abort_closes_open_steps_as_interrupted_not_failed(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "stage", 10.0) + progress.tracker.on_scan_hook(*hook("before_stage_modifier", 11.0)) + progress.tracker.on_scan_status(*status(state="aborted")) + for name in ("stage", "before_stage_modifier"): + assert progress.state.timings[name].status == "interrupted" + assert progress.state.hook_error is None + info = describe_state(progress.state) + assert info["outcome"] == "Aborted" + assert info["bar_text"].startswith("Aborted in Staging") + + +def queue(*scan_ids, entry_status="RUNNING"): + """A scan queue status content with one request per scan id, in a running queue.""" + infos = [{"status": entry_status, "scan_id": [scan_id]} for scan_id in scan_ids] + return {"queue": {"primary": {"info": infos, "status": "RUNNING"}}}, {} + + +def test_a_scan_that_left_the_queue_without_a_final_status_ends_as_aborted(progress, qtbot): + tracker = progress.tracker + tracker._lost_check.setInterval(20) + tracker.on_scan_status(*status(num_points=20)) + step(tracker, "scan_core", 10.0) + tracker.on_scan_progress({"value": 14, "max_value": 20}, {"scan_id": "s1"}) + tracker.on_queue_status(*queue("s1")) + assert not tracker._lost_check.isActive() + # the server was restarted while the scan ran: it never reports aborted + tracker.on_queue_status(*queue()) + qtbot.waitUntil(lambda: progress.state.finished, timeout=2000) + assert progress.state.status == "aborted" and progress.state.lost + assert progress.state.timings["scan_core"].status == "interrupted" + assert progress.bar.mode == BarMode.ERROR + assert progress.bar.text == "Aborted in Measuring · scan server stopped" + assert progress.next_label.full_text() == "The scan server stopped while the scan ran" + assert not progress.stop_button.isEnabled() + + +def test_a_resumed_scan_runs_again_when_its_queue_entry_runs(progress): + tracker = progress.tracker + tracker.on_scan_status(*status(num_points=10)) + step(tracker, "scan_core", 10.0) + tracker.on_scan_progress({"value": 4, "max_value": 10}, {"scan_id": "s1"}) + tracker.on_scan_status(*status(state="paused")) + assert progress.state_chip.text() == "Paused" and progress.bar.mode == BarMode.PAUSED + # a hard pause only pauses the queue entry; the queue itself still reports RUNNING + tracker.on_queue_status(*queue("s1", entry_status="PAUSED")) + assert progress.state_chip.text() == "Paused" + # BEC resumes through the entry's status and sends no new scan status + tracker.on_queue_status(*queue("s1")) + tracker.on_scan_progress({"value": 6, "max_value": 10}, {"scan_id": "s1"}) + assert progress.state_chip.text() == "Measuring" + assert progress.bar.mode == BarMode.PROGRESS + assert progress.bar.text.startswith("Point 6 of 10") + + +def test_a_paused_scan_that_reports_its_next_step_runs_again(progress): + tracker = progress.tracker + tracker.on_scan_status(*status()) + step(tracker, "stage", 10.0) + tracker.on_scan_status(*status(state="paused")) + assert progress.state_chip.text() == "Paused" + step(tracker, "pre_scan", 12.0) + assert progress.state.status == "open" + assert progress.state_chip.text() != "Paused" + + +def test_a_final_status_after_the_queue_update_wins(progress, qtbot): + tracker = progress.tracker + tracker._lost_check.setInterval(20) + tracker.on_scan_status(*status()) + tracker.on_queue_status(*queue()) # the queue can drop the scan just before its status + tracker.on_scan_status(*status(state="closed")) + qtbot.wait(60) + assert progress.state.status == "closed" and not progress.state.lost + assert not tracker._lost_check.isActive() + + +def test_the_check_of_a_lost_scan_does_not_end_the_next_scan(progress, qtbot): + tracker = progress.tracker + tracker._lost_check.setInterval(20) + tracker.on_scan_status(*status()) + tracker.on_queue_status(*queue()) + tracker.on_scan_status(*status(scan_id="s2")) # opened before the check ran + qtbot.wait(60) + assert progress.state.scan_id == "s2" and not progress.state.finished + + +GRID_NAMES = ["start", "stop", "steps"] + + +@pytest.mark.parametrize( + "values, names, expected", + [ + ([-5, 5, 10], GRID_NAMES, "samx -5 → 5 steps 10"), # the number of steps is no position + ([-5, 5], ["start", "stop"], "samx -5 → 5"), + ([1.5], ["target"], "samx 1.5"), + ([[1, 2, 3]], ["positions"], "samx 1 → 2 → 3"), + ([1, 2], ["center", "width"], "samx center 1 width 2"), + ([-5, 5], None, "samx -5 → 5"), + ([-5, 5, 10], None, "samx -5 5 10"), # unknown meaning: not shown as a path + ], +) +def test_argument_bundles_show_what_their_values_mean(values, names, expected): + assert args_summary({"args": {"samx": values}, "kwargs": {}}, names) == expected + + +def test_request_inputs_are_split_in_bundles_with_their_names(): + inputs = {"arg_bundle": ["samx", -5, 5, 10, "samy", -1, 1, 20], "inputs": {}, "kwargs": {}} + assert request_inputs_summary(inputs, GRID_NAMES) == ( + "samx -5 → 5 steps 10 · samy -1 → 1 steps 20" ) - - assert scan_progressbar.progressbar._user_value == 4 - assert scan_progressbar.progressbar._user_maximum == 10 - assert scan_progressbar.progressbar.state is ProgressState.WARNING - assert scan_progressbar.progress_tracker.task is None + assert request_inputs_summary(inputs) == "samx -5 5 10 samy -1 1 20" -def test_source_label_updates(scan_progressbar): - """update_source_label() renders the current scan label.""" - scan_progressbar.progress_tracker.scan_number = 5 - scan_progressbar.update_source_label() - assert scan_progressbar.ui.source_label.text() == "Scan 5" +def test_a_device_rpc_in_the_request_inputs_is_a_call(): + inputs = { + "arg_bundle": [], + "inputs": {"device": "samx", "func": "read"}, + "kwargs": {"func_args": ["a"], "func_kwargs": {"cached": False}, "rpc_id": "abc"}, + } + assert request_inputs_summary(inputs) == "samx.read('a', cached=False)" -def test_source_label_update_logs_only_on_text_change(scan_progressbar): - scan_progressbar.progress_tracker.scan_number = 5 - - with mock.patch( - "bec_widgets.widgets.progress.scan_progressbar.scan_progressbar.logger.info" - ) as mock_info: - scan_progressbar.update_source_label() - scan_progressbar.update_source_label() - scan_progressbar.update_source_label() - - mock_info.assert_called_once_with("Set progress source to Scan 5") +def test_scan_bundle_names_come_from_the_scan_info(): + arg_input = {"device": "device", "start": "float", "stop": "float", "steps": "int"} + scans = SimpleNamespace(grid_scan=SimpleNamespace(scan_info={"arg_input": arg_input})) + assert scan_bundle_names(scans, "grid_scan") == GRID_NAMES + assert scan_bundle_names(scans, "unknown_scan") == [] + assert scan_bundle_names(None, "grid_scan") == [] -def test_cleanup_disconnects_active_scan_subscription(scan_progressbar, monkeypatch): +def test_the_scan_arguments_follow_the_title(progress): + assert progress.args_label.full_text() == "" + progress.tracker.on_scan_status(*status()) + assert progress.title_label.full_text() == "#12 line_scan" + assert progress.title_label.font().bold() and not progress.args_label.font().bold() + assert progress.args_label.full_text().startswith("samx -5 5") + assert progress.args_label.full_text() in progress.header_row.toolTip() - disconnect_calls = [] - monkeypatch.setattr(scan_progressbar.bec_dispatcher, "connect_slot", lambda *args: None) - monkeypatch.setattr( - scan_progressbar.bec_dispatcher, - "disconnect_slot", - lambda slot, endpoint: disconnect_calls.append(endpoint), +def test_the_title_keeps_its_width_and_the_arguments_take_the_rest(progress, qtbot): + progress.resize(900, 200) + progress.show() + qtbot.waitExposed(progress) + progress.tracker.on_scan_status(*status()) + qtbot.waitUntil(lambda: progress.title_label.text() == "#12 line_scan", timeout=2000) + assert progress.args_label.width() > 100 + assert progress.args_label.x() <= progress.title_label.geometry().right() + 12 + + +def test_a_failed_step_stays_an_error_after_the_abort(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "stage", 10.0) + progress.tracker.on_scan_hook(*hook("before_stage_modifier", 11.0)) + progress.tracker.on_scan_hook(*hook("before_stage_modifier", 12.0, hook_status="error")) + progress.tracker.on_scan_hook(*hook("stage", 12.5, hook_status="error")) + progress.tracker.on_scan_status(*status(state="aborted")) + assert progress.state.timings["before_stage_modifier"].status == "error" + assert progress.state.timings["stage"].status == "error" + assert progress.state.hook_error == "stage" + + +def test_a_new_step_clears_the_wait_of_the_previous_step(progress): + trigger = [{"device": "eiger", "action": "trigger", "parameter": {}}] + step( + progress.tracker, + "scan_core", + 50.0, + instructions=trigger, + waiting=True, + wait_started_at=45.0, ) - monkeypatch.setattr(scan_progressbar.progressbar, "close", lambda: None) - monkeypatch.setattr(scan_progressbar.progressbar, "deleteLater", lambda: None) - monkeypatch.setattr(BECWidget, "cleanup", lambda self: None) - - with ( - mock.patch.object(scan_progressbar, "close", wraps=scan_progressbar.close) as close_mock, - mock.patch.object( - scan_progressbar, "deleteLater", wraps=scan_progressbar.deleteLater - ) as delete_later_mock, - ): - ScanProgressBar.cleanup(scan_progressbar) - - assert disconnect_calls == [MessageEndpoints.scan_progress(), MessageEndpoints.scan_status()] - assert scan_progressbar.progress_tracker._connected is False - close_mock.assert_not_called() - delete_later_mock.assert_not_called() + assert progress.instruction_label.full_text().startswith("Waiting for eiger") + progress.tracker.on_scan_hook(*hook("post_scan", 51.0)) + assert progress.state.waiting is False + assert progress.instruction_label.full_text() == "" -def test_cleanup_stops_active_task(scan_progressbar, monkeypatch): - monkeypatch.setattr(BECWidget, "cleanup", lambda self: None) - scan_progressbar.progress_tracker.task = ProgressTask(parent=scan_progressbar) - scan_progressbar.progress_tracker._active_scan_id = "scan-1" - timer = scan_progressbar.progress_tracker.task.timer +def test_a_step_of_another_scan_starts_that_scan(progress): + progress.tracker.on_scan_status(*status()) + step(progress.tracker, "scan_core", 10.0) + progress.tracker.on_scan_hook(*hook("stage", 20.0, scan_id="s2")) + assert progress.state.scan_id == "s2" and progress.state.top_hook == "stage" - ScanProgressBar.cleanup(scan_progressbar) +def opened_mid_scan(qtbot, mocked_client, stored): + """A ScanProgressBar created while the connector holds the given stored messages.""" + from bec_lib.endpoints import MessageEndpoints + + def get(endpoint): + msg = stored.get(endpoint.endpoint) + return None if msg is None else mock.MagicMock(content=msg[0], metadata=msg[1]) + + keys = { + "status": MessageEndpoints.scan_status().endpoint, + "hook": MessageEndpoints.scan_hook().endpoint, + "progress": MessageEndpoints.scan_progress().endpoint, + "queue": MessageEndpoints.scan_queue_status().endpoint, + } + stored = {keys[k]: v for k, v in stored.items()} + with mock.patch.object(mocked_client.connector, "get", side_effect=get): + widget = create_widget(qtbot, ScanProgressBar, client=mocked_client) + qtbot.waitUntil(lambda: widget.tracker.loaded, timeout=2000) # read in the thread pool + return widget + + +def test_opened_mid_scan_shows_the_stored_hook_and_progress(qtbot, mocked_client): + import time + + now = time.time() + widget = opened_mid_scan( + qtbot, + mocked_client, + { + "status": status(num_points=20), + "hook": hook( + "scan_core", + now - 1.0, + hook_started_at=now - 21.0, + instructions=[{"device": "eiger", "action": "trigger", "parameter": {}}], + waiting=True, + wait_started_at=now - 4.0, + ), + "progress": ({"value": 7, "max_value": 20, "done": False}, {"scan_id": "s1"}), + }, + ) + assert widget.state_chip.text() == "Measuring" + # the stored hook also has the current instruction and how long it has been waiting + assert widget.instruction_label.full_text() == "Waiting for eiger (trigger) · 0:04" + assert widget.bar.mode == BarMode.PROGRESS + # 7 points in 21 s, so the 13 points left take about 39 s + assert widget.state.remaining() == pytest.approx(39.0, abs=1.0) + assert widget.bar.text == "Point 7 of 20 · 35% · 0:39 left" + assert widget.state.hook_elapsed() == pytest.approx(21.0, abs=1.0) + # the steps before it are not known and not listed + assert [t.hook for t in widget.state.step_times()] == ["scan_core"] + assert widget.state.timings["scan_core"].duration(now) == pytest.approx(21.0, abs=1.0) + + +def test_stored_hook_and_progress_of_another_scan_are_ignored(qtbot, mocked_client): + import time + + now = time.time() + widget = opened_mid_scan( + qtbot, + mocked_client, + { + "status": status(num_points=20), + "hook": hook("close_scan", now - 50.0, scan_id="old"), + "progress": ({"value": 20, "max_value": 20, "done": True}, {"scan_id": "old"}), + }, + ) + assert widget.state.scan_id == "s1" + assert widget.state.top_hook is None and widget.state.progress_value is None + assert widget.state_chip.text() == "Running" + + +def test_opened_after_a_restart_ends_the_stale_stored_scan(qtbot, mocked_client): + from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import ScanHookTracker + + # the stored status still says open, but the restarted server's queue no longer has the scan + with mock.patch.object(ScanHookTracker, "LOST_SCAN_GRACE_MS", 20): + widget = opened_mid_scan( + qtbot, mocked_client, {"status": status(), "queue": queue("other")} + ) + qtbot.waitUntil(lambda: widget.state.finished, timeout=2000) + assert widget.state.lost + assert widget.state_chip.text() == "Aborted" + + +def test_a_scan_that_finished_between_the_startup_reads_shows_done(qtbot, mocked_client): + # read "open", then the scan finished before the queue was read: not a lost scan + widget = opened_mid_scan(qtbot, mocked_client, {"status": status(), "queue": queue()}) + assert not widget.state.finished # the grace period applies at startup too + widget.tracker.on_scan_status(*status(state="closed")) + assert widget.state_chip.text() == "Done" and not widget.state.lost + assert "scan server stopped" not in widget.bar.text + + +def test_a_late_final_status_replaces_an_inferred_abort(progress, qtbot): + tracker = progress.tracker + tracker._lost_check.setInterval(20) + tracker.on_scan_status(*status()) + step(tracker, "scan_core", 10.0) + tracker.on_queue_status(*queue()) + qtbot.waitUntil(lambda: progress.state.lost, timeout=2000) + tracker.on_scan_status(*status(state="closed")) # the real end, after the grace period + assert not progress.state.lost + assert progress.state_chip.text() == "Done" + assert progress.bar.text.startswith("Done ·") and "scan server stopped" not in progress.bar.text + assert progress.next_label.full_text().startswith("Took") + assert progress.state.timings["scan_core"].status == "completed" + + +def test_creating_the_bar_does_not_wait_for_redis(qtbot, mocked_client): + import threading + + from bec_lib.endpoints import MessageEndpoints + + started, release, threads = threading.Event(), threading.Event(), [] + old_status = mock.MagicMock(content=status(scan_id="old")[0], metadata={}) + + def get(endpoint, *args, **kwargs): + threads.append(threading.get_ident()) + if endpoint == MessageEndpoints.scan_status(): + started.set() + release.wait(5) + return old_status + return None + + with mock.patch.object(mocked_client.connector, "get", side_effect=get): + widget = create_widget(qtbot, ScanProgressBar, client=mocked_client) + assert started.wait(5) # the widget is built while the stored status is still read + assert not widget.tracker.loaded + widget.tracker.on_scan_status(*status(scan_id="live")) # a live update comes first + release.set() + qtbot.waitUntil(lambda: widget.tracker.loaded, timeout=2000) + assert threading.main_thread().ident not in threads + assert widget.state.scan_id == "live" # the older stored status does not replace it + + +def test_opened_mid_scan_keeps_a_scan_that_is_still_queued(qtbot, mocked_client): + widget = opened_mid_scan(qtbot, mocked_client, {"status": status(), "queue": queue("s1")}) + assert not widget.state.finished + assert widget.state_chip.text() == "Running" + + +def stored_read(widget, **stored): + """Deliver the result of the background startup read to a widget's tracker.""" + msgs = {key: mock.MagicMock(content=v[0], metadata=v[1]) for key, v in stored.items()} + widget.tracker._on_initial_state(msgs) + + +def test_a_live_hook_does_not_stop_the_stored_status_and_progress(progress): + step(progress.tracker, "scan_core", 100.0) # the live hook comes before the startup read + assert progress.state.scan_number is None + stored_read( + progress, + status=status(num_points=20, user_metadata={"scan_name": "My Scan"}), + hook=hook("stage", 90.0), + progress=({"value": 7, "max_value": 20}, {"scan_id": "s1"}), + ) + assert progress.state.scan_number == 12 + assert progress.state.display_name == "My Scan" + assert progress.title_label.full_text() == "#12 My Scan" + assert progress.state.progress_value == 7 + assert progress.state.top_hook == "scan_core" # the stored hook is older than the live one + + +def test_a_live_status_keeps_its_values_over_the_stored_one(progress): + progress.tracker.on_scan_status(*status(scan_number=13)) + progress.tracker.on_scan_progress({"value": 9, "max_value": 20}, {"scan_id": "s1"}) + stored_read( + progress, + status=status(scan_number=12), + progress=({"value": 7, "max_value": 20}, {"scan_id": "s1"}), + ) + assert progress.state.scan_number == 13 + assert progress.state.progress_value == 9 + + +def test_live_progress_wins_over_the_stored_one_after_a_live_hook(progress): + step(progress.tracker, "scan_core", 100.0) + progress.tracker.on_scan_progress({"value": 9, "max_value": 20}, {"scan_id": "s1"}) + stored_read( + progress, + status=status(num_points=20), + progress=({"value": 7, "max_value": 20}, {"scan_id": "s1"}), + ) + assert progress.state.scan_number == 12 + assert progress.state.progress_value == 9 + + +def test_the_stored_status_of_another_scan_is_ignored(progress): + step(progress.tracker, "scan_core", 100.0, scan_id="s2") + stored_read(progress, status=status(scan_id="old")) + assert progress.state.scan_id == "s2" + assert progress.state.scan_number is None + + +def test_time_left_is_the_same_for_a_widget_that_saw_the_whole_scan(progress): + import time + + now = time.time() + progress.tracker.on_scan_status(*status(num_points=20)) + progress.tracker.on_scan_hook(*hook("scan_core", now, hook_started_at=now - 21.0)) + progress.tracker.on_scan_progress({"value": 7, "max_value": 20}, {"scan_id": "s1"}) + assert progress.state.remaining() == pytest.approx(39.0, abs=1.0) + + +def test_progress_of_a_scan_without_a_status_is_ignored(progress): + progress.tracker.on_scan_progress({"value": 3, "max_value": 10}, {"scan_id": "unseen"}) + assert progress.state is None + progress.tracker.on_scan_status(*status()) + progress.tracker.on_scan_progress({"value": 3, "max_value": 10}, {"scan_id": "unseen"}) + assert progress.state.scan_id == "s1" and progress.state.progress_value is None + + +def test_bar_fills_spare_height_and_scales_its_label(progress, qtbot): + progress.tracker.on_scan_status(*status(num_points=50)) + step(progress.tracker, "scan_core", 50.0) + progress.resize(900, 180) + progress.show() + qtbot.waitExposed(progress) + small_bar = progress.bar.height() + small_font = progress.bar.label_font(small_bar, progress.bar.width()).pointSizeF() + progress.resize(900, 420) + qtbot.waitUntil(lambda: progress.bar.height() > small_bar + 100, timeout=1000) + big_font = progress.bar.label_font(progress.bar.height(), progress.bar.width()).pointSizeF() + assert big_font > small_font + + progress.fill_height = False + qtbot.waitUntil(lambda: progress.bar.height() == progress.bar_height, timeout=1000) + + +def test_metadata_is_under_the_title_and_parameters_stay_a_tooltip(progress): + progress.tracker.on_scan_status(*status()) + layout = progress.layout() + assert layout.indexOf(progress.chips) == layout.indexOf(progress.header_row) + 1 + assert not progress.chips.isHidden() + assert "steps 50" in progress.header_row.toolTip() + progress.tracker.on_scan_status(*status(scan_id="s2", user_metadata={})) + assert progress.chips.isHidden() + + +def test_long_instruction_is_elided_with_the_full_text_as_tooltip(progress, qtbot): + step(progress.tracker, "pre_scan", 10.0) + long_text = "Moving " + ", ".join(f"motor_{i}" for i in range(30)) + label = progress.instruction_label + progress.resize(260, 220) + progress.show() + qtbot.waitExposed(progress) + label.setText(long_text) + assert label.text().endswith("…") + assert label.toolTip() == long_text + with mock.patch.object(label, "setToolTip") as set_tooltip: + label.setText(long_text) + set_tooltip.assert_not_called() + progress._render() + with mock.patch.object(label, "setToolTip") as set_tooltip: + progress._render() # nothing changed: no re-elide, no tooltip churn + set_tooltip.assert_not_called() + label.setText("Short") + assert label.text() == "Short" + assert label.toolTip() == "" + + +def test_bar_label_tooltip_only_when_cut(progress, qtbot): + progress.resize(200, 160) + progress.show() + qtbot.waitExposed(progress) + long_text = "Point 1 of 50 · 2% · 1:23:45 left and a very long tail that cannot fit" + progress.bar.set_state("progress", 0.1, long_text) + assert progress.bar.toolTip() == long_text + progress.bar.set_state("progress", 0.1, "1%") + assert progress.bar.toolTip() == "" + + +def test_stretched_stop_button_follows_the_bar_and_label_grows_gently(progress, qtbot): + progress.tracker.on_scan_status(*status(num_points=50)) + step(progress.tracker, "scan_core", 50.0) + progress.tracker.on_scan_progress( + {"value": 20, "max_value": 50, "done": False}, {"scan_id": "s1"} + ) + progress.resize(900, 150) + progress.show() + qtbot.waitExposed(progress) + bar, stop = progress.bar, progress.stop_button + min_bar = bar.bar_height + small_stop_font = progress._stop_base_size # px + base_text = bar.label_font(min_bar, bar.width()).pointSizeF() + + progress.resize(900, 520) + qtbot.waitUntil(lambda: bar.height() > 300, timeout=1000) + qtbot.waitUntil(lambda: abs(stop.height() - bar.height()) <= 2, timeout=1000) + assert bar.scale > 1.0 + assert stop.button.fontInfo().pixelSize() > small_stop_font + font = bar.label_font(bar.height(), bar.width()) + assert font.pointSizeF() > base_text + text_h = QFontMetricsF(font).height() + base_h = QFontMetricsF(bar.label_font(min_bar, bar.width())).height() + assert text_h - base_h <= 0.25 * (bar.height() - min_bar) + 1 + # a normal progress label still fits the bar width, so it is not elided + width = QFontMetricsF(font).horizontalAdvance(bar.text) + assert width <= bar.width() - bar.TEXT_PADDING + assert bar.toolTip() == "" + + progress.fill_height = False + qtbot.waitUntil(lambda: bar.height() == min_bar, timeout=1000) + assert bar.scale == 1.0 and not bar.stretched + assert stop.button.fontInfo().pixelSize() == small_stop_font + assert stop.button.height() == stop.arrow.height() == min_bar + + +def test_stop_button_can_be_hidden(progress, qtbot): + progress.tracker.on_scan_status(*status()) + progress.resize(420, 160) + progress.show() + qtbot.waitExposed(progress) + bar_width = progress.bar.width() + progress.show_stop_button = False + qtbot.waitUntil(lambda: progress.bar.width() > bar_width, timeout=1000) + assert progress.stop_button.isHidden() + progress.ask_stop() + progress._render() + assert progress.confirm_frame.isHidden() + assert progress.stop_button.isHidden() + + progress.show_stop_button = True + assert not progress.stop_button.isHidden() + assert progress.stop_button.isEnabled() + progress.ask_stop() + assert not progress.confirm_frame.isHidden() + progress.show_stop_button = False + assert progress.confirm_frame.isHidden() and progress.stop_button.isHidden() + + +def test_stop_button_hidden_from_the_constructor(qtbot, mocked_client): + widget = create_widget(qtbot, ScanProgressBar, client=mocked_client, show_stop_button=False) + assert widget.stop_button.isHidden() + + +def test_style_sheets_have_no_unknown_properties(qtbot, mocked_client): + from qtpy.QtCore import qInstallMessageHandler + + messages = [] + previous = qInstallMessageHandler(lambda _mode, _context, text: messages.append(text)) + try: + progress = create_widget(qtbot, ScanProgressBar, client=mocked_client) + progress.tracker.on_scan_status(*status()) + progress.resize(420, 300) + progress.show() + qtbot.waitExposed(progress) + progress.grab() + finally: + qInstallMessageHandler(previous) + assert "text-decoration-style" not in progress.step_times.styleSheet() + assert not [m for m in messages if "Unknown property" in m] + + +def test_tall_bar_label_and_stop_do_not_change_size_on_ticks(progress, qtbot): + from qtpy.QtCore import QEvent, QObject + + class ResizeCounter(QObject): + count = 0 + + def eventFilter(self, _obj, event): # pylint: disable=invalid-name + if event.type() == QEvent.Type.Resize: + self.count += 1 + return False + + progress.tracker.on_scan_status(*status(num_points=120)) + step(progress.tracker, "scan_core", 1.0) + progress.resize(560, 480) + progress.show() + qtbot.waitExposed(progress) + qtbot.wait(50) + counter = ResizeCounter() + progress.stop_button.installEventFilter(counter) + sizes, bar_geometries = [], set() + for tick in range(60): + progress.tracker.on_scan_progress( + {"value": tick * 2, "max_value": 120, "done": False}, {"scan_id": "s1"} + ) + qtbot.wait(2) + rect = progress.bar._bar_rect() + sizes.append( + progress.bar.label_font(rect.height(), progress.bar._label_width(rect)).pointSizeF() + ) + bar_geometries.add(progress.bar.geometry().getRect()) + font_changes = sum(1 for a, b in zip(sizes, sizes[1:]) if a != b) + assert font_changes <= 2 # only when the reserved label length grows + assert len(bar_geometries) <= font_changes + 1 + assert counter.count <= font_changes + 1 + # the label uses most of a tall bar's width but keeps some air at both ends + rect = progress.bar._bar_rect() + font = progress.bar.label_font(rect.height(), progress.bar._label_width(rect)) + width = QFontMetricsF(font).horizontalAdvance(progress.bar.text) + assert 0.55 * rect.width() <= width <= progress.bar.TEXT_WIDTH_SHARE * rect.width() + + +def test_docked_stop_keeps_a_small_share_and_the_bar_label_fits(progress, qtbot): + progress.tracker.on_scan_status(*status(num_points=50)) + step(progress.tracker, "scan_core", 1.0) + progress.resize(690, 260) + progress.show() + qtbot.waitExposed(progress) + progress.tracker.on_scan_status(*status(state="aborted")) + qtbot.wait(50) + row = progress._bar_row.geometry().width() + stop = progress.stop_button + assert stop.width() <= progress.STOP_ROW_MAX * row + 1 + rect = progress.bar._bar_rect() + font = progress.bar.label_font(rect.height(), progress.bar._label_width(rect)) + assert progress.bar.text.startswith("Aborted in Measuring") + width = QFontMetricsF(font).horizontalAdvance(progress.bar.text) + assert width <= rect.width() - progress.bar.TEXT_PADDING # not elided + + progress.tracker.on_scan_status(*status(scan_id="s2", state="open", num_points=50)) + step(progress.tracker, "scan_core", 2.0, scan_id="s2") + qtbot.wait(50) + before = progress.bar.geometry() + stop._activate_emergency_stop() + qtbot.wait(50) + assert progress.bar.geometry() == before # Emergency Stop does not move the bar + stop._deactivate_emergency_stop() + qtbot.wait(50) + assert progress.bar.geometry() == before + + +@pytest.mark.parametrize("size", [(420, 190), (620, 190), (690, 260), (900, 300)]) +def test_stop_never_clips_its_label(progress, qtbot, size): + progress.tracker.on_scan_status(*status(num_points=1000)) + step(progress.tracker, "scan_core", 1.0) + progress.resize(*size) + progress.show() + qtbot.waitExposed(progress) + qtbot.wait(50) + stop = progress.stop_button + button = stop.button + for emergency in (False, True): + if emergency: + stop._activate_emergency_stop() + qtbot.wait(20) + assert button.width() >= button.sizeHint().width(), button.text() + assert stop.width() >= button.sizeHint().width() + stop.arrow.width() - 1 + # measured with the polished font, the label keeps some room before the divider + with_icon = not button.icon().isNull() + assert button.width() >= stop.label_width(button.text(), with_icon) + 2, button.text() + stop._reset_timer.stop() + stop._deactivate_emergency_stop() + + +def test_unstretched_stop_has_the_bar_height_on_both_segments(qtbot, mocked_client): + widget = create_widget(qtbot, ScanProgressBar, client=mocked_client, fill_height=False) + widget.tracker.on_scan_status(*status(num_points=50)) + step(widget.tracker, "scan_core", 1.0) + widget.resize(520, 200) + widget.show() + qtbot.waitExposed(widget) + bar, stop = widget.bar, widget.stop_button + + def aligned(height): + parts = (stop.button, stop.arrow) + return all(part.height() == height and part.y() == stop.button.y() for part in parts) + + qtbot.waitUntil(lambda: aligned(bar.height()), timeout=1000) + assert bar.height() == bar.get_bar_height() + + widget.bar_height = 34 + qtbot.waitUntil(lambda: bar.height() == 34 and aligned(34), timeout=1000) + + # stretched the parts follow the tall bar; back to normal they take the bar height again + widget.resize(520, 400) + widget.fill_height = True + qtbot.waitUntil(lambda: bar.stretched and aligned(bar.height()), timeout=1000) + assert stop.button.height() > 34 + widget.fill_height = False + qtbot.waitUntil(lambda: not bar.stretched and aligned(34), timeout=1000) + + +def test_the_scan_is_shown_by_its_own_name(progress): + progress.tracker.on_scan_status(*status(user_metadata={"scan_name": "My Scan"})) + assert progress.title_label.full_text() == "#12 My Scan" + assert progress.header_row.toolTip().startswith("line_scan: samx -5 5") + progress.tracker.on_scan_status(*status(scan_id="s2", user_metadata={})) + assert progress.title_label.full_text() == "#12 line_scan" + assert not progress.header_row.toolTip().startswith("line_scan:") + + +def test_show_details_toggles_the_metadata_chips(progress, qtbot): + progress.show() + qtbot.waitExposed(progress) + progress.tracker.on_scan_status(*status()) + assert progress.chips.isVisible() + progress.setProperty("show_details", False) # as Designer and the property editor set it + assert not progress.chips.isVisible() + progress.show_details = True + assert progress.chips.isVisible() + progress.tracker.on_scan_status(*status(scan_id="s2", user_metadata={})) + assert not progress.chips.isVisible() # nothing to show without user metadata + + +def test_busy_stripes_run_at_10_hz_only_while_shown(progress, qtbot): + progress.show() + qtbot.waitExposed(progress) + timer = progress.bar._stripe_timer + step(progress.tracker, "prepare_scan", 100.0) + assert progress.bar.mode == BarMode.BUSY + assert timer.isActive() and timer.interval() == 100 + + progress.hide() assert not timer.isActive() - assert scan_progressbar.progress_tracker.task is None - assert scan_progressbar.progress_tracker._active_scan_id is None + step(progress.tracker, "stage", 101.0) # an update while hidden does not restart it + assert not timer.isActive() + progress.show() + qtbot.waitExposed(progress) + assert timer.isActive() + + progress.showMinimized() + qtbot.waitUntil(lambda: not timer.isActive()) + step(progress.tracker, "pre_scan", 102.0) + assert not timer.isActive() + progress.showNormal() + qtbot.waitUntil(timer.isActive) + + step(progress.tracker, "scan_core", 103.0) + progress.tracker.on_scan_progress({"value": 1, "max_value": 10}, {"scan_id": "s1"}) + assert progress.bar.mode == BarMode.PROGRESS and not timer.isActive() diff --git a/tests/unit_tests/test_scan_status_item.py b/tests/unit_tests/test_scan_status_item.py new file mode 100644 index 00000000..048e3b21 --- /dev/null +++ b/tests/unit_tests/test_scan_status_item.py @@ -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