diff --git a/bec_widgets/cli/client.py b/bec_widgets/cli/client.py index 6f48a5e9..28dc9011 100644 --- a/bec_widgets/cli/client.py +++ b/bec_widgets/cli/client.py @@ -480,7 +480,7 @@ class BECProgressBar(RPCBase): class BECQueue(RPCBase): - """Widget to display the BEC queue.""" + """Live scan queue with the running scan, the scans up next and the finished scans.""" _IMPORT_MODULE = "bec_widgets.widgets.services.bec_queue.bec_queue" diff --git a/bec_widgets/cli/designer_plugins.py b/bec_widgets/cli/designer_plugins.py index 14e1dc65..c7de9ac8 100644 --- a/bec_widgets/cli/designer_plugins.py +++ b/bec_widgets/cli/designer_plugins.py @@ -117,7 +117,7 @@ widget_icons = { "BECColorMapWidget": "palette", "BECMainWindow": "widgets", "BECProgressBar": "page_control", - "BECQueue": "edit_note", + "BECQueue": "view_list", "BECShell": "hub", "BECSpinBox": "123", "BECStatusBox": "widgets", diff --git a/bec_widgets/widgets/services/bec_queue/bec_queue.py b/bec_widgets/widgets/services/bec_queue/bec_queue.py index caf5bf9f..7563e50e 100644 --- a/bec_widgets/widgets/services/bec_queue/bec_queue.py +++ b/bec_widgets/widgets/services/bec_queue/bec_queue.py @@ -1,353 +1,953 @@ +""" +Scan queue: the running scan with its live progress, compact one-line lists of the scans up next +and the finished ones, and a drawer at the bottom with the selected scan's details and actions. +""" + from __future__ import annotations -import json +import time +from enum import StrEnum -from bec_lib import messages -from bec_lib.endpoints import MessageEndpoints -from bec_lib.logger import bec_logger -from bec_qthemes import material_icon -from qtpy.QtCore import Property, Qt, Signal, Slot -from qtpy.QtGui import QColor -from qtpy.QtWidgets import QHeaderView, QLabel, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget +from qtpy.QtCore import QEvent, QSize, Qt, QTimer +from qtpy.QtGui import QAction, QFont, QPainter, QPen +from qtpy.QtWidgets import ( + QFrame, + QHBoxLayout, + QLabel, + QMenu, + QMessageBox, + QPushButton, + QScrollArea, + QSplitter, + QSplitterHandle, + QVBoxLayout, + QWidget, +) -from bec_widgets.utils.bec_connector import ConnectionConfig from bec_widgets.utils.bec_widget import BECWidget -from bec_widgets.utils.error_popups import SafeSlot -from bec_widgets.utils.toolbars.actions import WidgetAction -from bec_widgets.utils.toolbars.bundles import ToolbarBundle -from bec_widgets.utils.toolbars.toolbar import ModularToolBar -from bec_widgets.widgets.control.buttons.button_abort.button_abort import AbortButton -from bec_widgets.widgets.control.buttons.button_reset.button_reset import ResetButton -from bec_widgets.widgets.control.buttons.button_resume.button_resume import ResumeButton -from bec_widgets.widgets.control.buttons.stop_button.stop_button import StopButton +from bec_widgets.utils.error_popups import SafeProperty, SafeSlot +from bec_widgets.utils.theme_utils import DPR_EVENTS, crisp_icon, css, theme_colors +from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar +from bec_widgets.widgets.progress.stage_bar import Chip, Tone, mono_font +from bec_widgets.widgets.services.bec_queue.queue_model import ( + QueueAction, + QueueEntry, + QueueMove, + ScanQueueModel, +) +from bec_widgets.widgets.services.bec_queue.queue_ui import ( + AnimatedRow, + CountBadge, + DetailGrid, + ElidedLabel, + GroupTitle, + IconButton, + KeyedRowList, + MoreButton, + StatusIcon, + entry_detail_columns, + finished_times, + finished_tooltip, + set_style, +) -logger = bec_logger.logger +PAUSE_TOOLTIP = "Pause the queue; the running scan pauses at its next safe point" + + +class ListRow(AnimatedRow): + """ + One line: position or status icon, name, the user metadata, the scan arguments (with + show_details on the queue, elided to the row) and, for finished scans, the duration. The + scan arguments are always the row's tooltip and are listed in full in the drawer. + """ + + def __init__(self, owner: "BECQueue", entry: QueueEntry, finished: bool): + super().__init__(entry.key) + self.finished = finished + self.setCursor(Qt.CursorShape.PointingHandCursor) + line = QHBoxLayout() + line.setSpacing(8) + if finished: + self.lead = StatusIcon(self, size=14) + else: + self.lead = QLabel(self) + self.lead.setFont(mono_font(-1)) + self.lead.setFixedWidth(20) + self.lead.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + self.name_label = QLabel(self) + self.name_label.setFont(mono_font(0, bold=not finished)) + self.meta_label = ElidedLabel(parent=self) + self.tail_label = QLabel(self) + self.tail_label.setFont(mono_font(-1)) + self.tail_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + line.addWidget(self.lead) + line.addWidget(self.name_label) + line.addWidget(self.meta_label, 1) + line.addWidget(self.tail_label) + self.buttons: list[IconButton] = [] + if finished: + self.rerun_button = IconButton( + "replay", "Run again with the same parameters", parent=self + ) + self.rerun_button.setFixedSize(22, 22) + self.rerun_button.setIconSize(QSize(16, 16)) + # clicking the button must not also select the row + self.rerun_button.clicked.connect(lambda: owner.rerun_scan(self.key)) + keep = self.rerun_button.sizePolicy() + keep.setRetainSizeWhenHidden(True) # rows keep their size while "Queued ✓" shows + self.rerun_button.setSizePolicy(keep) + self.buttons = [self.rerun_button] + line.addWidget(self.rerun_button) + else: + self.up_button = IconButton("arrow_upward", "Move up", parent=self) + self.down_button = IconButton("arrow_downward", "Move down", parent=self) + self.remove_button = IconButton( + "delete", "Remove from the queue", Tone.BAD, parent=self + ) + self.up_button.clicked.connect(lambda: owner.move_scan(self.key, QueueMove.UP)) + self.down_button.clicked.connect(lambda: owner.move_scan(self.key, QueueMove.DOWN)) + self.remove_button.clicked.connect(lambda: owner.remove_scan(self.key)) + self.buttons = [self.up_button, self.down_button, self.remove_button] + actions = QHBoxLayout() + actions.setSpacing(0) + for button in self.buttons: + button.setFixedSize(22, 22) + button.setIconSize(QSize(16, 16)) + actions.addWidget(button) + line.addLayout(actions) + self.body.addLayout(line) + self.clicked.connect(owner.select) + self.owner = owner + + def set_entry( + self, + entry: QueueEntry, + selected: bool, + requeued: bool = False, + index: int = 0, + count: int = 1, + ) -> None: + """Fill the row from an entry; index and count place a waiting row in its list.""" + colors = theme_colors() + muted = css(colors["muted"]) + if self.finished: + icon, tone, _ = entry.history_status + self.lead.set_status(icon, tone, finished_tooltip(entry)) + self.tail_label.setText("Queued ✓" if requeued else finished_times(entry)) + tail_color = css(colors["ok"]) if requeued else muted + self.rerun_button.setVisible(not requeued) + self.rerun_button.setEnabled(entry.can_rerun) + self.rerun_button.setToolTip( + "Run again with the same parameters" + if entry.can_rerun + else "Cannot run again: the original request is not known" + ) + else: + self.lead.setText(str(entry.position)) + set_style(self.lead, f"color: {muted};") + self.tail_label.setText("") + tail_color = muted + self.up_button.setEnabled(index > 0) + self.down_button.setEnabled(index < count - 1) + self.up_button.setToolTip("Move up") + self.down_button.setToolTip("Move down") + set_style(self.tail_label, f"color: {tail_color};") + self.tail_label.setVisible(bool(self.tail_label.text())) + self.name_label.setText(entry.title) + # a scan with its own name keeps its type visible, muted, before the metadata + scan_type = [entry.scan_type] if entry.scan_type and entry.scan_type != entry.name else [] + parts = scan_type + [value for _, value in entry.metadata] + if self.owner.show_details and entry.args: + parts.append(entry.args) + self.meta_label.setText(" · ".join(parts)) + set_style(self.meta_label, f"color: {muted};") + if self.toolTip() != entry.args: # also restores it after a failure note + self.setToolTip(entry.args) + self.set_selected(selected) + + +class _SplitHandle(QSplitterHandle): + """An invisible splitter handle that shows a faint line while hovered.""" + + def __init__(self, orientation, parent): + super().__init__(orientation, parent) + self.setAttribute(Qt.WidgetAttribute.WA_Hover) + + def event(self, event): # pylint: disable=invalid-name + if event.type() in (QEvent.Type.HoverEnter, QEvent.Type.HoverLeave): + self.update() + return super().event(event) + + def paintEvent(self, _event): # pylint: disable=invalid-name + if not self.underMouse() or self.orientation() != Qt.Orientation.Horizontal: + return + painter = QPainter(self) + painter.setPen(QPen(theme_colors()["border"], 1)) + x = self.width() // 2 + painter.drawLine(x, 0, x, self.height()) + painter.end() + + +class ColumnSplitter(QSplitter): + """The drawer's column splitter: a transparent, draggable boundary between the columns.""" + + HANDLE = 8 + + def __init__(self, parent: QWidget | None = None): + super().__init__(Qt.Orientation.Horizontal, parent) + self.setHandleWidth(self.HANDLE) + self.setChildrenCollapsible(False) + + def createHandle(self): # pylint: disable=invalid-name + return _SplitHandle(self.orientation(), self) + + +class DetailDrawer(QFrame): + """ + The drawer at the bottom: the selected scan's details and its actions. The details are two + columns, the scan arguments and the user metadata, stacked when the drawer is narrow. + """ + + STACK_BELOW = 360 + + def __init__(self, owner: "BECQueue"): + super().__init__(owner) + self.owner = owner + self.setObjectName("scan_queue_drawer") + layout = self._outer_layout = QVBoxLayout(self) + layout.setContentsMargins(12, 10, 12, 10) + layout.setSpacing(6) + head = QHBoxLayout() + head.setSpacing(6) + self.status_icon = StatusIcon(self, size=14) + self.label = QLabel(self) + head.addWidget(self.status_icon) + head.addWidget(self.label, 1) + self.close_button = IconButton("close", "Close details", parent=self) + self.close_button.setFixedSize(22, 22) + self.close_button.setIconSize(QSize(16, 16)) + self.close_button.clicked.connect(owner.clear_selection) + head.addWidget(self.close_button) + layout.addLayout(head) + self.name_label = QLabel(self) + self.name_label.setFont(mono_font(1.5, bold=True)) + self.name_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + layout.addWidget(self.name_label) + self.details = QWidget(self) + details_layout = QVBoxLayout(self.details) + details_layout.setContentsMargins(0, 2, 0, 0) + self.splitter = ColumnSplitter(self.details) + details_layout.addWidget(self.splitter) + self.args_box, self.args_grid = self._column("Arguments") + self.meta_box, self.meta_grid = self._column("Metadata", left_gap=True) + self.splitter.addWidget(self.args_box) + self.splitter.addWidget(self.meta_box) + self.splitter.splitterMoved.connect(self._on_splitter_moved) + self._arranged: tuple | None = None + self._is_stacked = False + self._dragged_args_width: int | None = None # kept while this drawer lives + self._arranging = False + layout.addWidget(self.details) + + self.waiting_actions = QWidget(self) + actions = QHBoxLayout(self.waiting_actions) + actions.setContentsMargins(0, 2, 0, 0) + actions.setSpacing(6) + self.up_button = self._button("arrow_upward", "Up") + self.down_button = self._button("arrow_downward", "Down") + self.top_button = self._button("vertical_align_top", "To top") + self.remove_button = self._button("delete", "Remove", danger=True) + self.up_button.clicked.connect(lambda: owner.move_scan(owner.selected_key, QueueMove.UP)) + self.down_button.clicked.connect( + lambda: owner.move_scan(owner.selected_key, QueueMove.DOWN) + ) + self.top_button.clicked.connect(lambda: owner.move_scan(owner.selected_key, QueueMove.TOP)) + self.remove_button.clicked.connect(lambda: owner.remove_scan(owner.selected_key)) + for button in (self.up_button, self.down_button, self.top_button): + actions.addWidget(button) + actions.addStretch(1) + actions.addWidget(self.remove_button) + layout.addWidget(self.waiting_actions) + + self.finished_actions = QWidget(self) + factions = QHBoxLayout(self.finished_actions) + factions.setContentsMargins(0, 2, 0, 0) + self.rerun_button = self._button("replay", "Run again with these parameters") + self.rerun_button.clicked.connect(lambda: owner.rerun_scan(owner.selected_key)) + self.queued_label = QLabel("Added to Up next ✓", self) + factions.addWidget(self.rerun_button) + factions.addWidget(self.queued_label) + factions.addStretch(1) + layout.addWidget(self.finished_actions) + + self.hint = QLabel("Select a scan to see its arguments, metadata and actions.", self) + self.hint.setWordWrap(True) + layout.addWidget(self.hint) + self.refresh_style() + self.show_entry(None) + + def _column(self, title: str, left_gap: bool = False) -> tuple[QWidget, DetailGrid]: + box = QWidget(self.details) + box.setMinimumWidth(40) + column = QVBoxLayout(box) + # the splitter handle plus this margin make the gap between the columns + gap = self.COLUMN_GAP - ColumnSplitter.HANDLE if left_gap else 0 + column.setContentsMargins(gap, 0, 0, 0) + column.setSpacing(3) + column.addWidget(GroupTitle(title, box)) + grid = DetailGrid(box) + column.addWidget(grid) + column.addStretch(1) + return box, grid + + COLUMN_GAP = 16 + + def column_widths(self, width: int) -> tuple[bool, int, int]: + """ + Decide the layout for a drawer content width: (stacked, args width, metadata width). + + The arguments get their natural width and the metadata follows after a gap, packed to + the left, with the rest of the width. Only when both do not fit, a column narrower + than half keeps its natural width and the other gets the rest, else both get half. + Stacked when the drawer is narrow, or when side by side would cut argument values + that stacked fit. A position the user dragged the splitter to wins while it fits. + """ + args_n = self.args_grid.natural_width() + meta_n = self.meta_grid.natural_width() if not self.meta_box.isHidden() else 0 + if not meta_n: + return False, width, 0 + gap = self.COLUMN_GAP + if args_n + gap + meta_n <= width: + args_w = args_n + else: + half = (width - gap) // 2 + if meta_n <= half: + args_w = width - gap - meta_n + elif args_n <= half: + args_w = args_n + else: + args_w = half + stacked = width < self.STACK_BELOW or (args_w < args_n and args_n <= width) + if stacked: + return True, width, width + if self._dragged_args_width is not None: + args_w = max(40, min(self._dragged_args_width, width - gap - 40)) + return False, args_w, width - gap - args_w + + def _arrange_columns(self) -> None: + """Lay the columns out for the current width and content; no-op when nothing changed.""" + margins = self._outer_layout.contentsMargins() + width = max(0, self.width() - margins.left() - margins.right()) + content = (self.args_grid.natural_width(), self.meta_grid.natural_width()) + key = (width, content, self.meta_box.isHidden(), self._dragged_args_width) + if key == self._arranged: + return + self._arranged = key + stacked, args_w, meta_w = self.column_widths(width) + self._is_stacked = stacked + self._arranging = True + try: + if stacked: + self.splitter.setOrientation(Qt.Orientation.Vertical) + self.splitter.setSizes( + [self.args_box.sizeHint().height(), self.meta_box.sizeHint().height()] + ) + else: + self.splitter.setOrientation(Qt.Orientation.Horizontal) + handle = self.splitter.handleWidth() + self.splitter.setSizes([args_w, max(0, width - args_w - handle)]) + finally: + self._arranging = False + self.args_grid.fit_keys(args_w) + self.meta_grid.fit_keys(meta_w or width) + + @SafeSlot(int, int) + def _on_splitter_moved(self, _pos: int, _index: int) -> None: + if self._arranging or self._is_stacked: + return + self._dragged_args_width = self.splitter.sizes()[0] + self.args_grid.fit_keys(self.args_box.width()) + self.meta_grid.fit_keys(self.meta_box.width()) + + @property + def stacked(self) -> bool: + """Whether the metadata column sits under the arguments.""" + return self._is_stacked + + def resizeEvent(self, event): # pylint: disable=invalid-name + super().resizeEvent(event) + self._arrange_columns() + + def event(self, event): # pylint: disable=invalid-name + if event.type() in DPR_EVENTS: + self.refresh_style() # re-render the button icons for the new screen + return super().event(event) + + def _button(self, icon: str, text: str, danger: bool = False) -> QPushButton: + button = QPushButton(text, self) + button.setProperty("_icon", icon) + button.setProperty("_danger", danger) + button.setIconSize(QSize(16, 16)) + button.setCursor(Qt.CursorShape.PointingHandCursor) + return button + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + colors = theme_colors() + self.setStyleSheet( + f"#scan_queue_drawer {{ background: {css(colors['card'])};" + f" border-top: 1px solid {css(colors['border'])}; }}" + ) + self.label.setStyleSheet(f"color: {css(colors['muted'])};") + self.hint.setStyleSheet(f"color: {css(colors['muted'])};") + self.queued_label.setStyleSheet(f"color: {css(colors['ok'])}; font-weight: 600;") + for button in self.findChildren(QPushButton): + danger = bool(button.property("_danger")) + color = colors["bad"] if danger else colors["fg"] + button.setIcon(crisp_icon(button.property("_icon"), 16, color, widget=button)) + if danger: + button.setStyleSheet(f"color: {css(colors['bad'])};") + + def show_entry(self, entry: QueueEntry | None, finished: bool = False, **state) -> None: + """Show an entry, or the hint when nothing is selected.""" + has = entry is not None + self.close_button.setVisible(has) + for widget in (self.name_label, self.details, self.label): + widget.setVisible(has) + self.hint.setVisible(not has) + self.status_icon.setVisible(has and finished) + self.waiting_actions.setVisible(has and not finished) + self.finished_actions.setVisible(has and finished) + if not has: + return + self.name_label.setText(entry.title) + arguments, metadata = entry_detail_columns(entry) + self.args_grid.set_items(arguments) + self.meta_grid.set_items(metadata) + self.meta_box.setVisible(bool(metadata)) + self._arrange_columns() + if finished: + icon, tone, _ = entry.history_status + self.status_icon.set_status(icon, tone, finished_tooltip(entry)) + self.label.setText(f"Finished · {finished_tooltip(entry)}") + requeued = state.get("requeued", False) + self.rerun_button.setVisible(not requeued) + self.rerun_button.setEnabled(entry.can_rerun) + self.queued_label.setVisible(requeued) + else: + index, count = state.get("index", 0), state.get("count", 1) + self.label.setText(f"Waiting · position {entry.position} of {count}") + self.up_button.setEnabled(index > 0) + self.top_button.setEnabled(index > 0) + self.down_button.setEnabled(index < count - 1) + + +class PauseState(StrEnum): + """What the pause button of the queue offers.""" + + RUNNING = "running" # a scan runs: pause the queue + PAUSING = "pausing" # a pause was asked for and has not landed yet + PAUSED = "paused" # resume the queue + IDLE = "idle" # nothing runs: disabled class BECQueue(BECWidget, QWidget): """ - Widget to display the BEC queue. + Live scan queue with the running scan, the scans up next and the finished scans. + + The running scan shows its live progress; every scan up next and every finished scan is one + compact line, and a drawer at the bottom shows the selected scan's details and actions. """ PLUGIN = True - ICON_NAME = "edit_note" - status_colors = { - "STOPPED": "red", - "PENDING": "orange", - "IDLE": "gray", - "PAUSED": "yellow", - "DEFERRED_PAUSE": "lightyellow", - "RUNNING": "green", - "COMPLETED": "blue", - } + RPC = True + ICON_NAME = "view_list" - queue_busy = Signal(bool) + REMOVE_GRACE_S = 5.0 + QUEUED_NOTE_S = 3.0 + FAILURE_SHOWN_MS = 4000 + PAUSE_TEXTS = ("Pause queue", "Resume queue", "Pausing…") + PAUSE_PENDING_S = 10.0 - def __init__( - self, - parent: QWidget | None = None, - client=None, - config: ConnectionConfig = None, - gui_id: str = None, - refresh_upon_start: bool = True, - **kwargs, - ): - super().__init__(parent=parent, client=client, gui_id=gui_id, config=config, **kwargs) - self.main_layout = QVBoxLayout(self) - self.main_layout.setSpacing(0) - self.main_layout.setContentsMargins(0, 0, 0, 0) - self._toolbar_hidden = False + def __init__(self, parent: QWidget | None = None, client=None, config=None, gui_id=None, **kw): + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kw) + self.get_bec_shortcuts() + self.setMinimumWidth(300) + self.selected_key: str | None = None + self._show_details = True + self._waiting_index: dict[str, int] = {} + self._removing: dict[str, float] = {} + self._flash_next: dict[str, str] = {} + self._requeued: dict[str, float] = {} + self._new_rid: str | None = None + self._last_moved: list[str] = [] - # Set up the toolbar - self.set_toolbar() - # Set up the table - self.table = QTableWidget(self) - self.table.setColumnCount(5) - self.table.setHorizontalHeaderLabels( - ["Scan Number", "Scan Name", "Type", "Status", "Cancel"] + self.model = ScanQueueModel(self.client, self.bec_dispatcher, parent=self) + + self._outer = QVBoxLayout(self) + self._outer.setContentsMargins(0, 0, 0, 0) + self._outer.setSpacing(0) + self._build_header() + + self.scroll = QScrollArea(self) + self.scroll.setWidgetResizable(True) + self.scroll.setFrameShape(QFrame.Shape.NoFrame) + self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.content = QWidget(self.scroll) + self.content.setObjectName("scan_queue_content") + # click focus on the children, so Esc reaches the queue; a dock area profile restores + # the focusPolicy of the queue itself from the file + self.content.setFocusPolicy(Qt.FocusPolicy.ClickFocus) + self.content_layout = QVBoxLayout(self.content) + self.content_layout.setContentsMargins(10, 6, 10, 10) + self.content_layout.setSpacing(8) + self.scroll.setWidget(self.content) + self._outer.addWidget(self.scroll, 1) + + self.running_card = QFrame(self.content) + self.running_card.setObjectName("scan_queue_running") + running_layout = QVBoxLayout(self.running_card) + running_layout.setContentsMargins(0, 0, 0, 0) + self.progress = ScanProgressBar( + parent=self.running_card, client=self.client, fill_height=False + ) + running_layout.addWidget(self.progress) + + self._build_lists() + # a refused action is shown in the "Up next" hint for a while; nothing pops over the list + self._failure = "" + self._failure_timer = QTimer(self) + self._failure_timer.setSingleShot(True) + self._failure_timer.setInterval(self.FAILURE_SHOWN_MS) + self._failure_timer.timeout.connect(self._clear_failure) + self._expire_timer = QTimer(self) + self._expire_timer.setInterval(1000) + self._expire_timer.timeout.connect(self._expire_notes) + + self.model.changed.connect(self._on_model_changed) + self.model.action_sent.connect(self._on_action_sent) + self.model.action_failed.connect(self._on_action_failed) + self._apply_styles() + self.model.start() + # the queue is read in the background; until it lands, show no "empty" or "ready" state + self._render_header() + self.waiting_empty.hide() + + ################################################################################ + # Building + ################################################################################ + + def _build_header(self) -> None: + self.header = QFrame(self) + self.header.setObjectName("scan_queue_header") + layout = QHBoxLayout(self.header) + layout.setContentsMargins(12, 8, 8, 8) + layout.setSpacing(8) + self.title_label = QLabel("Scan queue", self.header) + self.title_label.setStyleSheet("font-weight: 600; font-size: 14px;") + self.queue_chip = Chip("Loading", Tone.NEUTRAL, self.header) + self.pause_button = QPushButton(self.header) + self.pause_button.setObjectName("scan_queue_pause") + self.pause_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.pause_button.setFixedHeight(26) + self.pause_button.setIconSize(QSize(16, 16)) + font = QFont(self.pause_button.font()) + font.setPixelSize(12) + font.setWeight(QFont.Weight.DemiBold) + self.pause_button.setFont(font) + metrics = self.pause_button.fontMetrics() + widest = max(metrics.horizontalAdvance(t) for t in self.PAUSE_TEXTS) + self.pause_button.setMinimumWidth(widest + 16 + 6 + 2 * 10 + 4) # text, icon, padding + self.pause_button.clicked.connect(self._toggle_pause) + self._pause_state: PauseState | None = None + self._pause_requested_at: float | None = None + self._pause_timeout = QTimer(self) + self._pause_timeout.setSingleShot(True) + self._pause_timeout.setInterval(int(self.PAUSE_PENDING_S * 1000)) + self._pause_timeout.timeout.connect(self._render_header) + layout.addWidget(self.title_label) + layout.addWidget(self.queue_chip) + layout.addStretch(1) + layout.addWidget(self.pause_button) + # actions that are rarely needed and cannot be undone sit in a menu, out of the way + self.more_button = MoreButton("More queue actions", parent=self.header) + self.more_button.setFocusPolicy(Qt.FocusPolicy.TabFocus) # keyboard: Tab, then Space + more_menu = QMenu(self.more_button) + self.reset_action = QAction("Reset queue…", more_menu) + self.reset_action.setToolTip( + "Stop the running scan and remove all waiting scans; asks for confirmation" + ) + self.reset_action.triggered.connect(self.ask_reset) + more_menu.addAction(self.reset_action) + self.more_button.setMenu(more_menu) + layout.addWidget(self.more_button) + self._outer.addWidget(self.header) + + def _group_header(self, title: str, badge: bool = False) -> tuple[QWidget, CountBadge | None]: + row = QWidget(self.content) + layout = QHBoxLayout(row) + layout.setContentsMargins(2, 4, 2, 0) + layout.setSpacing(6) + layout.addWidget(GroupTitle(title, row)) + count = None + if badge: + count = CountBadge(row) + layout.addWidget(count) + layout.addStretch(1) + row.hint = QLabel(row) + layout.addWidget(row.hint) + self._group_hints.append(row.hint) + return row, count + + def _build_lists(self) -> None: + self._group_hints: list[QLabel] = [] + layout = self.content_layout + running_header, _ = self._group_header("Running") + layout.addWidget(running_header) + layout.addWidget(self.running_card) + next_header, self.waiting_badge = self._group_header("Up next", badge=True) + self.waiting_hint = next_header.hint + layout.addWidget(next_header) + self.waiting_empty = QLabel("No scans waiting.", self.content) + layout.addWidget(self.waiting_empty) + self.waiting_rows = KeyedRowList( + lambda e: ListRow(self, e, finished=False), self._update_waiting, self.content, 1 + ) + layout.addWidget(self.waiting_rows) + self.finished_rule = QFrame(self.content) + self.finished_rule.setObjectName("scan_queue_rule") + self.finished_rule.setFixedHeight(1) + layout.addSpacing(4) + layout.addWidget(self.finished_rule) + self.finished_header, self.finished_badge = self._group_header("Finished", badge=True) + layout.addWidget(self.finished_header) + self.finished_rows = KeyedRowList( + lambda e: ListRow(self, e, finished=True), self._update_finished, self.content, 1 + ) + layout.addWidget(self.finished_rows) + layout.addStretch(1) + self.drawer = DetailDrawer(self) + self.drawer.setFocusPolicy(Qt.FocusPolicy.ClickFocus) + self._outer.addWidget(self.drawer) + + def _apply_styles(self) -> None: + colors = theme_colors() + self.header.setStyleSheet( + f"#scan_queue_header {{ border-bottom: 1px solid {css(colors['border'])}; }}" + ) + self.running_card.setStyleSheet( + f"#scan_queue_running {{ background: {css(colors['card'])};" + f" border: 1px solid {css(colors['border'])}; border-radius: 8px; }}" + ) + self.waiting_empty.setStyleSheet(f"color: {css(colors['muted'])}; padding: 6px 4px;") + for hint in self._group_hints: + hint.setStyleSheet(f"color: {css(colors['muted'])}; font-size: 11px;") + self.finished_rule.setStyleSheet( + f"#scan_queue_rule {{ background: {css(colors['border'])}; border: none; }}" ) - header = self.table.horizontalHeader() - header.setSectionResizeMode(QHeaderView.Stretch) + def apply_theme(self, theme: str): + """Restyle after a theme change.""" + self._apply_styles() + for widget in self.findChildren(QWidget): + refresh = getattr(widget, "refresh_style", None) + if callable(refresh): + refresh() + self._pause_state = None # restyle the pause button even though its state is the same + self._render_header() + self._render() - self.main_layout.addWidget(self.table) + ################################################################################ + # Properties + ################################################################################ - self.bec_dispatcher.connect_slot(self.update_queue, MessageEndpoints.scan_queue_status()) - self.reset_content() - if refresh_upon_start: - self.refresh_queue() - - def set_toolbar(self): + @SafeProperty(bool) + def show_details(self) -> bool: """ - Set the toolbar. + Show the scan arguments in the rows, after the user metadata, elided to the row. They + stay in the row's tooltip and in the drawer either way. """ - widget_label = QLabel(text="Live Queue", parent=self) - widget_label.setStyleSheet("font-weight: bold;") - self.toolbar = ModularToolBar(parent=self) - self.toolbar.components.add_safe("widget_label", WidgetAction(widget=widget_label)) - bundle = ToolbarBundle("queue_label", self.toolbar.components) - bundle.add_action("widget_label") - self.toolbar.add_bundle(bundle) + return self._show_details - self.toolbar.add_action( - "resume", WidgetAction(widget=ResumeButton(parent=self, toolbar=True)) - ) - self.toolbar.add_action("stop", WidgetAction(widget=StopButton(parent=self, toolbar=True))) - self.toolbar.add_action( - "reset", WidgetAction(widget=ResetButton(parent=self, toolbar=True)) - ) + @show_details.setter + def show_details(self, show: bool) -> None: + self._show_details = show + self._render() - control_bundle = ToolbarBundle("control", self.toolbar.components) - control_bundle.add_action("resume") - control_bundle.add_action("stop") - control_bundle.add_action("reset") - self.toolbar.add_bundle(control_bundle) - self.toolbar.show_bundles(["queue_label", "control"]) + ################################################################################ + # Model + ################################################################################ - self.main_layout.addWidget(self.toolbar) + def waiting_entries(self) -> list[QueueEntry]: + """Waiting entries, without those being removed right now.""" + now = time.monotonic() + self._removing = {k: t for k, t in self._removing.items() if now - t < self.REMOVE_GRACE_S} + return [e for e in self.model.waiting if e.key not in self._removing] - @Property(bool) - def hide_toolbar(self): - """Property to hide the BEC Queue toolbar.""" - return self._toolbar_hidden - - @hide_toolbar.setter - def hide_toolbar(self, hide: bool): - """ - Setters for the hide_toolbar property. - - Args: - hide(bool): Whether to hide the toolbar. - """ - self._hide_toolbar(hide) - - def _hide_toolbar(self, hide: bool): - """ - Hide the toolbar. - - Args: - hide(bool): Whether to hide the toolbar. - """ - self._toolbar_hidden = hide - self.toolbar.setVisible(not hide) - - def refresh_queue(self): - """ - Refresh the queue. - """ - msg = self.client.connector.get(MessageEndpoints.scan_queue_status()) - if msg is None: - # msg is None if no scan has been run yet (fresh start) - return - self.update_queue(msg.content, msg.metadata) - - @Slot(dict, dict) - def update_queue(self, content, _metadata): - """ - Update the queue table with the latest queue information. - - Args: - content (dict): The queue content. - _metadata (dict): The metadata. - """ - # only show the primary queue for now - queues = content.get("queue", {}) - if not queues: - self.reset_content() - return - primary_queue: messages.ScanQueueStatus | None = queues.get("primary") - if not primary_queue: - self.reset_content() - return - queue_info = primary_queue.info - - self.table.setRowCount(len(queue_info)) - self.table.clearContents() - - if not queue_info: - self.reset_content() - return - - for index, item in enumerate(queue_info): - blocks = item.request_blocks - scan_types = [] - scan_numbers = [] - scan_names = [] - user_metadatas = [] - request_ids = [] - status = item.status - for request_block in blocks: - scan_type = request_block.msg.scan_type - user_metadata = request_block.msg.metadata.get("user_metadata", {}) - scan_name = user_metadata.get("scan_name", scan_type) - if scan_type: - scan_types.append(scan_type) - scan_number = request_block.scan_number - if scan_number: - scan_numbers.append(str(scan_number)) - if scan_name: - scan_names.append(scan_name) - if user_metadata: - user_metadatas.append(user_metadata) - if request_block.RID: - request_ids.append(request_block.RID) - if scan_types: - scan_types = ", ".join(scan_types) - if scan_numbers: - scan_numbers = ", ".join(scan_numbers) - if scan_names: - scan_names = ", ".join(scan_names) - # Pretty print user metadata as tooltip - tooltip = "" - if user_metadatas: - if len(user_metadatas) == 1: - tooltip = json.dumps(user_metadatas[0], indent=2) - else: - tooltip = json.dumps(user_metadatas, indent=2) - self.set_row( - index, - scan_numbers, - scan_names, - scan_types, - status, - tooltip, - abort_request_id=request_ids[0] if request_ids else "", - ) - busy = ( - False - if all(item.status in ("STOPPED", "COMPLETED", "IDLE") for item in queue_info) - else True - ) - self.queue_busy.emit(busy) - - def format_item(self, content: str, status=False, tooltip: str = "") -> QTableWidgetItem: - """ - Format the content of the table item. - - Args: - content (str): The content to be formatted. - tooltip (str): Optional tooltip to display. - Returns: - QTableWidgetItem: The formatted item. - """ - if not content or not isinstance(content, str): - content = "" - item = QTableWidgetItem(content) - item.setTextAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter) - if tooltip: - item.setToolTip(tooltip) - - if status: - try: - color = self.status_colors.get(content, "black") # Default to black if not found - item.setForeground(QColor(color)) - except Exception as e: - logger.warning(f"Could not apply status color for queue item '{content}': {e}") - return item - - def set_row( - self, - index: int, - scan_number: str, - scan_name: str, - scan_type: str, - status: str, - tooltip: str = "", - abort_request_id: str = "", - ): - """ - Set the row of the table. - - Args: - index (int): The index of the row. - scan_number (str): The scan number. - scan_name (str): The scan name. - scan_type (str): The scan type. - status (str): The status. - tooltip (str): Optional tooltip to display (pretty-printed user metadata). - abort_request_id (str): Request id to abort. Rows without one, such as the - empty-queue placeholder, get no abort button. - """ - self.table.setItem(index, 0, self.format_item(scan_number, tooltip=tooltip)) - self.table.setItem(index, 1, self.format_item(scan_name, tooltip=tooltip)) - self.table.setItem(index, 2, self.format_item(scan_type, tooltip=tooltip)) - self.table.setItem(index, 3, self.format_item(status, status=True, tooltip=tooltip)) - - if not abort_request_id: - # Nothing to target. Never fall back to request_id=None: AbortButton treats it as - # "abort the current request", which would hit a scan this row does not show. - self.table.removeCellWidget(index, 4) - return - abort_button = self._create_abort_button(abort_request_id) - abort_button.button.clicked.connect(self.delete_selected_row) - self.table.setCellWidget(index, 4, abort_button) - - def _create_abort_button(self, request_id: str) -> AbortButton: - """ - Create an abort button with styling for BEC Queue widget for certain request_id. - - Args: - request_id(str): The request id to abort. - - Returns: - AbortButton: The abort button. - """ - abort_button = AbortButton(parent=self, request_id=request_id) - - abort_button.button.setText("") - abort_button.button.setIcon( - material_icon("cancel", color="#cc181e", filled=True, convert_to_pixmap=False) - ) - abort_button.setStyleSheet(""" - QPushButton { - background-color: transparent; - border: none; - } - """) - - return abort_button + def is_requeued(self, key: str) -> bool: + """Whether this finished entry was queued again in the last seconds.""" + stamp = self._requeued.get(key) + return stamp is not None and time.monotonic() - stamp < self.QUEUED_NOTE_S @SafeSlot() - def delete_selected_row(self): - """ - Remove the table row whose abort button was clicked. + def _on_model_changed(self) -> None: + self._render_header() + self._render() + self._flash_after_sync() - The signal is emitted by the inner button of an AbortButton cell widget, whose position is - relative to that cell widget and cannot be mapped to a table row. The row is therefore - resolved by looking up which row holds the clicked AbortButton. Removing the row also - deletes its cell widget. - """ - abort_button = self._find_abort_button(self.sender()) - if abort_button is None: + def _render_header(self) -> None: + model = self.model + if model.paused: + self.queue_chip.setText("Paused") + self.queue_chip.set_tone(Tone.WARN) + elif model.running is not None: + self.queue_chip.setText("Running") + self.queue_chip.set_tone(Tone.RUN) + elif not model.loaded: + self.queue_chip.setText("Loading") + self.queue_chip.set_tone(Tone.NEUTRAL) + else: + self.queue_chip.setText("Ready") + self.queue_chip.set_tone(Tone.OK) + self._style_pause_button(self.pause_state()) + self.reset_action.setEnabled(model.running is not None or bool(model.waiting)) + + def pause_state(self) -> PauseState: + """running, pausing, paused or idle: what the pause button offers.""" + model = self.model + if model.paused: + self._pause_requested_at = None + return PauseState.PAUSED + requested = self._pause_requested_at + if requested is not None and time.monotonic() - requested < self.PAUSE_PENDING_S: + return PauseState.PAUSING + self._pause_requested_at = None + return PauseState.RUNNING if model.running is not None else PauseState.IDLE + + def _style_pause_button(self, state: PauseState) -> None: + """Restyle the pause button only when its state changes.""" + if state == self._pause_state: return - for row in range(self.table.rowCount()): - if self.table.cellWidget(row, 4) is abort_button: - self.table.removeRow(row) - return + self._pause_state = state + colors = theme_colors() + button = self.pause_button + if state == PauseState.PAUSED: + text, icon, tooltip = "Resume queue", "play_arrow", "Resume the queue" + icon_color = colors["on_primary"] + sheet = ( + f"#scan_queue_pause {{ background: {css(colors['primary'])};" + f" color: {css(colors['on_primary'])}; border: 1px solid {css(colors['primary'])};" + " border-radius: 6px; padding: 0 10px; }" + f"#scan_queue_pause:hover {{ background: {css(colors['primary'], 0.85)}; }}" + ) + else: + text = "Pausing…" if state == PauseState.PAUSING else "Pause queue" + icon, tooltip = "pause", PAUSE_TOOLTIP + icon_color = colors["warn"] if state == PauseState.RUNNING else colors["muted"] + sheet = ( + f"#scan_queue_pause {{ background: transparent; color: {css(colors['fg'])};" + f" border: 1px solid {css(colors['warn'], 0.8)}; border-radius: 6px;" + " padding: 0 10px; }" + f"#scan_queue_pause:hover {{ background: {css(colors['warn'], 0.12)}; }}" + f"#scan_queue_pause:disabled {{ color: {css(colors['muted'])};" + f" border-color: {css(colors['border'])}; }}" + ) + button.setText(text) + button.setToolTip(tooltip) + button.setIcon(crisp_icon(icon, 16, icon_color, widget=button)) + button.setStyleSheet(sheet) + button.setEnabled(state in (PauseState.RUNNING, PauseState.PAUSED)) + self.pause_icon_name = icon - @staticmethod - def _find_abort_button(widget: QWidget | None) -> AbortButton | None: - """ - Return the AbortButton that contains the given widget. + def _flash_after_sync(self) -> None: + rows = self.waiting_rows + for key, tone in list(self._flash_next.items()): + row = rows.row(key) + if row is None: + del self._flash_next[key] + elif key in self._last_moved: + row.flash(tone) + del self._flash_next[key] + if self._new_rid: + for entry in self.model.waiting: + if entry.rid == self._new_rid: + row = rows.row(entry.key) + if row is not None and not row.flashing: + row.flash(Tone.ACCENT) + self._new_rid = None + break - Args: - widget(QWidget | None): The widget that emitted the signal, typically the inner button - of an AbortButton. + ################################################################################ + # Selection and rendering + ################################################################################ - Returns: - AbortButton | None: The enclosing AbortButton, or None if there is none. - """ - while widget is not None and not isinstance(widget, AbortButton): - widget = widget.parent() - return widget + @SafeSlot() + def clear_selection(self) -> None: + """Close the details: nothing selected, no row highlighted.""" + if self.selected_key is not None: + self.selected_key = None + self._render() - def reset_content(self): - """ - Reset the content of the table. - """ + def keyPressEvent(self, event): # pylint: disable=invalid-name + if event.key() == Qt.Key.Key_Escape and self.selected_key is not None: + self.clear_selection() + return + super().keyPressEvent(event) - self.table.setRowCount(1) - self.set_row(0, "", "", "", "", "") + @SafeSlot(str) + def select(self, key: str) -> None: + """Select a scan and show it in the drawer; selecting it again clears the selection.""" + self.selected_key = None if key == self.selected_key else key + self._render() + + def _update_waiting(self, row: ListRow, entry: QueueEntry) -> None: + index = self._waiting_index.get(entry.key, 0) + selected = entry.key == self.selected_key + row.set_entry(entry, selected, index=index, count=len(self._waiting_index)) + + def _update_finished(self, row: ListRow, entry: QueueEntry) -> None: + row.set_entry(entry, entry.key == self.selected_key, self.is_requeued(entry.key)) + + def _render(self) -> None: + waiting = self.waiting_entries() + self._waiting_index = {e.key: i for i, e in enumerate(waiting)} + finished = self.model.finished + self.waiting_badge.setText(str(len(waiting))) + self.waiting_hint.setText(self.reorder_hint()) + self.waiting_empty.setVisible(self.model.loaded and not waiting) + self._last_moved = self.waiting_rows.sync(waiting) + self.finished_badge.setText(str(len(finished))) + self.finished_rows.sync(finished, animate=False) + + index = next((i for i, e in enumerate(waiting) if e.key == self.selected_key), -1) + if index >= 0: + self.drawer.show_entry(waiting[index], index=index, count=len(waiting)) + return + entry = next((e for e in finished if e.key == self.selected_key), None) + if entry is not None: + self.drawer.show_entry(entry, finished=True, requeued=self.is_requeued(entry.key)) + return + if self.selected_key is not None and self.selected_key not in self._removing: + self.selected_key = None + self.drawer.show_entry(None) + + ################################################################################ + # Actions + ################################################################################ + + @SafeSlot(str, object) + def move_scan(self, key: str, action: QueueMove | str) -> None: + """Reorder a waiting scan (up, down, top, bottom).""" + self.model.move(key, action) + + @SafeSlot(str) + def remove_scan(self, key: str) -> None: + """Remove a waiting scan, animating its row out.""" + self.model.remove(key) + + @SafeSlot(str) + def rerun_scan(self, key: str) -> None: + """Queue a finished scan again with the same parameters.""" + self.model.rerun(key) + + def reset_text(self) -> str: + """What a reset does to the queue as it is now, for the confirmation.""" + model = self.model + parts = [] + if model.running is not None: + parts.append(f"stops the running scan {model.running.title} and its devices") + waiting = len(self.waiting_entries()) + if waiting: + parts.append(f"removes the {waiting} waiting scan{'s' if waiting != 1 else ''}") + what = " and ".join(parts) or "clears the queue" + return f"Resetting the queue {what}. This cannot be undone." + + @SafeSlot() + def ask_reset(self) -> None: + """Reset the queue after the user confirmed it in a dialog.""" + box = QMessageBox(self) + box.setIcon(QMessageBox.Icon.Warning) + box.setWindowTitle("Reset queue") + box.setText("Reset the scan queue?") + box.setInformativeText(self.reset_text()) + reset = box.addButton("Reset queue", QMessageBox.ButtonRole.DestructiveRole) + cancel = box.addButton(QMessageBox.StandardButton.Cancel) + box.setDefaultButton(cancel) + box.setEscapeButton(cancel) + box.exec() + if box.clickedButton() is reset: + self.model.reset() + box.deleteLater() + + @SafeSlot() + def _toggle_pause(self) -> None: + if self.model.paused: + self.model.resume() + else: + self.model.pause() + self._pause_requested_at = time.monotonic() + self._pause_timeout.start() # fall back to "Pause queue" if the pause never lands + self._render_header() + + @SafeSlot(object, str, str) + def _on_action_sent(self, kind: QueueAction, key: str, text: str) -> None: + match kind: + case QueueAction.MOVE: + self._flash_next[key] = Tone.ACCENT + case QueueAction.REMOVE: + self._removing[key] = time.monotonic() + self.waiting_rows.remove_animated(key) + self._render() + case QueueAction.RERUN: + self._new_rid = self.model.last_rerun_rid + self._requeued[key] = time.monotonic() + self._expire_timer.start() + self.waiting_badge.pulse() + # no announcement: the new waiting row flashes and the badge pulses + self._render() + case _: + # pause/resume/reset: the header and the lists are the feedback + self._render_header() + + @SafeSlot(object, str, str) + def _on_action_failed(self, kind: QueueAction, key: str, reason: str) -> None: + self._flash_next.pop(key, None) + self._failure = reason + self._failure_timer.start() + self._render() + row = self.waiting_rows.row(key) + if row is not None: + row.flash(Tone.WARN) + row.setToolTip(reason) # until the row's next update + + @SafeSlot() + def _clear_failure(self) -> None: + self._failure = "" + self._render() + + def reorder_hint(self) -> str: + """Short hint next to Up next: why the last action was refused, for a few seconds.""" + tone = "warn" if self._failure else "muted" + set_style(self.waiting_hint, f"color: {css(theme_colors()[tone])}; font-size: 11px;") + return self._failure + + def _expire_notes(self) -> None: + if not any(self.is_requeued(k) for k in self._requeued): + self._requeued.clear() + self._expire_timer.stop() + self._render() + + def cleanup(self): + """Disconnect the model and stop timers and animations.""" + self._expire_timer.stop() + self._failure_timer.stop() + self._pause_timeout.stop() + self.model.cleanup() + for rows in self.findChildren(KeyedRowList): + rows.stop_animations() + for badge in self.findChildren(CountBadge): + badge._anim.stop() # pylint: disable=protected-access + super().cleanup() if __name__ == "__main__": # pragma: no cover @@ -355,7 +955,11 @@ if __name__ == "__main__": # pragma: no cover from qtpy.QtWidgets import QApplication + from bec_widgets.utils.colors import apply_theme + app = QApplication(sys.argv) + apply_theme("dark") widget = BECQueue() + widget.resize(460, 900) widget.show() sys.exit(app.exec_()) diff --git a/bec_widgets/widgets/services/bec_queue/queue_model.py b/bec_widgets/widgets/services/bec_queue/queue_model.py new file mode 100644 index 00000000..3bf7017d --- /dev/null +++ b/bec_widgets/widgets/services/bec_queue/queue_model.py @@ -0,0 +1,666 @@ +""" +Scan queue model of the BECQueue widget: parses the queue status and history, and sends the +queue actions (reorder, remove, rerun, pause, resume). +""" + +from __future__ import annotations + +import copy +import time +import uuid +from collections import deque +from dataclasses import dataclass, field +from enum import StrEnum +from typing import Any + +from bec_lib import messages +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 ( + args_summary, + metadata_items, + scan_bundle_names, + scan_display_name, +) +from bec_widgets.widgets.progress.stage_bar import Tone + +logger = bec_logger.logger + +RUNNING_STATUSES = ("RUNNING", "PAUSED", "DEFERRED_PAUSE") +WAITING_STATUSES = ("PENDING", "IDLE") + + +class QueueAction(StrEnum): + """The kind of a queue action, sent with action_sent and action_failed.""" + + MOVE = "move" + REMOVE = "remove" + RERUN = "rerun" + PAUSE = "pause" + RESUME = "resume" + RESET = "reset" + + +class QueueMove(StrEnum): + """Where a waiting scan is moved.""" + + UP = "up" + DOWN = "down" + TOP = "top" + BOTTOM = "bottom" + + +# History status -> (icon name, tone, tooltip word) +HISTORY_STATUS = { + "COMPLETED": ("check_circle", Tone.OK, "Completed"), + "closed": ("check_circle", Tone.OK, "Completed"), + "user_completed": ("flag_circle", Tone.ACCENT, "Finished early"), + "STOPPED": ("cancel", Tone.BAD, "Stopped"), + "aborted": ("cancel", Tone.BAD, "Aborted"), + "halted": ("dangerous", Tone.BAD, "Halted"), + "CANCELLED": ("block", Tone.NEUTRAL, "Removed before it started"), +} + + +_REQUEST_ONLY_METADATA = ("RID", "scan_id", "queue_id", "client_info") + + +@dataclass +class QueueEntry: + """One queue item, waiting, running or finished.""" + + queue_id: str + status: str + scan_type: str + name: str + args: str = "" + bundle_names: list[str] = field(default_factory=list) + metadata: list[tuple[str, str]] = field(default_factory=list) + rid: str | None = None + scan_id: str | None = None + scan_number: int | None = None + blocks: int = 1 + position: int = 0 + request: Any = None + exit_status: str | None = None + started_at: float | None = None + finished_at: float | None = None + + @property + def key(self) -> str: + """Stable identity of the entry across queue updates.""" + return self.queue_id + + @property + def title(self) -> str: + """Display title, such as "#12 line_scan" or "line_scan +2".""" + number = f"#{self.scan_number} " if self.scan_number is not None else "" + more = f" +{self.blocks - 1}" if self.blocks > 1 else "" + return f"{number}{self.name}{more}" + + @property + def duration(self) -> float | None: + """Seconds between start and end, if both were seen.""" + if self.started_at is None or self.finished_at is None: + return None + return max(0.0, self.finished_at - self.started_at) + + @property + def history_status(self) -> tuple[str, str, str]: + """(icon, tone, word) for a finished entry.""" + key = self.exit_status or self.status + return HISTORY_STATUS.get(key, HISTORY_STATUS.get(self.status, ("help", Tone.NEUTRAL, key))) + + @property + def can_rerun(self) -> bool: + """Whether the original scan request is known, so it can be sent again.""" + return self.request is not None and bool(getattr(self.request, "scan_type", None)) + + +def _entry_from_info(info: Any, position: int = 0, scans: Any = None) -> QueueEntry | None: + blocks = list(getattr(info, "request_blocks", None) or []) + first = blocks[0] if blocks else None + request = getattr(first, "msg", None) if first is not None else None + scan_type = getattr(request, "scan_type", "") or "" + metadata = dict(getattr(request, "metadata", {}) or {}) + user_metadata = dict(metadata.get("user_metadata") or {}) + scan_ids = list(getattr(info, "scan_id", None) or []) + scan_id = getattr(first, "scan_id", None) or (scan_ids[0] if scan_ids else None) + scan_numbers = [n for n in (getattr(info, "scan_number", None) or []) if n is not None] + scan_number = getattr(first, "scan_number", None) + if scan_number is None and scan_numbers: + scan_number = scan_numbers[0] + bundle_names = scan_bundle_names(scans, scan_type) + return QueueEntry( + queue_id=getattr(info, "queue_id", ""), + status=str(getattr(info, "status", "")), + scan_type=scan_type, + name=scan_display_name(user_metadata, scan_type, fallback="request"), + args=args_summary(getattr(request, "parameter", None), bundle_names), + bundle_names=bundle_names, + metadata=metadata_items(user_metadata), + rid=getattr(first, "RID", None) or metadata.get("RID"), + scan_id=scan_id, + scan_number=scan_number, + blocks=max(1, len(blocks)), + position=position, + request=request, + ) + + +class _ReadResult(QObject): + """Carries the result of a background queue read to the GUI thread.""" + + done = Signal(int, object) + + +def _read_queue_state( + connector, + result: _ReadResult, + generation: int, + with_queue: bool, + known: set, + count: int, + scans: Any = None, +) -> None: + """ + Read the queue status, the queue history and, for scans not in known, the scan history + times. Runs in the thread pool: only Redis reads and message decoding, no Qt objects. + """ + payload: dict = {"queue": None, "history": None, "times": {}, "missing": set()} + if with_queue: + try: + msg = connector.get(MessageEndpoints.scan_queue_status()) + except Exception: # pylint: disable=broad-except + msg = None + if msg is not None and hasattr(msg, "content"): + payload["queue"] = msg.content + try: + history = connector.lrange(MessageEndpoints.scan_queue_history(), 0, count - 1) + except Exception: # pylint: disable=broad-except + logger.debug("Could not read the queue history") + history = None + if history is not None: + finished = [] + for item in history: + info = getattr(item, "info", None) + if info is None: + continue + entry = _entry_from_info(info, scans=scans) + if entry is None: + continue + entry.status = str(getattr(item, "status", entry.status)) + finished.append(entry) + payload["history"] = finished + missing = {e.scan_id for e in finished if e.scan_id and e.scan_id not in known} + if missing: + times = _read_history_times(connector, count) + if times is not None: + # the file writer can publish a scan's history entry after the queue moved it + # to the history, so a scan not found yet is looked up again by the model + payload["times"] = {sid: times[sid] for sid in missing if sid in times} + payload["missing"] = missing - set(times) + try: + result.done.emit(generation, payload) + except RuntimeError: + logger.debug("Queue read finished after its model was deleted") + + +def _read_history_times(connector, count: int) -> dict | None: + try: + msgs = connector.get_last(MessageEndpoints.scan_history(), key="data", count=count) + except Exception: # pylint: disable=broad-except + logger.debug("Could not read the scan history") + return None + if msgs is None: + msgs = [] + elif not isinstance(msgs, list): + msgs = [msgs] + return { + getattr(m, "scan_id", None): ( + getattr(m, "start_time", None), + getattr(m, "end_time", None), + getattr(m, "exit_status", None), + ) + for m in msgs + } + + +class ScanQueueModel(QObject): + """ + Follows the primary scan queue and its history. + + Signals: + changed(): The running, waiting or finished lists changed. + action_sent(QueueAction, str, str): (kind, entry key, message) after an action was sent; + kind is move, remove, rerun, pause, resume or reset. + action_failed(QueueAction, str, str): (kind, entry key, reason) when an action was + refused. + """ + + changed = Signal() + # object, not str: a str signal would hand the slots a plain str instead of the QueueAction + action_sent = Signal(object, str, str) + action_failed = Signal(object, str, str) + + HISTORY_LENGTH = 50 + # a scan not in BEC's scan history yet is looked up again this often, at most this many times + HISTORY_RETRY_MS = 3000 + HISTORY_RETRIES = 5 + MOVE_CONFIRM_S = 3.0 + + def __init__(self, client, bec_dispatcher, parent: QObject | None = None): + super().__init__(parent=parent) + self.client = client + self.bec_dispatcher = bec_dispatcher + self.running: QueueEntry | None = None + self.waiting: list[QueueEntry] = [] + self.finished: list[QueueEntry] = [] + self.queue_state: str = "RUNNING" + self._queue_offset = 0 + self._known_ids: set[str] = set() + self._scan_times: dict[str, dict] = {} + self._history_times: dict[str, tuple] = {} + self._history_misses: dict[str, int] = {} + self.last_rerun_rid: str | None = None + # moves sent and not answered yet, oldest first, as (key, deadline) + self._pending_moves: deque[tuple[str, float]] = deque() + self._server_waiting: list[QueueEntry] = [] + self._wanted_order: list[str] | None = None + self._wanted_until = 0.0 + self._connected = False + # Redis reads run in the thread pool; a result is used only if its generation is current + self.loaded = False + # parented, so it is deleted with the model on the GUI thread, never in the thread pool + self._read_result = _ReadResult(self) + self._read_result.done.connect(self._on_read_done) + self._history_retry = QTimer(self) + self._history_retry.setSingleShot(True) + self._history_retry.setInterval(self.HISTORY_RETRY_MS) + self._history_retry.timeout.connect(self.reload_history) + self._read_generation = 0 + self._reading = False + self._read_again = False + self._read_queue_again = False + self._queue_updates = 0 + self._read_queue_mark = 0 + self._worker: Worker | None = None + + ################################################################################ + # Subscriptions + ################################################################################ + + def start(self) -> None: + """Subscribe to queue and scan status and load the current state.""" + if self._connected: + return + self.bec_dispatcher.connect_slot(self.on_queue_status, MessageEndpoints.scan_queue_status()) + self.bec_dispatcher.connect_slot(self.on_scan_status, MessageEndpoints.scan_status()) + self.bec_dispatcher.connect_slot( + self.on_order_response, MessageEndpoints.scan_queue_order_change_response() + ) + self._connected = True + self.refresh() + + def cleanup(self) -> None: + """Disconnect from all endpoints and drop the result of a read still in flight.""" + self._read_generation += 1 + self._reading = self._read_again = self._read_queue_again = False + self._history_retry.stop() + if not self._connected: + return + self.bec_dispatcher.disconnect_slot( + self.on_queue_status, MessageEndpoints.scan_queue_status() + ) + self.bec_dispatcher.disconnect_slot(self.on_scan_status, MessageEndpoints.scan_status()) + self.bec_dispatcher.disconnect_slot( + self.on_order_response, MessageEndpoints.scan_queue_order_change_response() + ) + self._connected = False + + def refresh(self) -> None: + """Read the queue status and history from Redis in the background.""" + self._start_read(with_queue=True) + + def reload_history(self) -> None: + """Read the finished queue items from the queue history list in the background.""" + self._start_read(with_queue=False) + + def _start_read(self, with_queue: bool) -> None: + if self._reading: + # one read at a time; a request during it is folded into a single read after it + self._read_again = True + self._read_queue_again = self._read_queue_again or with_queue + return + self._reading = True + self._read_generation += 1 + self._read_queue_mark = self._queue_updates + known = {sid for sid, t in self._scan_times.items() if t.get("start")} + known |= set(self._history_times) + known |= { + sid for sid, misses in self._history_misses.items() if misses >= self.HISTORY_RETRIES + } + self._worker = Worker( + _read_queue_state, + self.client.connector, + self._read_result, + self._read_generation, + with_queue, + known, + self.HISTORY_LENGTH, + getattr(self.client, "scans", None), + ) + QThreadPool.globalInstance().start(self._worker) + + @SafeSlot(int, object) + def _on_read_done(self, generation: int, payload: dict) -> None: + if generation != self._read_generation: + return # superseded, or the model was cleaned up meanwhile + self._reading = False + self._worker = None + # a queue status read before a live update is older than what is shown already + if payload["queue"] is not None and self._read_queue_mark == self._queue_updates: + self._apply_queue(payload["queue"]) + finished = payload["history"] + if finished is not None: + self._history_times.update(payload["times"]) + self._count_history_misses(finished, payload["missing"]) + for entry in finished: + self._add_times(entry) + self._add_history_times(finished) + self.finished = finished + self.loaded = True + if self._read_again: + with_queue = self._read_queue_again + self._read_again = self._read_queue_again = False + self._start_read(with_queue) + self.changed.emit() + + def _count_history_misses(self, entries: list[QueueEntry], missing: set[str]) -> None: + """Look up scans not in the scan history yet again later; a few times, then give up.""" + shown = {e.scan_id for e in entries} + self._history_misses = { + sid: misses for sid, misses in self._history_misses.items() if sid in shown + } + for sid in missing: + self._history_misses[sid] = self._history_misses.get(sid, 0) + 1 + if any(self._history_misses.get(sid, 0) < self.HISTORY_RETRIES for sid in missing): + self._history_retry.start() + + def _add_history_times(self, entries: list[QueueEntry]) -> None: + """Fill start, end and exit status the widget did not see live from BEC's scan history.""" + self._history_times = { + e.scan_id: self._history_times[e.scan_id] + for e in entries + if e.scan_id in self._history_times + } + for entry in entries: + if entry.started_at is not None or entry.scan_id not in self._history_times: + continue + entry.started_at, end, exit_status = self._history_times[entry.scan_id] + entry.finished_at = entry.finished_at or end + entry.exit_status = entry.exit_status or exit_status + + def _add_times(self, entry: QueueEntry) -> None: + times = self._scan_times.get(entry.scan_id or "") + if not times: + return + entry.started_at = times.get("start") + entry.finished_at = times.get("end") + entry.exit_status = times.get("exit") + + @SafeSlot(dict, dict) + def on_scan_status(self, content: dict, _metadata: dict) -> None: + """Remember start and end times of scans for the history durations.""" + scan_id = content.get("scan_id") + if not scan_id: + return + status = content.get("status") + stamp = content.get("timestamp") or time.time() + times = self._scan_times.setdefault(scan_id, {}) + if status == "open": + times.setdefault("start", stamp) + elif status in ("closed", "aborted", "halted", "user_completed"): + times["end"] = stamp + times["exit"] = status + if len(self._scan_times) > 4 * self.HISTORY_LENGTH: + for old in list(self._scan_times)[: self.HISTORY_LENGTH]: + self._scan_times.pop(old, None) + + @SafeSlot(dict, dict) + def on_order_response(self, content: dict, _metadata: dict) -> None: + """ + Undo the shown reorder and report it when the scan server refused it. The response names + no request and is broadcast to all clients, so it is matched to the oldest move still + waiting for one; a response with no move waiting belongs to another client. + """ + now = time.monotonic() + while self._pending_moves and self._pending_moves[0][1] < now: + self._pending_moves.popleft() + if not self._pending_moves: + return + key, _deadline = self._pending_moves.popleft() + if content.get("accepted", True): + return + reason = content.get("message") or "The queue refused the move" + self._wanted_order = None + self.waiting = self._numbered(list(self._server_waiting)) + self.changed.emit() + self.action_failed.emit(QueueAction.MOVE, key, reason) + + @SafeSlot(dict, dict) + def on_queue_status(self, content: dict, _metadata: dict) -> None: + """Handle a ScanQueueStatusMessage.""" + before = self._known_ids + self._queue_updates += 1 + self._apply_queue(content) + if before - self._known_ids: + # an item left the queue; the server writes its history entry before removing it + self.reload_history() + self.changed.emit() + + def _apply_queue(self, content: dict) -> None: + queues = content.get("queue", {}) or {} + primary = queues.get("primary") + if primary is None: + self.running, self.waiting, self._known_ids = None, [], set() + return + self.queue_state = str(getattr(primary, "status", "RUNNING")) + infos = list(getattr(primary, "info", None) or []) + # every item still in the queue, finished ones included: a finished item is only removed + # after its history entry was written, so its removal is when the history is complete + self._known_ids = {getattr(info, "queue_id", "") for info in infos} + running = None + waiting = [] + self._queue_offset = 0 + for index, info in enumerate(infos): + entry = _entry_from_info( + info, position=index, scans=getattr(self.client, "scans", None) + ) + if entry is None: + continue + if entry.status in RUNNING_STATUSES and running is None: + running = entry + self._queue_offset = index + 1 + elif entry.status in WAITING_STATUSES: + waiting.append(entry) + self.running = running + self._server_waiting = list(waiting) + self.waiting = self._numbered(self._apply_wanted_order(waiting)) + + @staticmethod + def _numbered(waiting: list[QueueEntry]) -> list[QueueEntry]: + for pos, entry in enumerate(waiting, start=1): + entry.position = pos + return waiting + + def _apply_wanted_order(self, waiting: list[QueueEntry]) -> list[QueueEntry]: + """ + Show a reorder the user asked for until the queue reports it, so the rows move at once + and do not jump back while the server works through several quick moves. + """ + wanted = self._wanted_order + if wanted is None: + return waiting + keys = [e.key for e in waiting] + if keys == [k for k in wanted if k in keys] or time.monotonic() > self._wanted_until: + self._wanted_order = None + return waiting + by_key = {e.key: e for e in waiting} + ordered = [by_key[k] for k in wanted if k in by_key] + return ordered + [e for e in waiting if e.key not in wanted] + + ################################################################################ + # Lookups + ################################################################################ + + def entry(self, key: str) -> QueueEntry | None: + """Find an entry by key among waiting, running and finished.""" + for entry in [*self.waiting, *([self.running] if self.running else []), *self.finished]: + if entry.key == key: + return entry + return None + + def waiting_index(self, key: str) -> int: + """Index of a waiting entry, or -1.""" + for index, entry in enumerate(self.waiting): + if entry.key == key: + return index + return -1 + + ################################################################################ + # Actions + ################################################################################ + + def move(self, key: str, action: QueueMove | str) -> bool: + """ + Reorder a waiting scan. The running scan always stays first. + + Args: + key(str): The entry key. + action(QueueMove | str): up, down, top or bottom. + + Returns: + bool: True if a request was sent. + """ + action = QueueMove(action) + index = self.waiting_index(key) + if index < 0: + return False + target = { + QueueMove.UP: index - 1, + QueueMove.DOWN: index + 1, + QueueMove.TOP: 0, + QueueMove.BOTTOM: len(self.waiting) - 1, + }.get(action, index) + target = max(0, min(target, len(self.waiting) - 1)) + if target == index: + return False + entry = self.waiting[index] + if not entry.scan_id: + logger.warning(f"Cannot move {entry.title}: it has no scan id yet") + return False + # the widget shows and indexes the primary queue, not the client's default scan queue + self.client.queue.request_queue_order_modification( + scan_id=entry.scan_id, + action="move_to", + position=target + self._queue_offset, + queue="primary", + ) + self._pending_moves.append((key, time.monotonic() + self.MOVE_CONFIRM_S)) + waiting = list(self.waiting) + waiting.insert(target, waiting.pop(index)) + self._wanted_order = [e.key for e in waiting] + self._wanted_until = time.monotonic() + self.MOVE_CONFIRM_S + self.waiting = self._numbered(waiting) + words = { + QueueMove.UP: "up", + QueueMove.DOWN: "down", + QueueMove.TOP: "to the top", + QueueMove.BOTTOM: "to the bottom", + } + self.action_sent.emit(QueueAction.MOVE, key, f"Moved {entry.title} {words.get(action, '')}") + self.changed.emit() + return True + + def remove(self, key: str) -> bool: + """Remove a waiting scan from the queue.""" + index = self.waiting_index(key) + if index < 0: + return False + entry = self.waiting[index] + if not entry.rid: + return False + self.client.queue.request_scan_abortion(request_id=entry.rid) + self.action_sent.emit(QueueAction.REMOVE, key, f"Removed {entry.title}") + return True + + def rerun(self, entry: QueueEntry | str) -> str | None: + """ + Queue a new scan with the same request as an existing entry. + + Args: + entry(QueueEntry | str): The entry or its key. + + Returns: + str | None: The new request id. + """ + if isinstance(entry, str): + entry = self.entry(entry) + if entry is None or not entry.can_rerun: + return None + request = entry.request + metadata = { + k: copy.deepcopy(v) + for k, v in (getattr(request, "metadata", {}) or {}).items() + if k not in _REQUEST_ONLY_METADATA + } + rid = str(uuid.uuid4()) + metadata["RID"] = rid + client_info = dict((getattr(request, "metadata", {}) or {}).get("client_info") or {}) + client_info["acl_user"] = getattr(self.client, "username", client_info.get("acl_user")) + metadata["client_info"] = client_info + msg = messages.ScanQueueMessage( + scan_type=request.scan_type, + parameter=copy.deepcopy(request.parameter), + queue=getattr(request, "queue", "primary"), + metadata=metadata, + ) + self.client.connector.send(MessageEndpoints.scan_queue_request(self.client.username), msg) + self.last_rerun_rid = rid + self.action_sent.emit(QueueAction.RERUN, entry.key, f"Queued {entry.name} again") + return rid + + def pause(self) -> None: + """Pause the queue; the running scan pauses at its next safe point. Needs a running scan.""" + if self.running is None: + return + # sent directly: request_scan_interruption aborts instead when the running item has no + # scan id (umv, mv, a device RPC), while the server holds the queue after such an item + msg = messages.ScanQueueModificationMessage( + request_id=self.running.rid, action="deferred_pause", parameter={} + ) + self.client.connector.send(MessageEndpoints.scan_queue_modification_request(), msg) + self.action_sent.emit(QueueAction.PAUSE, "", "Queue pauses at the next safe point") + + def resume(self) -> None: + """Resume a paused queue.""" + self.client.queue.request_scan_continuation() + self.action_sent.emit(QueueAction.RESUME, "", "Queue resumed") + + def reset(self) -> None: + """ + Reset the queue: the scan server pauses it, stops the running scan and the devices it + uses, and removes every waiting scan. + """ + self.client.queue.request_queue_reset() + self.action_sent.emit(QueueAction.RESET, "", "Queue reset") + + @property + def paused(self) -> bool: + """Whether the queue is paused or locked.""" + return self.queue_state in ("PAUSED", "LOCKED") diff --git a/bec_widgets/widgets/services/bec_queue/queue_ui.py b/bec_widgets/widgets/services/bec_queue/queue_ui.py new file mode 100644 index 00000000..9cc0c78b --- /dev/null +++ b/bec_widgets/widgets/services/bec_queue/queue_ui.py @@ -0,0 +1,683 @@ +""" +Animated rows, keyed row lists and small controls of the BECQueue widget. +""" + +from __future__ import annotations + +from datetime import date, datetime +from typing import Callable + +from qtpy.QtCore import ( + QEasingCurve, + QEvent, + QPoint, + QPointF, + QPropertyAnimation, + QRect, + QRectF, + QSize, + Qt, + QVariantAnimation, + Signal, +) +from qtpy.QtGui import QColor, QPainter, QPainterPath, QPen +from qtpy.QtWidgets import ( + QFrame, + QGridLayout, + QLabel, + QSizePolicy, + QToolButton, + QVBoxLayout, + QWidget, +) + +from bec_widgets.utils.theme_utils import DPR_EVENTS, crisp_icon, crisp_pixmap, css, theme_colors +from bec_widgets.widgets.progress.scan_progressbar.scan_hook_tracker import format_duration +from bec_widgets.widgets.progress.scan_progressbar.scan_ui import ElidedLabel, args_items +from bec_widgets.widgets.progress.stage_bar import Tone, mono_font +from bec_widgets.widgets.services.bec_queue.queue_model import QueueEntry + + +def set_style(widget: QWidget, sheet: str) -> None: + """Set a stylesheet only when it changed; restyling on every update makes rows flicker.""" + if widget.styleSheet() != sheet: + widget.setStyleSheet(sheet) + + +def tone_color(tone: Tone | str) -> QColor: + """Theme colour for a tone; neutral is the muted colour.""" + colors = theme_colors() + return { + Tone.OK: colors["ok"], + Tone.BAD: colors["bad"], + Tone.WARN: colors["warn"], + Tone.RUN: colors["run"], + Tone.ACCENT: colors["primary"], + }.get(Tone(tone), colors["muted"]) + + +class IconButton(QToolButton): + """A flat icon button with a tooltip, used for row actions.""" + + def __init__( + self, + icon_name: str, + tooltip: str, + tone: Tone | str = Tone.NEUTRAL, + parent: QWidget | None = None, + ): + super().__init__(parent) + self._icon_name = icon_name + self._tone = Tone(tone) + self.setToolTip(tooltip) + self.setAccessibleName(tooltip) + self.setAutoRaise(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setIconSize(QSize(18, 18)) + self.setFixedSize(26, 26) + self.refresh_style() + + def event(self, event): # pylint: disable=invalid-name + if event.type() in DPR_EVENTS: + self.refresh_style() # re-render the icon for the new screen + return super().event(event) + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + colors = theme_colors() + color = tone_color(self._tone) if self._tone != Tone.NEUTRAL else colors["fg"] + self.setIcon(crisp_icon(self._icon_name, 18, color, widget=self)) + set_style( + self, + "QToolButton { border: none; border-radius: 5px; background: transparent; }" + f"QToolButton:hover {{ background: {css(colors['fg'], 0.10)}; }}" + f"QToolButton:disabled {{ background: transparent; }}", + ) + + +class MoreButton(QToolButton): + """ + A flat "more actions" button: three vertical dots in the text colour that open its menu. + The dots are painted, so they are sharp at every scale and need no icon font. + """ + + def __init__(self, tooltip: str, parent: QWidget | None = None): + super().__init__(parent) + self.setToolTip(tooltip) + self.setAccessibleName(tooltip) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setFixedSize(26, 26) + self.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + self.refresh_style() + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + colors = theme_colors() + set_style( + self, + "QToolButton { border: none; border-radius: 5px; background: transparent; }" + f"QToolButton:hover {{ background: {css(colors['fg'], 0.10)}; }}" + f"QToolButton:focus {{ border: 1px solid {css(colors['primary'])}; }}" + "QToolButton::menu-indicator { image: none; width: 0; }", + ) + self.update() + + def paintEvent(self, event): # pylint: disable=invalid-name + super().paintEvent(event) + colors = theme_colors() + color = colors["fg"] if self.isEnabled() else colors["muted"] + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(color) + radius = 1.8 + center = QRectF(self.rect()).center() + for offset in (-5.0, 0.0, 5.0): + painter.drawEllipse(center + QPointF(0, offset), radius, radius) + painter.end() + + +class StatusIcon(QLabel): + """A small status icon whose tooltip tells the status in words.""" + + def __init__(self, parent: QWidget | None = None, size: int = 16): + super().__init__(parent) + self._size = size + self.setFixedSize(size + 4, size + 4) + self.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.icon_name = "" + self.tone = Tone.NEUTRAL + + def set_status(self, icon_name: str, tone: Tone | str, tooltip: str) -> None: + """Show an icon in a tone colour with a tooltip.""" + tone = Tone(tone) + if (icon_name, tone) == (self.icon_name, self.tone) and self.toolTip() == tooltip: + return + self.icon_name, self.tone = icon_name, tone + self._render_icon() + self.setToolTip(tooltip) + self.setAccessibleName(tooltip) + + def _render_icon(self) -> None: + if self.icon_name: + self.setPixmap( + crisp_pixmap( + self.icon_name, self._size, tone_color(self.tone), filled=True, widget=self + ) + ) + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + self._render_icon() + + def event(self, event): # pylint: disable=invalid-name + if event.type() in DPR_EVENTS: + self._render_icon() + return super().event(event) + + +class CountBadge(QLabel): + """A count in a pill that pulses when asked.""" + + def __init__(self, parent: QWidget | None = None): + super().__init__("0", parent) + self.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.setMinimumWidth(22) + self._pulse = 0.0 + self._anim = QVariantAnimation(self) + self._anim.setDuration(900) + self._anim.setStartValue(1.0) + self._anim.setEndValue(0.0) + self._anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._anim.valueChanged.connect(self._on_pulse) + self.refresh_style() + + def _on_pulse(self, value) -> None: + self._pulse = float(value) + self.refresh_style() + + def pulse(self) -> None: + """Flash the badge in the accent colour.""" + self._anim.stop() + self._anim.start() + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + colors = theme_colors() + bg = css(colors["primary"], 0.15 + 0.75 * self._pulse) + fg = css(colors["on_primary"]) if self._pulse > 0.4 else css(colors["primary"]) + self.setStyleSheet( + f"QLabel {{ background: {bg}; color: {fg}; border-radius: 9px; padding: 0 7px;" + " font-weight: 600; }" + ) + + +class GroupTitle(QLabel): + """Uppercase muted title above a group of rows or details.""" + + def __init__(self, text: str, parent: QWidget | None = None): + super().__init__(text.upper(), parent) + self.refresh_style() + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + self.setStyleSheet( + f"color: {css(theme_colors()['muted'])}; font-weight: 700; letter-spacing: 1px;" + " font-size: 11px;" + ) + + +class DetailGrid(QWidget): + """Key/value grid for a scan's arguments and metadata.""" + + def __init__(self, parent: QWidget | None = None): + super().__init__(parent) + self._grid = QGridLayout(self) + self._grid.setContentsMargins(0, 0, 0, 0) + self._grid.setHorizontalSpacing(12) + self._grid.setVerticalSpacing(2) + self._grid.setColumnStretch(1, 1) + self._items: list[tuple[str, str]] | None = None + self._keys: list[ElidedLabel] = [] + self._values: list[ElidedLabel] = [] + + KEY_SHARE_MAX = 0.45 # a very long key may take at most this share of the grid width + + def natural_key_width(self) -> int: + """Width of the widest key, unelided (with a little slack for fractional advances).""" + widths = [k.fontMetrics().horizontalAdvance(t) for k, t in self._key_texts()] + return max(widths) + 2 if widths else 0 + + def natural_width(self) -> int: + """Width this grid needs to show every key and value in full.""" + if not self._items: + return 0 + values = max( + ( + v.fontMetrics().horizontalAdvance(t) + for v, t in zip(self._values, self._value_texts()) + ), + default=0, + ) + return self.natural_key_width() + self._grid.horizontalSpacing() + values + 2 + + def fit_keys(self, width: int) -> None: + """ + Give the keys their natural width. Only when key and value do not both fit, the keys + give way first, down to KEY_SHARE_MAX of the width, then the values elide. + """ + natural_key = self.natural_key_width() + values = self.natural_width() - natural_key + room_for_keys = max(width - values, int(width * self.KEY_SHARE_MAX)) + key_width = max(1, min(natural_key, room_for_keys)) + for key in self._keys: + key.setFixedWidth(key_width) + # the keys ignore their size hints, so the column needs its width set explicitly + self._grid.setColumnMinimumWidth(0, key_width) + + def _key_texts(self): + return [(k, k.full_text()) for k in self._keys] + + def _value_texts(self): + return [v.full_text() for v in self._values] + + def refresh_style(self) -> None: + """Re-read the theme colours.""" + if self._items is not None: + self.set_items(self._items, force=True) + + def set_items(self, items: list[tuple[str, str]], force: bool = False) -> None: + """Replace the rows, unless they did not change.""" + if items == self._items and not force: + return + self._items = list(items) + while self._grid.count(): + item = self._grid.takeAt(0) + if item.widget() is not None: + item.widget().deleteLater() + muted = css(theme_colors()["muted"]) + self._keys, self._values = [], [] + for row, (key, value) in enumerate(items): + k = ElidedLabel(key, self) + k.setStyleSheet(f"color: {muted};") + k.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) + # one line per value, cut with the full text as tooltip; never widens the view + v = ElidedLabel(value, self) + v.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + if key == "args": + v.setFont(mono_font(-1)) + self._grid.addWidget(k, row, 0) + self._grid.addWidget(v, row, 1) + self._keys.append(k) + self._values.append(v) + + +def entry_detail_columns(entry: QueueEntry) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]: + """ + The details of an entry split in two: (scan arguments and request info, user metadata). + Every argument is its own row. + """ + arguments = args_items(getattr(entry.request, "parameter", None), entry.bundle_names) + if not arguments and entry.args: + arguments = [("args", entry.args)] + if entry.scan_type and entry.scan_type != entry.name: + arguments.append(("scan", entry.scan_type)) + if entry.blocks > 1: + arguments.append(("requests", f"{entry.blocks} scans in this queue item")) + return arguments, list(entry.metadata) + + +def finished_times(entry: QueueEntry, today: date | None = None) -> str: + """ + Start time and duration of a finished entry: "14:03:21 (0:11)", or "Oct 29 14:03 (0:11)" + for a scan from another day. Without a known start, the finish time minus the duration. + """ + took = f"({format_duration(entry.duration)})" if entry.duration is not None else "" + start = entry.started_at + if start is None and entry.finished_at is not None and entry.duration is not None: + start = entry.finished_at - entry.duration + if not start: + return took + started = datetime.fromtimestamp(start) + if started.date() == (today or date.today()): + when = f"{started:%H:%M:%S}" + else: + when = f"{started:%b} {started.day} {started:%H:%M}" + return f"{when} {took}".strip() + + +def finished_tooltip(entry: QueueEntry) -> str: + """Tooltip for a finished entry's status icon: status, time, duration.""" + _, _, word = entry.history_status + parts = [word] + if entry.finished_at: + parts.append(f"at {datetime.fromtimestamp(entry.finished_at):%H:%M:%S}") + if entry.duration is not None: + parts.append(f"took {format_duration(entry.duration)}") + return " · ".join(parts) + + +class AnimatedRow(QFrame): + """ + A rounded row that can flash, slide in, and collapse out; hovered or selected rows are + highlighted. + + Subclasses add their content to ``self.body`` (a QVBoxLayout). + """ + + clicked = Signal(str) + height_changed = Signal() + + def __init__(self, key: str, parent: QWidget | None = None): + super().__init__(parent) + self.key = key + self.leaving = False + self.selected = False + self._hover = False + self._flash = 0.0 + self._flash_tone = Tone.ACCENT + self.setAttribute(Qt.WidgetAttribute.WA_Hover, True) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) + self.body = QVBoxLayout(self) + self.body.setContentsMargins(6, 3, 6, 3) + self.body.setSpacing(3) + + self._flash_anim = QVariantAnimation(self) + self._flash_anim.setDuration(1400) + self._flash_anim.setStartValue(1.0) + self._flash_anim.setEndValue(0.0) + self._flash_anim.setEasingCurve(QEasingCurve.Type.InQuad) + self._flash_anim.valueChanged.connect(self._on_flash) + self._height_anim = QPropertyAnimation(self, b"maximumHeight", self) + self._height_anim.setDuration(260) + self._height_anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._height_anim.finished.connect(self._on_height_finished) + self._height_anim.valueChanged.connect(lambda _v: self.height_changed.emit()) + self._height_done: Callable[[], None] | None = None + self.move_anim = QPropertyAnimation(self, b"pos", self) + self.move_anim.setEasingCurve(QEasingCurve.Type.OutCubic) + + def _on_flash(self, value) -> None: + self._flash = float(value) + self.update() + + def flash(self, tone: Tone | str = Tone.ACCENT) -> None: + """Highlight the row and fade the highlight out.""" + self._flash_tone = Tone(tone) + self._flash_anim.stop() + self._flash_anim.start() + + @property + def flashing(self) -> bool: + """Whether a flash is running.""" + return self._flash_anim.state() == QVariantAnimation.State.Running + + def slide_in(self) -> None: + """Grow from zero height, then flash.""" + target = max(self.sizeHint().height(), 24) + self._height_anim.stop() + self._height_done = lambda: self.setMaximumHeight(16777215) + self._height_anim.setStartValue(0) + self._height_anim.setEndValue(target) + self._height_anim.start() + self.flash(Tone.ACCENT) + + def leave(self, on_done: Callable[[], None] | None = None) -> None: + """Turn red and collapse to zero height, then call on_done.""" + if self.leaving: + return + self.leaving = True + self.setEnabled(False) + self._flash_tone = Tone.BAD + self._flash = 1.0 + self.update() + self._height_anim.stop() + self._height_done = on_done + self._height_anim.setDuration(380) + self._height_anim.setStartValue(self.height()) + self._height_anim.setEndValue(0) + self._height_anim.start() + + def _on_height_finished(self) -> None: + done, self._height_done = self._height_done, None + if done is not None: + done() + self.height_changed.emit() + + def wanted_height(self, width: int) -> int: + """Height for a width, limited by a running height animation.""" + if self.hasHeightForWidth(): + height = self.heightForWidth(width) + else: + height = self.sizeHint().height() + return max(0, min(height, self.maximumHeight())) + + def set_selected(self, selected: bool) -> None: + """Mark the row as selected.""" + if selected != self.selected: + self.selected = selected + self.update() + + def enterEvent(self, event): # pylint: disable=invalid-name + self._hover = True + self.update() + super().enterEvent(event) + + def leaveEvent(self, event): # pylint: disable=invalid-name + self._hover = False + self.update() + super().leaveEvent(event) + + def mouseReleaseEvent(self, event): # pylint: disable=invalid-name + if event.button() == Qt.MouseButton.LeftButton and self.rect().contains(event.pos()): + self.clicked.emit(self.key) + super().mouseReleaseEvent(event) + + @property + def gliding(self) -> bool: + """Whether the row is moving to a new place in its list.""" + return self.move_anim.state() == QPropertyAnimation.State.Running + + def stop_animations(self) -> None: + """Stop running animations (before deletion).""" + self._flash_anim.stop() + self._height_anim.stop() + self.move_anim.stop() + + def paintEvent(self, event): # pylint: disable=invalid-name + colors = theme_colors() + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + path = QPainterPath() + path.addRoundedRect(rect, 7, 7) + if self.selected: + sel = QColor(colors["primary"]) + sel.setAlphaF(0.16) + painter.fillPath(path, sel) + elif self._hover: + hov = QColor(colors["fg"]) + hov.setAlphaF(0.06) + painter.fillPath(path, hov) + if self._flash > 0: + flash = QColor(tone_color(self._flash_tone)) + flash.setAlphaF(0.32 * self._flash) + painter.fillPath(path, flash) + if self.selected: + border = colors["primary"] + if self._flash > 0.05: + border = tone_color(self._flash_tone) + painter.setPen(QPen(border, 1)) + painter.drawPath(path) + painter.end() + super().paintEvent(event) + + +class KeyedRowList(QWidget): + """ + A vertical list of AnimatedRow widgets kept in sync with a list of entries by key. + + New rows slide in, vanished rows collapse out, kept rows are reused and glide to their new + place when the order changes. Rows are placed by hand rather than by a layout, so a reorder + can animate and an update that changes nothing does not touch the geometry. + """ + + MOVE_MS = 240 + + def __init__( + self, + make_row: Callable[[QueueEntry], AnimatedRow], + update_row: Callable[[AnimatedRow, QueueEntry], None], + parent: QWidget | None = None, + spacing: int = 4, + ): + super().__init__(parent) + self._make_row = make_row + self._update_row = update_row + self._spacing = spacing + self.rows: dict[str, AnimatedRow] = {} + self.order: list[str] = [] + self._layout_keys: list[str] = [] + self._height = 0 + self._initialised = False + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) + + def sync(self, entries: list[QueueEntry], animate: bool = True) -> list[str]: + """ + Make the rows match the entries. + + Returns: + list[str]: Keys of rows whose position changed. + """ + animate = animate and self._initialised + self._initialised = True + new_order = [e.key for e in entries] + old_index = {k: i for i, k in enumerate(self.order)} + moved = [] + for index, entry in enumerate(entries): + row = self.rows.get(entry.key) + if row is None or row.leaving: + if row is not None: + self._drop(row) + row = self._make_row(entry) + row.setParent(self) + row.height_changed.connect(self._relayout) + self.rows[entry.key] = row + self._update_row(row, entry) + if animate: + row.slide_in() + row.show() + continue + if old_index.get(entry.key) != index: + moved.append(entry.key) + self._update_row(row, entry) + + for key in list(self.rows): + if key not in new_order: + row = self.rows[key] + if not row.leaving: + if animate: + row.leave(lambda r=row: self._drop(r)) + else: + self._drop(row) + + # leaving rows keep their old place until they have collapsed + layout_keys = list(new_order) + for key in self._layout_keys: + row = self.rows.get(key) + if row is not None and row.leaving and key not in layout_keys: + layout_keys.insert(min(old_index.get(key, len(layout_keys)), len(layout_keys)), key) + self._layout_keys = layout_keys + self.order = new_order + self._relayout(animate=animate, lift=moved) + return moved + + def _targets(self) -> dict[str, QRect]: + width = self.width() + y = 0 + targets = {} + for key in self._layout_keys: + row = self.rows.get(key) + if row is None: + continue + height = row.wanted_height(width) + targets[key] = QRect(0, y, width, height) + y += height + (self._spacing if height > 0 else 0) + self._height = max(0, y - self._spacing) if targets else 0 + return targets + + def _relayout(self, animate: bool = False, lift: list[str] | None = None) -> None: + targets = self._targets() + if self.minimumHeight() != self._height or self.maximumHeight() != self._height: + self.setFixedHeight(self._height) + for key, rect in targets.items(): + row = self.rows[key] + if row.size() != rect.size(): + row.resize(rect.size()) + running = row.gliding + if row.pos() == rect.topLeft() and not running: + continue + if (animate or running) and row.isVisible() and row.height() > 0: + self._glide(row, rect.topLeft()) + else: + row.move(rect.topLeft()) + for key in lift or (): + row = self.rows.get(key) + if row is not None: + row.raise_() + + def _glide(self, row: AnimatedRow, target: QPoint) -> None: + anim = row.move_anim + anim.setDuration(self.MOVE_MS) + if anim.state() == QPropertyAnimation.State.Running: + if anim.endValue() == target: + return + anim.stop() + anim.setStartValue(row.pos()) + anim.setEndValue(target) + anim.start() + + def sizeHint(self) -> QSize: # pylint: disable=invalid-name + return QSize(super().sizeHint().width(), self._height) + + def resizeEvent(self, event): # pylint: disable=invalid-name + super().resizeEvent(event) + if event.size().width() != event.oldSize().width(): + self._relayout() + + def event(self, event): + if event.type() == QEvent.Type.LayoutRequest: + # a row's content changed size + self._relayout() + return super().event(event) + + def _drop(self, row: AnimatedRow) -> None: + if self.rows.get(row.key) is row: + del self.rows[row.key] + row.stop_animations() + row.hide() + row.deleteLater() + if row.key in self._layout_keys and row.key not in self.rows: + self._layout_keys.remove(row.key) + self._relayout() + + def remove_animated(self, key: str) -> None: + """Collapse a row out now, before the queue confirms its removal.""" + row = self.rows.get(key) + if row is not None and not row.leaving: + row.leave(lambda r=row: self._drop(r)) + + def row(self, key: str) -> AnimatedRow | None: + """The row for a key, if shown.""" + row = self.rows.get(key) + return row if row is not None and not row.leaving else None + + @property + def gliding(self) -> list[str]: + """Keys of rows that are moving to a new place.""" + return [key for key, row in self.rows.items() if row.gliding] + + def stop_animations(self) -> None: + """Stop all row animations.""" + for row in self.rows.values(): + row.stop_animations() diff --git a/tests/unit_tests/test_bec_queue.py b/tests/unit_tests/test_bec_queue.py index 36a5a3fd..fd5667c3 100644 --- a/tests/unit_tests/test_bec_queue.py +++ b/tests/unit_tests/test_bec_queue.py @@ -1,299 +1,1190 @@ -from unittest.mock import MagicMock +import threading +from unittest import mock import pytest -import shiboken6 from bec_lib import messages -from qtpy.QtCore import QEvent -from qtpy.QtWidgets import QAbstractButton, QApplication +from bec_lib.endpoints import MessageEndpoints +from qtpy.QtCore import Qt, QThreadPool -from bec_widgets.tests.client_mocks import mocked_client -from bec_widgets.widgets.control.buttons.button_abort.button_abort import AbortButton +from bec_widgets.tests.utils import create_widget +from bec_widgets.widgets.progress.scan_progressbar.scan_ui import args_items, args_summary +from bec_widgets.widgets.progress.stage_bar import Tone from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue +from bec_widgets.widgets.services.bec_queue.queue_model import QueueMove, ScanQueueModel +from bec_widgets.widgets.services.bec_queue.queue_ui import entry_detail_columns + + +def make_request(scan_type="line_scan", rid="rid", args=None, kwargs=None, user_metadata=None): + return messages.ScanQueueMessage( + scan_type=scan_type, + parameter={ + "args": args if args is not None else {"samx": [-5, 5]}, + "kwargs": ( + kwargs + if kwargs is not None + else {"steps": 50, "exp_time": 0.1, "relative": True, "system_config": {}} + ), + }, + queue="primary", + metadata={ + "RID": rid, + "user_metadata": user_metadata or {}, + "client_info": {"acl_user": "user"}, + }, + ) + + +def make_info( + queue_id, status="PENDING", scan_number=None, scan_id=None, rid=None, **request_kwargs +): + rid = rid or f"rid-{queue_id}" + scan_id = scan_id or f"scan-{queue_id}" + request = make_request(rid=rid, **request_kwargs) + block = messages.RequestBlock( + msg=request, + RID=rid, + readout_priority={"monitored": [], "baseline": [], "on_request": [], "async": []}, + is_scan=True, + scan_number=scan_number, + scan_id=scan_id, + ) + return messages.QueueInfoEntry( + queue_id=queue_id, + scan_id=[scan_id], + is_scan=[True], + request_blocks=[block], + scan_number=[scan_number], + status=status, + ) + + +def queue_status(infos, status="RUNNING"): + return messages.ScanQueueStatusMessage( + queue={"primary": messages.ScanQueueStatus(info=infos, status=status)}, metadata={} + ) + + +def history_msg(queue_id, status="COMPLETED", **info_kwargs): + info = make_info(queue_id, status=status, **info_kwargs) + return messages.ScanQueueHistoryMessage(status=status, queue_id=queue_id, info=info) @pytest.fixture -def bec_queue_msg_full(): - content = { - "primary": { - "info": [ - { - "active_request_block": None, - "is_scan": [True], - "queue_id": "600163fc-5e56-4901-af25-14e9ee76817c", - "request_blocks": [ - { - "RID": "89a76021-28c0-4297-828e-74ae40b941e5", - "content": { - "parameter": { - "args": {"samx": [-0.1, 0.1]}, - "kwargs": { - "exp_time": 0.5, - "relative": True, - "steps": 20, - "system_config": { - "file_directory": None, - "file_suffix": None, - }, - }, - }, - "queue": "primary", - "scan_type": "line_scan", - }, - "is_scan": True, - "metadata": { - "RID": "89a76021-28c0-4297-828e-74ae40b941e5", - "file_directory": None, - "file_suffix": None, - "user_metadata": {"sample_name": "testA"}, - }, - "msg": messages.ScanQueueMessage( - metadata={ - "file_suffix": None, - "file_directory": None, - "user_metadata": {"sample_name": "testA"}, - "RID": "89a76021-28c0-4297-828e-74ae40b941e5", - }, - scan_type="line_scan", - parameter={ - "args": {"samx": [-0.1, 0.1]}, - "kwargs": { - "steps": 20, - "exp_time": 0.5, - "relative": True, - "system_config": { - "file_suffix": None, - "file_directory": None, - }, - }, - }, - queue="primary", - ), - "readout_priority": { - "async": [], - "baseline": [], - "monitored": ["samx"], - "on_request": [], - }, - "report_instructions": [{"scan_progress": 20}], - "scan_id": "2d704cc3-c172-404c-866d-608ce09fce40", - "scan_number": 1289, - } - ], - "scan_id": ["2d704cc3-c172-404c-866d-608ce09fce40"], - "scan_number": [1289], - "status": "COMPLETED", - } - ], - "status": "RUNNING", - } - } - msg = messages.ScanQueueStatusMessage(metadata={}, queue=content) - return msg +def queue_infos(): + return [ + make_info("q-run", status="RUNNING", scan_number=12, user_metadata={"sample": "LiFePO4"}), + make_info( + "q-a", + scan_type="grid_scan", + args={"samx": [-2, 2, 21], "samy": [-1, 1, 11]}, + user_metadata={"sample": "LiFePO4", "edge": "Fe K"}, + ), + make_info("q-b", scan_type="time_scan", args={}, kwargs={"points": 100, "interval": 1.0}), + make_info("q-c", user_metadata={"scan_name": "align_slit", "operator": "jw"}), + ] + + +def push_state(client, infos, history=(), status="RUNNING"): + client.connector.delete(MessageEndpoints.scan_queue_history()) + client.connector.set_and_publish( + MessageEndpoints.scan_queue_status(), queue_status(infos, status) + ) + for item in reversed(list(history)): + client.connector.lpush(MessageEndpoints.scan_queue_history(), item) + + +def set_queue(widget, infos, status="PAUSED"): + msg = queue_status(infos, status=status) + widget.model.on_queue_status(msg.content, msg.metadata) + + +def wait_for_reads(qtbot, widget): + """Wait until the queue's background Redis reads have landed.""" + qtbot.waitUntil(lambda: widget.model.loaded and not widget.model._reading) + + +def create_queue(qtbot, client): + widget = create_widget(qtbot, BECQueue, client=client) + wait_for_reads(qtbot, widget) + return widget @pytest.fixture -def bec_queue(qtbot, mocked_client): - widget = BECQueue(client=mocked_client, refresh_upon_start=False) - qtbot.addWidget(widget) - qtbot.waitExposed(widget) +def queue_widget(qtbot, mocked_client, queue_infos): + push_state( + mocked_client, + queue_infos, + history=[history_msg("h-1", scan_number=11), history_msg("h-2", "STOPPED", scan_number=10)], + ) + widget = create_queue(qtbot, mocked_client) yield widget -def test_bec_queue(bec_queue, bec_queue_msg_full): - bec_queue.update_queue(bec_queue_msg_full.content, {}) - assert bec_queue.table.rowCount() == 1 - assert bec_queue.table.item(0, 0).text() == "1289" - assert bec_queue.table.item(0, 1).text() == "line_scan" - assert bec_queue.table.item(0, 2).text() == "line_scan" - assert bec_queue.table.item(0, 3).text() == "COMPLETED" +def test_model_splits_running_waiting_and_finished(queue_widget): + model = queue_widget.model + assert model.running is not None and model.running.queue_id == "q-run" + assert [e.queue_id for e in model.waiting] == ["q-a", "q-b", "q-c"] + assert [e.position for e in model.waiting] == [1, 2, 3] + assert [e.queue_id for e in model.finished] == ["h-1", "h-2"] + assert model.waiting[2].name == "align_slit" + assert ("edge", "Fe K") in model.waiting[0].metadata + # without the scan's signature the third value is not taken for a position + assert "samx -2 2 21" in model.waiting[0].args + assert model.finished[1].history_status[0] == "cancel" -def test_bec_queue_empty(bec_queue): - bec_queue.update_queue({}, {}) - assert bec_queue.table.rowCount() == 1 - assert bec_queue.table.item(0, 0).text() == "" - assert bec_queue.table.item(0, 1).text() == "" - assert bec_queue.table.item(0, 2).text() == "" - assert bec_queue.table.item(0, 3).text() == "" +def test_rows_follow_queue(queue_widget): + rows = queue_widget.waiting_rows + assert rows.order == ["q-a", "q-b", "q-c"] + assert queue_widget.waiting_badge.text() == "3" -def test_queue_abort(bec_queue, bec_queue_msg_full): - # test if abort buttons are not leaking, so making 3 times the same abort request and fixture should check the leak of the buttons automatically - - bec_queue.update_queue(bec_queue_msg_full.content, {}) - assert bec_queue.table.rowCount() == 1 - assert bec_queue.table.item(0, 0).text() == "1289" - assert bec_queue.table.item(0, 1).text() == "line_scan" - assert bec_queue.table.item(0, 2).text() == "line_scan" - assert bec_queue.table.item(0, 3).text() == "COMPLETED" - - abort_button = bec_queue.table.cellWidget(0, 4) - abort_button.button.click() - - bec_queue.update_queue(bec_queue_msg_full.content, {}) - - assert bec_queue.table.rowCount() == 1 - assert bec_queue.table.item(0, 0).text() == "1289" - assert bec_queue.table.item(0, 1).text() == "line_scan" - assert bec_queue.table.item(0, 2).text() == "line_scan" - assert bec_queue.table.item(0, 3).text() == "COMPLETED" - - abort_button = bec_queue.table.cellWidget(0, 4) - abort_button.button.click() - - bec_queue.update_queue(bec_queue_msg_full.content, {}) - - assert bec_queue.table.rowCount() == 1 - assert bec_queue.table.item(0, 0).text() == "1289" - assert bec_queue.table.item(0, 1).text() == "line_scan" - assert bec_queue.table.item(0, 2).text() == "line_scan" - assert bec_queue.table.item(0, 3).text() == "COMPLETED" - - abort_button = bec_queue.table.cellWidget(0, 4) - abort_button.button.click() +def test_move_sends_move_to_after_the_running_scan(queue_widget): + queue = queue_widget.client.queue + with mock.patch.object(queue, "request_queue_order_modification") as order: + queue_widget.move_scan("q-b", QueueMove.UP) + order.assert_called_once_with( + scan_id="scan-q-b", action="move_to", position=1, queue="primary" + ) + order.reset_mock() + queue_widget.move_scan("q-b", QueueMove.UP) + order.assert_not_called() + queue_widget.move_scan("q-b", QueueMove.BOTTOM) + order.assert_called_once_with( + scan_id="scan-q-b", action="move_to", position=3, queue="primary" + ) + assert queue_widget.waiting_rows.order == ["q-a", "q-c", "q-b"] -def _queue_entry(scan_number: int, rid: str, status: str = "PENDING") -> dict: - """Build a single primary-queue entry with one request block.""" - msg = messages.ScanQueueMessage( - metadata={"RID": rid}, scan_type="line_scan", parameter={"args": {}, "kwargs": {}} +def test_move_shows_the_new_order_at_once_until_the_queue_confirms(queue_widget, queue_infos): + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-c", QueueMove.TOP) + rows = queue_widget.waiting_rows + assert rows.order == ["q-c", "q-a", "q-b"] + assert rows.row("q-c").flashing + assert [e.position for e in queue_widget.model.waiting] == [1, 2, 3] + set_queue(queue_widget, queue_infos, status="RUNNING") # the server has not moved it yet + assert rows.order == ["q-c", "q-a", "q-b"] + reordered = [queue_infos[0], queue_infos[3], queue_infos[1], queue_infos[2]] + set_queue(queue_widget, reordered, status="RUNNING") + assert queue_widget.model._wanted_order is None + set_queue(queue_widget, queue_infos, status="RUNNING") # someone else moved it back + assert rows.order == ["q-a", "q-b", "q-c"] + + +def test_remove_aborts_by_request_id_and_collapses_the_row(queue_widget, qtbot): + queue = queue_widget.client.queue + with mock.patch.object(queue, "request_scan_abortion") as abort: + queue_widget.remove_scan("q-b") + abort.assert_called_once_with(request_id="rid-q-b") + assert queue_widget.waiting_rows.rows["q-b"].leaving + assert "q-b" not in [e.key for e in queue_widget.waiting_entries()] + qtbot.waitUntil(lambda: "q-b" not in queue_widget.waiting_rows.rows, timeout=2000) + + +def test_rerun_resends_the_request_with_a_new_rid(queue_widget): + with mock.patch.object(queue_widget.client.connector, "send") as send: + queue_widget.rerun_scan("h-1") + msg = send.call_args.args[1] + assert msg.scan_type == "line_scan" + assert msg.parameter["args"] == {"samx": [-5, 5]} + assert msg.metadata["RID"] not in ("rid-h-1", None) + assert "scan_id" not in msg.metadata + assert queue_widget.is_requeued("h-1") + assert ( + queue_widget.waiting_badge._anim.state() == queue_widget.waiting_badge._anim.State.Running ) - return { - "queue_id": f"queue-{scan_number}", - "scan_id": [f"scan-{scan_number}"], - "is_scan": [True], - "request_blocks": [ - { - "msg": msg, - "RID": rid, - "readout_priority": {"monitored": [], "baseline": [], "on_request": []}, - "is_scan": True, - "scan_number": scan_number, - "scan_id": f"scan-{scan_number}", - } - ], - "scan_number": [scan_number], - "status": status, - } -@pytest.fixture -def bec_queue_msg_three_rows(): - """Queue status with three pending scans, one row each.""" - content = { - "primary": { - "info": [ - _queue_entry(1001, "rid-1001", status="RUNNING"), - _queue_entry(1002, "rid-1002"), - _queue_entry(1003, "rid-1003"), - ], - "status": "RUNNING", - } - } - return messages.ScanQueueStatusMessage(metadata={}, queue=content) +def test_finished_status_is_an_icon_with_tooltip(queue_widget): + rows = queue_widget.finished_rows + stopped = rows.rows["h-2"] + icon = stopped.status_icon if hasattr(stopped, "status_icon") else stopped.lead + assert icon.icon_name == "cancel" + assert icon.toolTip().startswith("Stopped") -def _row_scan_numbers(bec_queue: BECQueue) -> list[str]: - return [bec_queue.table.item(row, 0).text() for row in range(bec_queue.table.rowCount())] +def test_finished_durations_come_from_scan_status(qtbot, queue_widget): + model = queue_widget.model + model.on_scan_status({"scan_id": "scan-h-1", "status": "open", "timestamp": 100.0}, {}) + model.on_scan_status({"scan_id": "scan-h-1", "status": "closed", "timestamp": 165.0}, {}) + model.reload_history() + wait_for_reads(qtbot, queue_widget) + assert model.finished[0].duration == 65.0 + assert model.finished[0].exit_status == "closed" -@pytest.mark.parametrize("clicked_row", [0, 1, 2]) -def test_queue_abort_removes_clicked_row(bec_queue, bec_queue_msg_three_rows, clicked_row): - """Clicking the abort button of a row aborts that request and removes exactly that row.""" - bec_queue.update_queue(bec_queue_msg_three_rows.content, {}) - assert _row_scan_numbers(bec_queue) == ["1001", "1002", "1003"] - - queue_mock = MagicMock() - for row in range(bec_queue.table.rowCount()): - bec_queue.table.cellWidget(row, 4).queue = queue_mock - - clicked = bec_queue.table.cellWidget(clicked_row, 4) - assert isinstance(clicked, AbortButton) - expected_rid = f"rid-{1001 + clicked_row}" - assert clicked.request_id == expected_rid - - clicked.button.click() - - queue_mock.request_scan_abortion.assert_called_once_with(request_id=expected_rid) - remaining = [n for n in ["1001", "1002", "1003"] if n != str(1001 + clicked_row)] - assert _row_scan_numbers(bec_queue) == remaining - - # Every remaining row keeps an intact abort button for its own request. - QApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) - for row, scan_number in enumerate(remaining): - cell = bec_queue.table.cellWidget(row, 4) - assert isinstance(cell, AbortButton) - assert cell.request_id == f"rid-{scan_number}" - assert shiboken6.isValid(cell.button) - # The aborted row's cell widget is deleted together with its row. - assert not shiboken6.isValid(clicked) +def _sent_modifications(send): + return [ + call.args[1] + for call in send.call_args_list + if call.args[0] == MessageEndpoints.scan_queue_modification_request() + ] -def test_queue_delete_selected_row_without_abort_sender_is_noop( - bec_queue, bec_queue_msg_three_rows +def test_pause_and_resume(queue_widget, queue_infos): + queue = queue_widget.client.queue + with mock.patch.object(queue_widget.client.connector, "send") as send: + queue_widget.pause_button.click() + (pause,) = _sent_modifications(send) + assert (pause.action, pause.request_id) == ("deferred_pause", "rid-q-run") + msg = queue_status(queue_infos, status="PAUSED") + queue_widget.model.on_queue_status(msg.content, msg.metadata) + assert queue_widget.queue_chip.text() == "Paused" + with mock.patch.object(queue, "request_scan_continuation") as resume: + queue_widget.pause_button.click() + resume.assert_called_once() + + +def test_pause_during_a_motor_move_holds_the_queue_instead_of_aborting(qtbot, mocked_client): + """A umv has no scan id; bec_lib's request_scan_interruption would abort it.""" + request = messages.ScanQueueMessage( + scan_type="umv", parameter={"args": {"samx": [10]}, "kwargs": {}}, queue="primary" + ) + block = messages.RequestBlock( + msg=request, + RID="rid-umv", + readout_priority={"monitored": [], "baseline": [], "on_request": [], "async": []}, + is_scan=False, + scan_number=None, + scan_id=None, + ) + umv = messages.QueueInfoEntry( + queue_id="q-umv", + scan_id=[None], + is_scan=[False], + request_blocks=[block], + scan_number=[None], + status="RUNNING", + ) + push_state(mocked_client, [umv, make_info("q-next")]) + widget = create_queue(qtbot, mocked_client) + assert widget.pause_button.isEnabled() + queue = mocked_client.queue + with ( + mock.patch.object(mocked_client.connector, "send") as send, + mock.patch.object(queue, "request_scan_interruption") as interruption, + mock.patch.object(queue, "request_scan_abortion") as abortion, + ): + widget.pause_button.click() + assert [(m.action, m.request_id) for m in _sent_modifications(send)] == [ + ("deferred_pause", "rid-umv") + ] + interruption.assert_not_called() + abortion.assert_not_called() + + +def test_pause_disabled_without_running_scan(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos[1:]) + widget = create_queue(qtbot, mocked_client) + assert widget.model.running is None + assert not widget.pause_button.isEnabled() + assert widget.queue_chip.text() == "Ready" + + +def test_detail_drawer_follows_selection(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + widget = create_queue(qtbot, mocked_client) + assert widget.drawer.hint.isVisibleTo(widget.drawer) + widget.select("q-b") + assert widget.drawer.waiting_actions.isVisibleTo(widget.drawer) + assert "position 2 of 3" in widget.drawer.label.text() + with mock.patch.object(widget.client.queue, "request_queue_order_modification") as order: + widget.drawer.top_button.click() + order.assert_called_once_with(scan_id="scan-q-b", action="move_to", position=1, queue="primary") + assert "position 1 of 3" in widget.drawer.label.text() + widget.select("h-1") + assert widget.drawer.finished_actions.isVisibleTo(widget.drawer) + with mock.patch.object(widget.client.connector, "send"): + widget.drawer.rerun_button.click() + assert widget.drawer.queued_label.isVisibleTo(widget.drawer) + widget.select("h-1") + assert widget.selected_key is None + + +def test_model_ignores_missing_queue(qtbot, mocked_client): + model = ScanQueueModel(mocked_client, mock.MagicMock()) + model._apply_queue({"queue": {}}) + assert model.running is None and model.waiting == [] + + +def test_refused_move_from_server_shows_its_reason(queue_widget): + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-c", QueueMove.UP) + queue_widget.model.on_order_response( + {"accepted": False, "message": "The running scan cannot be moved."}, {} + ) + assert queue_widget._flash_next == {} + assert queue_widget.waiting_hint.text() == "The running scan cannot be moved." + assert queue_widget.waiting_rows.row("q-c").toolTip() == "The running scan cannot be moved." + + +def test_detail_rows_have_their_own_actions(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + first, last = widget.waiting_rows.rows["q-a"], widget.waiting_rows.rows["q-c"] + assert not first.up_button.isEnabled() and first.down_button.isEnabled() + assert last.up_button.isEnabled() and not last.down_button.isEnabled() + with mock.patch.object(widget.client.queue, "request_queue_order_modification") as order: + last.up_button.click() + order.assert_called_once_with(scan_id="scan-q-c", action="move_to", position=2, queue="primary") + with mock.patch.object(widget.client.queue, "request_scan_abortion") as abort: + first.remove_button.click() + abort.assert_called_once_with(request_id="rid-q-a") + assert first.leaving + + +def test_rows_glide_to_their_new_place(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + widget.resize(460, 700) + widget.show() + qtbot.waitExposed(widget) + rows = widget.waiting_rows + top = rows.rows["q-a"].y() + with mock.patch.object(widget.client.queue, "request_queue_order_modification"): + widget.move_scan("q-c", QueueMove.TOP) + assert "q-c" in rows.gliding + qtbot.waitUntil(lambda: not rows.gliding, timeout=2000) + ys = [rows.rows[k].y() for k in ("q-c", "q-a", "q-b")] + assert ys == sorted(ys) and ys[0] == top + + +def test_detail_rows_show_metadata_then_arguments_and_keep_them_for_hover( + qtbot, mocked_client, queue_infos ): - """A call that does not originate from an abort button must not remove any row.""" - bec_queue.update_queue(bec_queue_msg_three_rows.content, {}) - bec_queue.delete_selected_row() - assert _row_scan_numbers(bec_queue) == ["1001", "1002", "1003"] + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + assert widget.show_details + for entry in widget.model.waiting: + row = widget.waiting_rows.rows[entry.key] + named = entry.name != entry.scan_type # a scan with its own name shows its type first + prefix = [entry.scan_type] if named else [] + parts = prefix + [v for _, v in entry.metadata] + ([entry.args] if entry.args else []) + assert row.meta_label.full_text() == " · ".join(parts) + assert row.toolTip() == entry.args + assert row.tail_label.isHidden() + assert widget.finished_badge.text() == str(len(widget.model.finished)) -def _primary_queue_content(entries: list[dict]) -> dict: - """Content of a queue status message whose primary queue holds the given entries.""" - return messages.ScanQueueStatusMessage( - metadata={}, queue={"primary": {"info": entries, "status": "RUNNING"}} - ).content +def test_an_accepted_move_is_not_blamed_for_a_later_rejection(queue_widget): + model = queue_widget.model + failed = [] + model.action_failed.connect(lambda *args: failed.append(args)) + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-b", QueueMove.UP) + order = [e.key for e in model.waiting] + model.on_order_response({"accepted": True, "message": "ok"}, {}) + # another client's move is refused later: the response is broadcast to everyone + model.on_order_response({"accepted": False, "message": "not ours"}, {}) + assert failed == [] + assert [e.key for e in model.waiting] == order -def _click_every_button_in_row(bec_queue: BECQueue, row: int) -> None: - """Click every button that any cell widget of the given row offers.""" - for column in range(bec_queue.table.columnCount()): - cell = bec_queue.table.cellWidget(row, column) - if cell is None: - continue - for button in cell.findChildren(QAbstractButton): - button.click() +def test_a_rejection_is_attributed_to_the_move_it_answers(queue_widget): + model = queue_widget.model + failed = [] + model.action_failed.connect(lambda *args: failed.append(args)) + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-b", QueueMove.UP) + queue_widget.move_scan("q-c", QueueMove.UP) + model.on_order_response({"accepted": True, "message": "ok"}, {}) + model.on_order_response({"accepted": False, "message": "refused"}, {}) + assert [(args[1], args[2]) for args in failed] == [("q-c", "refused")] + + +def test_a_move_no_response_came_for_expires(queue_widget): + model = queue_widget.model + failed = [] + model.action_failed.connect(lambda *args: failed.append(args)) + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-b", QueueMove.UP) + model._pending_moves[0] = ("q-b", 0.0) # its deadline has passed + model.on_order_response({"accepted": False, "message": "not ours"}, {}) + assert failed == [] + assert not model._pending_moves @pytest.mark.parametrize( - "empty_content", - [{}, {"queue": {}}, "primary_without_items"], - ids=["no_queue", "no_primary_queue", "empty_primary_queue"], + "request_name, action", + [ + ("request_queue_order_modification", lambda widget: widget.move_scan("q-b", QueueMove.UP)), + ("request_scan_abortion", lambda widget: widget.remove_scan("q-b")), + ], ) -def test_queue_placeholder_row_never_requests_abort(bec_queue, mocked_client, empty_content): - """ - The empty-queue placeholder row targets no request, so it must not offer an abort. - - An empty request id is not harmless by design: AbortButton treats None as "abort the current - request", and a scan may already run while the placeholder is still displayed. Clicking what - the placeholder offers must therefore send no abort request at all and keep the placeholder. - """ - if empty_content == "primary_without_items": - empty_content = _primary_queue_content([]) - # Start from a populated table so the placeholder replaces a real row. - bec_queue.update_queue(_primary_queue_content([_queue_entry(1001, "rid-1001")]), {}) - previous_button = bec_queue.table.cellWidget(0, 4) - assert isinstance(previous_button, AbortButton) - - bec_queue.update_queue(empty_content, {}) - assert _row_scan_numbers(bec_queue) == [""] - # The placeholder must not inherit the abort button of the row it replaces. - QApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) - assert not shiboken6.isValid(previous_button) - - _click_every_button_in_row(bec_queue, 0) - - mocked_client.queue.request_scan_abortion.assert_not_called() - assert _row_scan_numbers(bec_queue) == [""] - assert bec_queue.table.cellWidget(0, 4) is None +def test_a_failed_send_does_not_escape_and_keeps_the_shown_order( + queue_widget, request_name, action +): + order = [e.key for e in queue_widget.model.waiting] + with mock.patch.object( + queue_widget.client.queue, request_name, side_effect=RuntimeError("redis is gone") + ): + action(queue_widget) + assert [e.key for e in queue_widget.model.waiting] == order + assert not queue_widget.model._pending_moves -def test_queue_row_without_request_id_has_no_abort_button(bec_queue, mocked_client): - """A queue item that carries no request id cannot be aborted by id, so it gets no button.""" - bec_queue.update_queue(_primary_queue_content([_queue_entry(1002, "")]), {}) - assert _row_scan_numbers(bec_queue) == ["1002"] - assert bec_queue.table.cellWidget(0, 4) is None +def test_a_failed_rerun_does_not_escape(queue_widget): + entry = queue_widget.model.finished[0] + with mock.patch.object( + queue_widget.client.connector, "send", side_effect=RuntimeError("redis is gone") + ): + queue_widget.rerun_scan(entry.key) - _click_every_button_in_row(bec_queue, 0) - mocked_client.queue.request_scan_abortion.assert_not_called() - assert _row_scan_numbers(bec_queue) == ["1002"] + +def test_rows_and_drawer_name_the_values_of_an_argument_bundle(qtbot, mocked_client, queue_infos): + from types import SimpleNamespace + + arg_input = {"device": "device", "start": "float", "stop": "float", "steps": "int"} + grid_scan = SimpleNamespace(scan_info={"arg_input": arg_input}) + push_state(mocked_client, queue_infos) + with mock.patch.object(mocked_client, "scans", SimpleNamespace(grid_scan=grid_scan)): + widget = create_queue(qtbot, mocked_client) + entry = widget.model.waiting[0] + assert entry.args.startswith("samx -2 → 2 steps 21 · samy -1 → 1 steps 11") + assert ("samx", "-2 → 2 steps 21") in entry_detail_columns(entry)[0] + + +def test_a_device_rpc_is_shown_as_a_call(): + parameter = { + "args": [], + "kwargs": { + "device": "samx", + "func": "set", + "func_args": (5.0,), + "func_kwargs": {"wait": True}, + "rpc_id": "abc", + "system_config": {}, + }, + } + assert args_summary(parameter) == "samx.set(5, wait=True)" + assert args_items(parameter) == [("call", "samx.set(5, wait=True)")] + + +def test_show_details_off_hides_the_arguments_in_the_rows_only(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + widget = create_queue(qtbot, mocked_client) + waiting, finished = widget.model.waiting[0], widget.model.finished[0] + rows = (widget.waiting_rows.rows[waiting.key], widget.finished_rows.rows[finished.key]) + assert waiting.args and finished.args + assert all(row.meta_label.full_text().endswith(row.toolTip()) for row in rows) + + widget.show_details = False + assert waiting.args not in rows[0].meta_label.full_text() + assert rows[0].meta_label.full_text() == " · ".join(v for _, v in waiting.metadata) + assert finished.args not in rows[1].meta_label.full_text() + assert [row.toolTip() for row in rows] == [waiting.args, finished.args] + + widget.show_details = True + assert rows[0].meta_label.full_text().endswith(waiting.args) + + +def test_a_scan_without_metadata_shows_just_its_arguments(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + entry = next(e for e in widget.model.waiting if e.key == "q-b") + assert not entry.metadata and entry.args + assert widget.waiting_rows.rows[entry.key].meta_label.full_text() == entry.args + + +def test_long_arguments_are_elided_in_the_row(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + entry = widget.model.waiting[0] + row = widget.waiting_rows.rows[entry.key] + row.meta_label.resize(60, row.meta_label.height()) + assert row.meta_label.full_text().endswith(entry.args) + assert row.meta_label.text() != row.meta_label.full_text() # the shown text is elided + assert row.toolTip() == entry.args + + +def test_drawer_shows_arguments_and_metadata_side_by_side(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + widget.resize(520, 700) + widget.show() + qtbot.waitExposed(widget) + drawer = widget.drawer + entry = next(e for e in widget.model.waiting if e.metadata) + widget.select(entry.key) + qtbot.waitUntil(lambda: drawer.width() >= drawer.STACK_BELOW, timeout=1000) + assert drawer.meta_grid._items == entry.metadata + assert drawer.args_grid._items and all( + k not in dict(entry.metadata) for k, _ in drawer.args_grid._items + ) + assert not drawer.meta_box.isHidden() and not drawer.stacked + assert drawer.args_box.y() == drawer.meta_box.y() # top-aligned, side by side + + widget.resize(300, 700) + qtbot.waitUntil(lambda: drawer.stacked, timeout=1000) + qtbot.waitUntil(lambda: drawer.meta_box.y() > drawer.args_box.y(), timeout=1000) + assert drawer.meta_box.x() == drawer.args_box.x() + + +def test_drawer_without_metadata_has_one_column(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + entry = next(e for e in widget.model.waiting if not e.metadata) + widget.select(entry.key) + assert widget.drawer.meta_box.isHidden() + assert widget.drawer.args_grid._items + + +def test_icon_buttons_render_at_the_device_pixel_ratio(qtbot): + from qtpy.QtCore import QSize + from qtpy.QtGui import QIcon + from qtpy.QtWidgets import QWidget + + from bec_widgets.widgets.services.bec_queue.queue_ui import IconButton + + host = QWidget() + qtbot.addWidget(host) + with mock.patch.object(IconButton, "devicePixelRatioF", return_value=2.0): + button = IconButton("delete", "Remove", parent=host) + icon = button.icon() + assert QSize(36, 36) in icon.availableSizes(QIcon.Mode.Normal) + normal = icon.pixmap(QSize(18, 18), 2.0, QIcon.Mode.Normal).toImage() + disabled = icon.pixmap(QSize(18, 18), 2.0, QIcon.Mode.Disabled).toImage() + assert normal.size() == QSize(36, 36) + assert normal != disabled + + +SCREENSHOT_KWARGS = { + "steps": 10, + "relative": False, + "exp_time": 1, + "frames_per_trigger": 1, + "settling_time": 0, + "settling_time_after_trigger": 0, + "readout_time": 0, + "burst_at_each_point": 1, + "system_config": {}, +} + + +def _drawer_for(qtbot, mocked_client, width, kwargs=None, metadata=None): + infos = [ + make_info("q-run", status="RUNNING", scan_number=1), + make_info( + "q-x", + args={"samx": [0, 1]}, + kwargs=kwargs or SCREENSHOT_KWARGS, + user_metadata=metadata or {"comment": "stuff", "sample_name": "sample"}, + ), + ] + push_state(mocked_client, infos) + widget = create_queue(qtbot, mocked_client) + widget.resize(width, 760) + widget.show() + qtbot.waitExposed(widget) + widget.select("q-x") + qtbot.wait(50) + return widget.drawer + + +def _elided(grid): + return [v.full_text() for v in grid._values if v.text() != v.full_text()] + + +def test_drawer_columns_sized_by_content(qtbot, mocked_client): + drawer = _drawer_for(qtbot, mocked_client, 444) # 420 px of drawer content + assert not drawer.stacked + qtbot.waitUntil(lambda: not _elided(drawer.args_grid), timeout=1000) + assert not _elided(drawer.meta_grid) + args, meta = drawer.args_box.geometry(), drawer.meta_box.geometry() + assert args.right() < meta.left() # side by side, no overlap + # metadata follows the arguments at their natural width plus the gap, packed to the left + assert args.width() == drawer.args_grid.natural_width() + meta_text_left = meta.left() + drawer.meta_box.layout().contentsMargins().left() + assert meta_text_left - args.left() == args.width() + drawer.COLUMN_GAP + + +def test_drawer_splitter_can_be_dragged_and_keeps_its_place(qtbot, mocked_client): + drawer = _drawer_for(qtbot, mocked_client, 600) + before = drawer.args_box.width() + drawer.splitter.moveSplitter(before + 40, 1) + qtbot.waitUntil(lambda: drawer.args_box.width() == before + 40, timeout=1000) + drawer.resize(drawer.width() + 20, drawer.height()) + qtbot.wait(50) + assert drawer.args_box.width() == before + 40 # the dragged place is kept + + +def test_drawer_columns_share_half_when_both_overflow(qtbot, mocked_client): + long_kwargs = {f"long_parameter_name_{i}": "x" * 120 for i in range(3)} + long_meta = {f"long_metadata_key_{i}": "y" * 120 for i in range(3)} + drawer = _drawer_for(qtbot, mocked_client, 1200, kwargs=long_kwargs, metadata=long_meta) + stacked, args_w, meta_w = drawer.column_widths(700) + assert not stacked and abs(args_w - meta_w) <= 1 + + +def test_drawer_columns_stack_when_narrow(qtbot, mocked_client): + drawer = _drawer_for(qtbot, mocked_client, 320) + qtbot.waitUntil(lambda: drawer.stacked, timeout=1000) + + +def test_finished_rows_have_an_inline_rerun_button(qtbot, mocked_client, queue_infos): + push_state( + mocked_client, + queue_infos, + history=[history_msg("h-1", scan_number=10), history_msg("h-2", status="STOPPED")], + ) + widget = create_queue(qtbot, mocked_client) + rows = widget.finished_rows.rows + assert all(not row.rerun_button.isHidden() for row in rows.values()) + row = rows["h-1"] + assert row.rerun_button.isEnabled() + with mock.patch.object(widget.client.connector, "send") as send: + row.rerun_button.click() + send.assert_called_once() + assert widget.selected_key is None # the click did not select the row + assert row.tail_label.text() == "Queued ✓" + assert row.rerun_button.isHidden() + + +def test_inline_rerun_is_disabled_without_the_request(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=10)]) + widget = create_queue(qtbot, mocked_client) + entry = widget.model.finished[0] + entry.request = None + row = widget.finished_rows.rows[entry.key] + row.set_entry(entry, selected=False) + assert not row.rerun_button.isEnabled() + assert "Cannot run again" in row.rerun_button.toolTip() + + +def test_drawer_close_button_toggle_and_escape(qtbot, mocked_client, queue_infos): + from qtpy.QtCore import Qt + + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + drawer = widget.drawer + assert drawer.close_button.isHidden() + widget.select("q-b") + assert not drawer.close_button.isHidden() + assert widget.waiting_rows.rows["q-b"].selected + drawer.close_button.click() + assert widget.selected_key is None + assert drawer.details.isHidden() and drawer.close_button.isHidden() + assert not widget.waiting_rows.rows["q-b"].selected + + widget.select("q-b") + widget.select("q-b") # clicking the selected row again closes it + assert widget.selected_key is None + + widget.select("q-b") + qtbot.keyClick(widget, Qt.Key.Key_Escape) + assert widget.selected_key is None + + +def test_drawer_keys_are_not_cut_when_there_is_room(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + widget = create_queue(qtbot, mocked_client) + widget.resize(460, 680) + widget.show() + qtbot.waitExposed(widget) + widget.select("h-1") + qtbot.wait(50) + keys = widget.drawer.args_grid._keys + assert keys and all(k.text() == k.full_text() for k in keys) + + +def test_finished_times_show_start_and_duration(): + from datetime import date, datetime + + from bec_widgets.widgets.services.bec_queue.queue_model import QueueEntry + from bec_widgets.widgets.services.bec_queue.queue_ui import finished_times + + start = datetime(2026, 10, 30, 14, 2, 31).timestamp() + entry = QueueEntry(queue_id="q", status="COMPLETED", scan_type="line_scan", name="line_scan") + entry.started_at, entry.finished_at = start, start + 11 + assert finished_times(entry, today=date(2026, 10, 30)) == "14:02:31 (0:11)" + assert finished_times(entry, today=date(2026, 10, 31)) == "Oct 30 14:02 (0:11)" + entry.started_at = None + assert finished_times(entry, today=date(2026, 10, 30)) == "" + entry.started_at, entry.finished_at = None, None + assert finished_times(entry) == "" + + +def test_history_times_come_from_the_scan_history(qtbot, mocked_client, queue_infos): + from bec_lib import messages as bec_messages + + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + hist = mock.MagicMock(spec=bec_messages.ScanHistoryMessage) + hist.scan_id, hist.start_time, hist.end_time = "scan-h-1", 1000.0, 1011.0 + with mock.patch.object(mocked_client.connector, "get_last", return_value=[hist]): + widget = create_queue(qtbot, mocked_client) + entry = widget.model.finished[0] + assert (entry.started_at, entry.finished_at) == (1000.0, 1011.0) + assert widget.finished_rows.rows[entry.key].tail_label.text().endswith("(0:11)") + + +def test_scan_history_is_read_only_for_scans_not_seen_yet(qtbot, mocked_client, queue_infos): + from bec_lib import messages as bec_messages + + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + hist = mock.MagicMock(spec=bec_messages.ScanHistoryMessage) + hist.scan_id, hist.start_time, hist.end_time = "scan-h-1", 1000.0, 1011.0 + with mock.patch.object(mocked_client.connector, "get_last", return_value=[hist]) as get_last: + widget = create_queue(qtbot, mocked_client) + model = widget.model + model.HISTORY_RETRIES = 2 + model._history_retry.setInterval(60_000) # the retries are triggered by hand here + assert get_last.call_count == 1 + + model.reload_history() + wait_for_reads(qtbot, widget) + assert get_last.call_count == 1 # h-1 was found, it is not looked up again + assert model.finished[0].started_at == 1000.0 + + mocked_client.connector.lpush( + MessageEndpoints.scan_queue_history(), history_msg("h-2", scan_number=12) + ) + model.reload_history() + wait_for_reads(qtbot, widget) + assert get_last.call_count == 2 + assert model._history_retry.isActive() # h-2 is not in the scan history yet + model.reload_history() + wait_for_reads(qtbot, widget) + assert get_last.call_count == 3 + # after HISTORY_RETRIES misses (e.g. a scan that never started) it is not looked up again + model.reload_history() + wait_for_reads(qtbot, widget) + assert get_last.call_count == 3 + + +def test_a_scan_history_entry_published_late_is_still_found(qtbot, mocked_client, queue_infos): + from bec_lib import messages as bec_messages + + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + hist = mock.MagicMock(spec=bec_messages.ScanHistoryMessage) + hist.scan_id, hist.start_time, hist.end_time = "scan-h-1", 1000.0, 1011.0 + published: list = [] # the file writer publishes the entry after the queue moved the scan + with mock.patch.object( + mocked_client.connector, "get_last", side_effect=lambda *a, **k: published + ): + widget = create_queue(qtbot, mocked_client) + widget.model._history_retry.setInterval(20) + assert widget.model.finished[0].started_at is None + published.append(hist) + qtbot.waitUntil(lambda: widget.model.finished[0].started_at == 1000.0, timeout=2000) + assert widget.model.finished[0].finished_at == 1011.0 + assert not widget.model._history_retry.isActive() + + +def _blocking_lrange(client): + """Patch value for connector.lrange that waits until released.""" + started, release = threading.Event(), threading.Event() + original = client.connector.lrange + + def lrange(*args, **kwargs): + started.set() + release.wait(5) + return original(*args, **kwargs) + + return lrange, started, release + + +def test_queue_reads_run_off_the_gui_thread(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + threads = [] + connector = mocked_client.connector + + def record(original): + def wrapper(endpoint, *args, **kwargs): + if "queue" in endpoint.endpoint or endpoint == MessageEndpoints.scan_history(): + threads.append(threading.get_ident()) + return original(endpoint, *args, **kwargs) + + return wrapper + + with ( + mock.patch.object(connector, "get", side_effect=record(connector.get)), + mock.patch.object(connector, "lrange", side_effect=record(connector.lrange)), + mock.patch.object(connector, "get_last", side_effect=record(lambda *a, **k: [])), + ): + widget = create_queue(qtbot, mocked_client) + set_queue(widget, queue_infos[1:], status="RUNNING") # the running scan leaves + wait_for_reads(qtbot, widget) + assert len(threads) >= 4 # queue status, history, scan history, history again + assert threading.main_thread().ident not in threads + assert [e.queue_id for e in widget.model.finished] == ["h-1"] + + +def test_a_stale_read_is_ignored(qtbot, queue_widget): + model = queue_widget.model + finished = list(model.finished) + stale = {"queue": queue_status([]).content, "history": [], "times": {}} + model._on_read_done(model._read_generation - 1, stale) + assert model.finished == finished + assert model.running is not None and model.running.queue_id == "q-run" + + +def test_a_read_older_than_a_live_queue_update_keeps_the_live_queue( + qtbot, mocked_client, queue_infos +): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + lrange, started, release = _blocking_lrange(mocked_client) + with mock.patch.object(mocked_client.connector, "lrange", side_effect=lrange): + widget = create_widget(qtbot, BECQueue, client=mocked_client) + assert started.wait(5) + set_queue(widget, queue_infos[2:], status="RUNNING") # newer than the read in flight + release.set() + wait_for_reads(qtbot, widget) + assert [e.queue_id for e in widget.model.waiting] == ["q-b", "q-c"] + assert [e.queue_id for e in widget.model.finished] == ["h-1"] + + +def test_loading_shows_no_empty_state(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + lrange, started, release = _blocking_lrange(mocked_client) + with mock.patch.object(mocked_client.connector, "lrange", side_effect=lrange): + widget = create_widget(qtbot, BECQueue, client=mocked_client) + assert started.wait(5) + assert not widget.waiting_empty.isVisibleTo(widget) + assert widget.queue_chip.text() == "Loading" + release.set() + wait_for_reads(qtbot, widget) + assert widget.queue_chip.text() == "Running" + assert not widget.waiting_empty.isVisibleTo(widget) + + +def test_closing_while_a_read_is_in_flight_is_safe(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + lrange, started, release = _blocking_lrange(mocked_client) + with mock.patch.object(mocked_client.connector, "lrange", side_effect=lrange): + widget = create_widget(qtbot, BECQueue, client=mocked_client) + 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.model.finished == [] and not widget.model.loaded + + +def test_reloads_during_a_read_are_folded_into_one(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + widget = create_queue(qtbot, mocked_client) + lrange, started, release = _blocking_lrange(mocked_client) + with mock.patch.object(mocked_client.connector, "lrange", side_effect=lrange) as patched: + widget.model.reload_history() + assert started.wait(5) + mocked_client.connector.lpush( + MessageEndpoints.scan_queue_history(), history_msg("h-2", scan_number=12) + ) + for _ in range(5): + widget.model.reload_history() + release.set() + wait_for_reads(qtbot, widget) + assert patched.call_count == 2 + assert [e.queue_id for e in widget.model.finished] == ["h-2", "h-1"] + + +def test_no_toasts_anywhere(queue_widget): + from qtpy.QtWidgets import QFrame + + from bec_widgets.widgets.services.bec_queue import queue_ui + + assert not hasattr(queue_ui, "Toast") + assert not hasattr(queue_widget, "toast") + assert not [w for w in queue_widget.findChildren(QFrame) if w.objectName() == "queue_toast"] + + +def test_refusal_note_clears_after_a_while(queue_widget, qtbot, monkeypatch): + queue_widget._failure_timer.setInterval(100) + with mock.patch.object(queue_widget.client.queue, "request_queue_order_modification"): + queue_widget.move_scan("q-c", QueueMove.UP) + queue_widget.model.on_order_response({"accepted": False, "message": "Refused."}, {}) + assert queue_widget.waiting_hint.text() == "Refused." + qtbot.waitUntil(lambda: queue_widget.waiting_hint.text() != "Refused.", timeout=2000) + + +def test_pause_button_states(queue_widget, queue_infos): + button = queue_widget.pause_button + assert button.text() == "Pause queue" and button.isEnabled() + assert queue_widget.pause_icon_name == "pause" + with mock.patch.object(queue_widget.client.connector, "send") as send: + button.click() + assert [m.action for m in _sent_modifications(send)] == ["deferred_pause"] + assert button.text() == "Pausing…" and not button.isEnabled() + + paused = queue_status(queue_infos, status="PAUSED") + queue_widget.model.on_queue_status(paused.content, paused.metadata) + assert button.text() == "Resume queue" and button.isEnabled() + assert queue_widget.pause_icon_name == "play_arrow" + assert queue_widget.queue_chip.text() == "Paused" + with mock.patch.object(button, "setStyleSheet") as restyle: + queue_widget._render_header() + queue_widget._render_header() + restyle.assert_not_called() # no style churn while the state is unchanged + with mock.patch.object(queue_widget.client.queue, "request_scan_continuation") as resume: + button.click() + resume.assert_called_once() + + +def test_pause_button_idle_and_pending_timeout(qtbot, mocked_client, queue_infos): + push_state(mocked_client, queue_infos[1:]) + widget = create_queue(qtbot, mocked_client) + assert widget.pause_button.text() == "Pause queue" + assert not widget.pause_button.isEnabled() + widget._pause_requested_at = 0.0 # a pause that never landed falls back + widget._render_header() + assert widget.pause_button.text() == "Pause queue" + + +def test_queue_style_sheets_have_no_unknown_properties(qtbot, mocked_client, queue_infos): + from qtpy.QtCore import qInstallMessageHandler + + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + logged = [] + previous = qInstallMessageHandler(lambda _mode, _context, text: logged.append(text)) + try: + widget = create_queue(qtbot, mocked_client) + widget.select("q-a") + widget.resize(420, 600) + widget.show() + qtbot.waitExposed(widget) + widget.grab() + finally: + qInstallMessageHandler(previous) + assert not [m for m in logged if "Unknown property" in m] + + +def test_rpc_remove_closes_the_widget_and_keeps_the_queue(queue_widget, qtbot): + """remove() is the BECConnector removal; removing a scan is remove_scan().""" + queue_widget.model.remove = mock.MagicMock() + with qtbot.waitSignal(queue_widget.widget_removed, timeout=1000): + queue_widget.remove() + queue_widget.model.remove.assert_not_called() + + +def test_theme_switch_restyles_the_header_and_status_icons_without_a_queue_update( + queue_widget, qtbot +): + from bec_widgets.utils.colors import apply_theme + from bec_widgets.utils.theme_utils import css, theme_colors + + apply_theme("light") + try: + status_icon = queue_widget.finished_rows.rows["h-1"].lead + light_warn = css(theme_colors()["warn"], 0.8) + light_icon = status_icon.pixmap().toImage().pixelColor(status_icon.pixmap().rect().center()) + assert light_warn in queue_widget.pause_button.styleSheet() + + with mock.patch.object(queue_widget.model, "changed") as changed: + apply_theme("dark") + changed.emit.assert_not_called() + dark_warn = css(theme_colors()["warn"], 0.8) + assert dark_warn != light_warn + assert dark_warn in queue_widget.pause_button.styleSheet() + assert light_warn not in queue_widget.pause_button.styleSheet() + dark_icon = status_icon.pixmap().toImage().pixelColor(status_icon.pixmap().rect().center()) + assert dark_icon != light_icon + finally: + apply_theme("light") + + +def test_escape_closes_the_drawer_after_a_profile_restored_the_focus_policy( + qtbot, mocked_client, queue_infos +): + """A dock area profile restores the queue's own Qt properties, focusPolicy included.""" + from qtpy.QtCore import QSize + + push_state(mocked_client, queue_infos) + widget = create_queue(qtbot, mocked_client) + widget.setProperty("minimumSize", QSize(0, 0)) + widget.setProperty("focusPolicy", Qt.FocusPolicy.NoFocus) + assert widget.minimumSizeHint().width() >= 300 + # a click on a row or on the drawer gives focus to these, and Esc propagates to the queue + assert widget.content.focusPolicy() == Qt.FocusPolicy.ClickFocus + assert widget.drawer.focusPolicy() == Qt.FocusPolicy.ClickFocus + + widget.select("q-b") + qtbot.keyClick(widget.waiting_rows.rows["q-b"], Qt.Key.Key_Escape) + assert widget.selected_key is None + widget.select("q-b") + qtbot.keyClick(widget.drawer.name_label, Qt.Key.Key_Escape) + assert widget.selected_key is None + + +@pytest.mark.parametrize("end_status", ["STOPPED", "COMPLETED"]) +def test_finished_scan_reaches_the_history_without_waiting_for_the_next_one( + qtbot, mocked_client, end_status +): + """The server publishes the end status, then pushes the history entry, then drops the item.""" + push_state(mocked_client, [make_info("q-1", status="RUNNING", scan_number=1)]) + widget = create_queue(qtbot, mocked_client) + assert widget.model.finished == [] + + # 1. the item ends, but it is still in the queue and not in the history yet + set_queue(widget, [make_info("q-1", status=end_status, scan_number=1)], status="RUNNING") + # 2. the worker pushes the history entry + mocked_client.connector.lpush( + MessageEndpoints.scan_queue_history(), history_msg("q-1", end_status, scan_number=1) + ) + # 3. the item is removed from the queue + set_queue(widget, [], status="RUNNING") + wait_for_reads(qtbot, widget) + + assert [entry.queue_id for entry in widget.model.finished] == ["q-1"] + assert "q-1" in widget.finished_rows.rows + + +def test_a_scan_finished_early_has_its_own_icon(qtbot, mocked_client, queue_infos): + from bec_lib import messages as bec_messages + + push_state( + mocked_client, + queue_infos, + history=[history_msg("h-1", scan_number=11), history_msg("h-2", scan_number=10)], + ) + early = mock.MagicMock(spec=bec_messages.ScanHistoryMessage) + early.scan_id, early.start_time, early.end_time = "scan-h-1", 1000.0, 1011.0 + early.exit_status = "user_completed" + done = mock.MagicMock(spec=bec_messages.ScanHistoryMessage) + done.scan_id, done.start_time, done.end_time = "scan-h-2", 900.0, 950.0 + done.exit_status = "closed" + with mock.patch.object(mocked_client.connector, "get_last", return_value=[early, done]): + widget = create_queue(qtbot, mocked_client) + finished_early = widget.finished_rows.rows["h-1"].lead + completed = widget.finished_rows.rows["h-2"].lead + assert (finished_early.icon_name, finished_early.tone) == ("flag_circle", Tone.ACCENT) + assert finished_early.toolTip().startswith("Finished early") + assert (completed.icon_name, completed.tone) == ("check_circle", Tone.OK) + assert completed.toolTip().startswith("Completed") + + +def test_every_view_shows_the_scan_by_its_own_name(qtbot, mocked_client, tmp_path): + from qtpy.QtCore import QSettings + + from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem + from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar + + infos = [ + make_info( + "q-run", status="RUNNING", scan_number=12, user_metadata={"scan_name": "My Scan"} + ), + make_info("q-a", user_metadata={"scan_name": "Next Scan"}), + ] + push_state(mocked_client, infos) + queue = create_queue(qtbot, mocked_client) + bar = create_widget(qtbot, ScanProgressBar, client=mocked_client) + pill = create_widget( + qtbot, + ScanStatusItem, + client=mocked_client, + settings=lambda: QSettings(str(tmp_path / "pill.ini"), QSettings.Format.IniFormat), + ) + pill.set_width_mode("wide") + status = { + "scan_id": "scan-q-run", + "status": "open", + "scan_number": 12, + "scan_name": "line_scan", + "user_metadata": {"scan_name": "My Scan", "sample": "LaB6"}, + "request_inputs": {"arg_bundle": ["samx", -5, 5], "inputs": {}, "kwargs": {}}, + } + for tracker in (bar.tracker, queue.progress.tracker, pill.tracker): + tracker.on_scan_status(status, {"RID": "rid-q-run", "scan_id": "scan-q-run"}) + + for progress in (bar, queue.progress): + assert progress.title_label.full_text() == "#12 My Scan" + # the scan type is still one hover away + assert progress.header_row.toolTip().startswith("line_scan: samx -5 5") + assert pill.pill.text.startswith("#12 My Scan") + row = queue.waiting_rows.rows["q-a"] + assert row.name_label.text() == "Next Scan" + assert row.meta_label.full_text().startswith("line_scan") + + +def _answer_reset(choice): + """Stand in for the modal dialog: click its button with this text, or press Esc.""" + from qtpy.QtWidgets import QMessageBox + + shown = [] + + def exec_(box): + shown.append((box.windowTitle(), box.text(), box.informativeText(), box.defaultButton())) + if choice == "escape": + box.escapeButton().click() + return 0 + next(b for b in box.buttons() if b.text().replace("&", "") == choice).click() + return 0 + + return mock.patch.object(QMessageBox, "exec", exec_), shown + + +def test_reset_queue_asks_first_and_resets_on_confirm(queue_widget): + queue_widget.model.client.queue.request_queue_reset = mock.MagicMock() + patch, shown = _answer_reset("Reset queue") + with patch: + queue_widget.reset_action.trigger() + queue_widget.model.client.queue.request_queue_reset.assert_called_once_with() + _title, text, details, default = shown[0] # macOS message boxes have no window title + assert text == "Reset the scan queue?" + assert "stops the running scan #12 line_scan" in details + assert "removes the 3 waiting scans" in details + assert details.endswith("This cannot be undone.") + assert default.text().replace("&", "") == "Cancel" + + +@pytest.mark.parametrize("choice", ["Cancel", "escape"]) +def test_reset_queue_cancel_does_nothing(queue_widget, choice): + queue_widget.model.client.queue.request_queue_reset = mock.MagicMock() + patch, _shown = _answer_reset(choice) + with patch: + queue_widget.reset_action.trigger() + queue_widget.model.client.queue.request_queue_reset.assert_not_called() + + +def test_reset_queue_is_offered_only_when_there_is_something_to_reset(qtbot, mocked_client): + push_state(mocked_client, []) + widget = create_queue(qtbot, mocked_client) + assert not widget.reset_action.isEnabled() + set_queue(widget, [make_info("q-a")], status="PAUSED") + assert widget.reset_action.isEnabled() + assert widget.more_button.menu().actions() == [widget.reset_action] + assert widget.more_button.focusPolicy() == Qt.FocusPolicy.TabFocus + + +def test_queue_actions_are_reported_with_their_enum_kind(queue_widget): + from bec_widgets.widgets.services.bec_queue.queue_model import QueueAction + + model = queue_widget.model + sent, failed = [], [] + model.action_sent.connect(lambda kind, key, _text: sent.append((kind, key))) + model.action_failed.connect(lambda kind, key, _text: failed.append((kind, key))) + with mock.patch.object(queue_widget.client.connector, "send"): + model.pause() + model.resume() + with mock.patch.object(model.client.queue, "request_scan_abortion"): + model.remove("q-a") + with mock.patch.object(model.client.queue, "request_queue_order_modification"): + model.move("q-b", QueueMove.UP) + model.on_order_response({"accepted": False, "message": "The running scan cannot be moved."}, {}) + assert sent == [ + (QueueAction.PAUSE, ""), + (QueueAction.RESUME, ""), + (QueueAction.REMOVE, "q-a"), + (QueueAction.MOVE, "q-b"), + ] + assert failed == [(QueueAction.MOVE, "q-b")] + # the slots get the enum itself, not a plain str + assert all(type(kind) is QueueAction for kind, _ in sent + failed) + + +def test_deleting_while_a_read_is_in_flight_is_safe(qtbot, mocked_client, queue_infos): + from qtpy.QtWidgets import QApplication + + push_state(mocked_client, queue_infos, history=[history_msg("h-1", scan_number=11)]) + lrange, started, release = _blocking_lrange(mocked_client) + with mock.patch.object(mocked_client.connector, "lrange", side_effect=lrange): + widget = BECQueue(client=mocked_client) + assert started.wait(5) + model_destroyed = [] + widget.model.destroyed.connect(lambda: model_destroyed.append(True)) + widget.cleanup() + widget.deleteLater() # widget and model are gone before the read returns + qtbot.waitUntil(lambda: bool(model_destroyed), timeout=2000) + release.set() + qtbot.waitUntil(lambda: QThreadPool.globalInstance().activeThreadCount() == 0, timeout=5000) + QApplication.processEvents() # the late result has no receiver left; nothing raises diff --git a/tests/unit_tests/test_bec_widget_cell_widgets.py b/tests/unit_tests/test_bec_widget_cell_widgets.py index 54d1b376..de9bae54 100644 --- a/tests/unit_tests/test_bec_widget_cell_widgets.py +++ b/tests/unit_tests/test_bec_widget_cell_widgets.py @@ -15,7 +15,6 @@ import sys import pytest import shiboken6 -from bec_lib import messages from qtpy.QtCore import QEvent from qtpy.QtWidgets import ( QApplication, @@ -30,10 +29,8 @@ from qtpy.QtWidgets import ( from bec_widgets.tests.client_mocks import dap_plugin_message, mocked_client, mocked_client_with_dap from bec_widgets.utils.bec_widget import BECWidget -from bec_widgets.widgets.control.buttons.button_abort.button_abort import AbortButton from bec_widgets.widgets.plots.waveform.settings.curve_settings.curve_tree import CurveTree from bec_widgets.widgets.plots.waveform.waveform import Waveform -from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue from .conftest import create_widget @@ -90,44 +87,6 @@ class ViewHost(BECWidget, QWidget): return (self.table, self.tree, self.list) -def _queue_entry(scan_number: int, rid: str, status: str = "PENDING") -> dict: - """Build a single primary-queue entry with one request block.""" - msg = messages.ScanQueueMessage( - metadata={"RID": rid}, scan_type="line_scan", parameter={"args": {}, "kwargs": {}} - ) - return { - "queue_id": f"queue-{scan_number}", - "scan_id": [f"scan-{scan_number}"], - "is_scan": [True], - "request_blocks": [ - { - "msg": msg, - "RID": rid, - "readout_priority": {"monitored": [], "baseline": [], "on_request": []}, - "is_scan": True, - "scan_number": scan_number, - "scan_id": f"scan-{scan_number}", - } - ], - "scan_number": [scan_number], - "status": status, - } - - -def _three_row_queue_content() -> dict: - content = { - "primary": { - "info": [ - _queue_entry(1001, "rid-1001", status="RUNNING"), - _queue_entry(1002, "rid-1002"), - _queue_entry(1003, "rid-1003"), - ], - "status": "RUNNING", - } - } - return messages.ScanQueueStatusMessage(metadata={}, queue=content).content - - ##################################################################### # Scenarios, executed only inside the child process ##################################################################### @@ -172,24 +131,6 @@ def test_inner_nested_view_close_releases_cell_widgets(qtbot, mocked_client): assert all(table.cellWidget(row, 0) is None for row in range(3)) -@inner_only -def test_inner_bec_queue_close_then_relayout(qtbot, mocked_client): - queue = BECQueue(client=mocked_client, refresh_upon_start=False) - qtbot.addWidget(queue) - qtbot.waitExposed(queue) - queue.update_queue(_three_row_queue_content(), {}) - assert queue.table.rowCount() == 3 - buttons = [queue.table.cellWidget(row, 4) for row in range(3)] - assert all(isinstance(button, AbortButton) for button in buttons) - - queue.close() - _flush_deferred_deletes() - queue.table.updateEditorGeometries() # SIGSEGV on the deleted abort buttons - - assert not any(shiboken6.isValid(button) for button in buttons) - assert all(queue.table.cellWidget(row, 4) is None for row in range(3)) - - @inner_only def test_inner_curve_tree_close_then_relayout(qtbot, mocked_client_with_dap): """Guard: CurveTree keeps BEC combo boxes in tree cells and removes its rows on cleanup.""" @@ -222,7 +163,6 @@ def test_inner_curve_tree_close_then_relayout(qtbot, mocked_client_with_dap): [ "test_inner_view_host_close_releases_cell_widgets", "test_inner_nested_view_close_releases_cell_widgets", - "test_inner_bec_queue_close_then_relayout", "test_inner_curve_tree_close_then_relayout", ], ) diff --git a/tests/unit_tests/test_scan_progress_bar.py b/tests/unit_tests/test_scan_progress_bar.py index 76032450..8fb5c02a 100644 --- a/tests/unit_tests/test_scan_progress_bar.py +++ b/tests/unit_tests/test_scan_progress_bar.py @@ -1044,6 +1044,102 @@ def test_unstretched_stop_has_the_bar_height_on_both_segments(qtbot, mocked_clie qtbot.waitUntil(lambda: not bar.stretched and aligned(34), timeout=1000) +def test_hook_broadcasts_reach_every_scan_progress_in_the_app(qtbot, mocked_client, tmp_path): + """A docked ScanProgressBar, the queue's running card and the status-bar pill side by side.""" + from qtpy.QtCore import QSettings + + from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem + from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue + + docked = create_widget(qtbot, ScanProgressBar, client=mocked_client) + queue = create_widget(qtbot, BECQueue, client=mocked_client) + pill = create_widget( + qtbot, + ScanStatusItem, + client=mocked_client, + settings=lambda: QSettings(str(tmp_path / "pill.ini"), QSettings.Format.IniFormat), + ) + pill.set_width_mode("wide") + trackers = [docked.tracker, queue.progress.tracker, pill.tracker] + progresses = [docked, queue.progress] + + def send(method, *args): + for tracker in trackers: + getattr(tracker, method)(*args) + + send("on_scan_status", *status(num_points=10)) + staging = [{"device": ["samx", "bpm4i"], "action": "stage", "parameter": {}}] + send("on_scan_hook", *hook("stage", 1.0, instructions=staging)) + for progress in progresses: + assert progress.state_chip.text() == "Staging" + assert progress.bar.mode == BarMode.BUSY + assert progress.instruction_label.full_text() == "Staging samx, bpm4i" + assert pill.pill.mode == BarMode.BUSY and "Staging" in pill.pill.text + + move = [{"device": "samx", "action": "set", "parameter": {"value": -5.0}}] + send( + "on_scan_hook", + *hook("scan_core", 2.0, instructions=move, waiting=True, wait_started_at=2.0), + ) + send("on_scan_progress", {"value": 3, "max_value": 10, "done": False}, {"scan_id": "s1"}) + for progress in progresses: + assert progress.state_chip.text() == "Measuring" + assert progress.bar.mode == BarMode.PROGRESS + assert progress.instruction_label.full_text() == "Waiting for samx to reach -5" + assert pill.pill.mode == BarMode.PROGRESS + assert "Point 3 of 10" in pill.pill.text # the pill shows points; the card has the line + + +def test_every_stop_button_has_the_same_colours(qtbot, mocked_client, tmp_path): + """ScanControl, the status bar pill, the queue's running card and a docked progress bar.""" + from bec_lib import messages + from bec_lib.endpoints import MessageEndpoints + from qtpy.QtCore import QSettings + + from bec_widgets.utils.colors import apply_theme + from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem + from bec_widgets.widgets.control.scan_control.scan_control import ScanControl + from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue + + def stops(): + return { + "scan_control": scan_control.button_stop_scan, + "pill": pill.stop_button, + "queue": queue.progress.stop_button, + "progress": docked.stop_button, + } + + def resolved(stop): + return {k: v.name(v.NameFormat.HexArgb) for k, v in stop.style_colors().items()} + + mocked_client.connector.set_and_publish( + MessageEndpoints.available_scans(), messages.AvailableResourceMessage(resource={}) + ) + scan_control = create_widget(qtbot, ScanControl, client=mocked_client) + pill = create_widget( + qtbot, + ScanStatusItem, + client=mocked_client, + settings=lambda: QSettings(str(tmp_path / "pill.ini"), QSettings.Format.IniFormat), + ) + queue = create_widget(qtbot, BECQueue, client=mocked_client) + docked = create_widget(qtbot, ScanProgressBar, client=mocked_client) + try: + for theme in ("light", "dark"): + apply_theme(theme) + looks = {name: resolved(stop) for name, stop in stops().items()} + assert all(look == looks["scan_control"] for look in looks.values()), looks + # rest and hover rules in each style sheet carry the same colours + for stop in stops().values(): + colors = stop.style_colors() + sheet = stop.button.styleSheet() + for key in ("background", "hover_background", "hover_text"): + color = colors[key] + assert f"rgba({color.red()}, {color.green()}, {color.blue()}," in sheet + finally: + apply_theme("light") + + 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"