feat(bec_queue): replace the scan queue with a list and detail view

This commit is contained in:
wyzula_j authored and Jan Wyzula committed 2026-11-09 13:55:29 +01:00
1 parent d918df79d9
commit 63bb68dbce
8 files changed
+3515 -635

No files matched your search

+1 -1
View File
@@ -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"
+1 -1
View File
@@ -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",
File diff suppressed because it is too large. Load diff
@@ -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")
@@ -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()
File diff suppressed because it is too large. Load diff
@@ -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",
],
)
@@ -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"