From 9367194e3525cd5ed02cfda221f9afb65572f138 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Mon, 16 Nov 2026 08:07:35 +0100 Subject: [PATCH] fix(scheduler): temperature controller items, row heights and layout - Store the temperature controller config as a plain dict and pass its values to load_config() as keyword arguments, so the item is JSON-serialisable; the item dialog now rejects non-JSON parameters with a clear message. - Size table rows to the word-wrapped text at the current column width and recompute them when columns resize, so long commands are shown in full. - Start the block guide line at the top of the first child row instead of drawing it over the parent's text. - Move the notes field below the schedule name and put the file save/load buttons on their own left-aligned row. Co-Authored-By: Claude Opus 5.5 --- .../bec_widgets/widgets/scheduler/actions.py | 9 ++- .../widgets/scheduler/item_dialog.py | 19 ++++- .../widgets/scheduler/schedule_table.py | 71 +++++++++++++------ .../widgets/scheduler/scheduler.py | 32 +++++---- .../tests_bec_widgets/test_scheduler_logic.py | 9 +++ 5 files changed, 102 insertions(+), 38 deletions(-) diff --git a/debye_bec/bec_widgets/widgets/scheduler/actions.py b/debye_bec/bec_widgets/widgets/scheduler/actions.py index 985e347..9d2571f 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/actions.py +++ b/debye_bec/bec_widgets/widgets/scheduler/actions.py @@ -445,7 +445,14 @@ register_action( # Temperature controller # ---------------------------------------------------------------------------------------------- # def _run_temperature_controller(ctx: ExecutionContext, config: dict): - return ctx.dev["univ_temp_cont"].load_config(config=config) + # Pass plain values: the device builds its own ConfigDict from them, so no pydantic object + # has to be stored in (or sent from) the schedule. + return ctx.dev["univ_temp_cont"].load_config( + power_mode=config["power_mode"], + target_setpoint=config["target_setpoint"], + ramp_rate=config["ramp_rate"], + ramp_rate_unit=config["ramp_rate_unit"], + ) def _describe_temperature_controller(params: dict, _beamline: str | None) -> str: diff --git a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py index 230f173..8249938 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py +++ b/debye_bec/bec_widgets/widgets/scheduler/item_dialog.py @@ -12,7 +12,9 @@ which maps 1:1 onto `ScheduleItem` fields. from __future__ import annotations +import json import math +from types import SimpleNamespace from typing import Callable from bec_lib.logger import bec_logger @@ -481,8 +483,12 @@ class ScheduleItemDialog(QDialog): "temperature_controller", "Temperature Controller", page, - lambda: {"config": self.temperature_controller.get_config()}, - lambda params: self.temperature_controller.load_config(params["config"]), + # get_config() returns a pydantic ConfigDict; store it as a plain (JSON) dict. + lambda: {"config": self.temperature_controller.get_config().model_dump(mode="json")}, + # load_config() only reads attributes, so a namespace over the stored dict suffices. + lambda params: self.temperature_controller.load_config( + SimpleNamespace(**params["config"]) + ), ) # ------------------------------------------------------------------------------------------ # @@ -568,6 +574,15 @@ class ScheduleItemDialog(QDialog): except ValueError as exc: QMessageBox.warning(self, "Invalid item", str(exc)) return + try: + json.dumps(params) + except TypeError as exc: + # A page returned a non-JSON value (e.g. a pydantic model) - a programming error. + logger.error(f"Parameters of {action!r} are not JSON-serialisable: {params!r}") + QMessageBox.critical( + self, "Invalid item", f"The item parameters cannot be saved (not JSON): {exc}" + ) + return self._result = { "action": action, "params": params, diff --git a/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py index d1929ed..84f8a40 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py +++ b/debye_bec/bec_widgets/widgets/scheduler/schedule_table.py @@ -18,7 +18,7 @@ from bec_qthemes import material_icon from bec_widgets.utils.colors import get_accent_colors # pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint -from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, Signal +from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, QTimer, Signal from qtpy.QtGui import QKeySequence, QPen from qtpy.QtWidgets import QHeaderView, QStyle, QStyledItemDelegate, QTableView @@ -236,57 +236,73 @@ def _paint_background(painter, option) -> None: class _TextDelegate(QStyledItemDelegate): """ - Paints multi-line text (labels contain explicit line breaks) and reports the full multi-line - height, so the view's ResizeToContents row mode can fit it. If `indent` is True, the text is - indented by the item's block depth and the block guide line is drawn. + Paints word-wrapped, multi-line text and reports the height the wrapped text needs at the + current column width, so the view's ResizeToContents row mode shows the full text. If + `indent` is True, the text is indented by the item's block depth and the block guide line + is drawn. Selection is painted with the palette highlight colour, like `BecLogTableView`. """ + _FLAGS = Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + _H_MARGIN = 6 + def __init__(self, parent=None, indent: bool = False): super().__init__(parent) self._indent = indent + def _text_rect(self, cell: QRect, index: QModelIndex) -> QRect: + """Area of the cell the text is drawn in (margins and block indentation removed).""" + rect = cell.adjusted(self._H_MARGIN, _ROW_MARGIN // 2, -self._H_MARGIN, -(_ROW_MARGIN // 2)) + if self._indent: + rect.setLeft(rect.left() + (index.data(DepthRole) or 0) * INDENT_WIDTH) + return rect + def paint(self, painter, option, index): painter.save() _paint_background(painter, option) painter.setFont(option.font) text_pen = painter.pen() - - rect = option.rect.adjusted(6, _ROW_MARGIN // 2, -6, -(_ROW_MARGIN // 2)) if self._indent: - depth = index.data(DepthRole) or 0 self._paint_guide(painter, option.rect, index.data(BlockRoleRole)) - rect.setLeft(rect.left() + depth * INDENT_WIDTH) painter.setPen(text_pen) text = index.data(Qt.ItemDataRole.DisplayRole) or "" - flags = ( - Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter - ) - painter.drawText(rect, int(flags), text) + painter.drawText(self._text_rect(option.rect, index), int(self._FLAGS), text) painter.restore() @staticmethod def _paint_guide(painter, rect: QRect, role: BlockRole | None) -> None: - if role in (None, BlockRole.NONE, BlockRole.PARENT_EMPTY): + """ + Draw the block guide line of a child row: a vertical line from the top edge of the row + (i.e. the bottom edge of the row above, ending there so it never crosses the parent's + text) down to the next child, plus a short tick towards the indented text. + """ + if role not in (BlockRole.CHILD, BlockRole.LAST_CHILD): return pen = QPen(get_accent_colors().highlight) pen.setWidth(2) painter.setPen(pen) x = rect.left() + 10 mid = rect.center().y() - if role == BlockRole.PARENT: - painter.drawLine(x, mid + 4, x, rect.bottom()) - else: - bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom() - painter.drawLine(x, rect.top(), x, bottom) - painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid) + bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom() + painter.drawLine(x, rect.top(), x, bottom) + painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid) def sizeHint(self, option, index): # noqa: N802 text = index.data(Qt.ItemDataRole.DisplayRole) or "" - lines = text.count("\n") + 1 - height = option.fontMetrics.lineSpacing() * lines + _ROW_MARGIN - return QSize(super().sizeHint(option, index).width(), max(height, ICON_SIZE + _ROW_MARGIN)) + view = self.parent() + column_width = ( + view.columnWidth(index.column()) + if isinstance(view, QTableView) + else option.rect.width() + ) + cell = QRect(0, 0, max(column_width, 1), 100000) + width = max(self._text_rect(cell, index).width(), 20) + text_height = option.fontMetrics.boundingRect( + QRect(0, 0, width, 100000), int(self._FLAGS), text + ).height() + height = max(text_height + _ROW_MARGIN, ICON_SIZE + _ROW_MARGIN) + return QSize(column_width, height) class _CenteredIconDelegate(QStyledItemDelegate): @@ -359,6 +375,17 @@ class ScheduleTableView(QTableView): for col in ScheduleTableModel.ICON_COLUMNS: self.setItemDelegateForColumn(col, icon_delegate) + # Wrapped text needs more or fewer lines when the stretching columns change width, so + # the row heights are recomputed (once per event-loop pass) after any column resize. + self._row_resize_timer = QTimer(self) + self._row_resize_timer.setSingleShot(True) + self._row_resize_timer.setInterval(0) + self._row_resize_timer.timeout.connect(self._resize_rows) + self.horizontalHeader().sectionResized.connect(self._row_resize_timer.start) + + def _resize_rows(self) -> None: + self.verticalHeader().resizeSections(QHeaderView.ResizeMode.ResizeToContents) + def configure_columns(self) -> None: """Apply the column sizing; call after `setModel()`.""" header = self.horizontalHeader() diff --git a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py index 37104c5..054d209 100644 --- a/debye_bec/bec_widgets/widgets/scheduler/scheduler.py +++ b/debye_bec/bec_widgets/widgets/scheduler/scheduler.py @@ -263,6 +263,14 @@ class Scheduler(BECWidget, QWidget): name_row.addStretch() layout.addLayout(name_row) + layout.addWidget(QLabel("Notes")) + self.notes_edit = QPlainTextEdit() + self.notes_edit.setPlaceholderText("Notes about this schedule...") + self.notes_edit.setPlainText(self.schedule.notes) + self.notes_edit.setMaximumHeight(100) + self.notes_edit.textChanged.connect(self._notes_save_timer.start) + layout.addWidget(self.notes_edit) + edit_row = QHBoxLayout() self.add_btn = AccentButton("Add") self.edit_btn = AccentButton("Edit") @@ -303,13 +311,6 @@ class Scheduler(BECWidget, QWidget): self.table_view.pastePressed.connect(self._on_paste_clicked) layout.addWidget(self.table_view, 1) - layout.addWidget(QLabel("Notes")) - self.notes_edit = QPlainTextEdit() - self.notes_edit.setPlaceholderText("Notes about this schedule...") - self.notes_edit.setPlainText(self.schedule.notes) - self.notes_edit.setMaximumHeight(100) - self.notes_edit.textChanged.connect(self._notes_save_timer.start) - layout.addWidget(self.notes_edit) return group def _build_states_group(self) -> QGroupBox: @@ -353,7 +354,11 @@ class Scheduler(BECWidget, QWidget): def _build_settings_group(self) -> QGroupBox: group = QGroupBox("Settings") - row = QHBoxLayout(group) + layout = QVBoxLayout(group) + notifications_row = QHBoxLayout() + file_row = QHBoxLayout() + layout.addLayout(notifications_row) + layout.addLayout(file_row) self.notifications_btn = AccentButton("Notifications") self.notifications_btn.clicked.connect(self._on_notifications_clicked) self.notification_status_label = QLabel() @@ -361,11 +366,12 @@ class Scheduler(BECWidget, QWidget): self.save_file_btn.clicked.connect(self._on_save_to_file_clicked) self.load_file_btn = AccentButton("Load from file") self.load_file_btn.clicked.connect(self._on_load_from_file_clicked) - row.addWidget(self.notifications_btn) - row.addWidget(self.notification_status_label) - row.addStretch() - row.addWidget(self.save_file_btn) - row.addWidget(self.load_file_btn) + notifications_row.addWidget(self.notifications_btn) + notifications_row.addWidget(self.notification_status_label) + notifications_row.addStretch() + file_row.addWidget(self.save_file_btn) + file_row.addWidget(self.load_file_btn) + file_row.addStretch() return group @SafeSlot(str) diff --git a/tests/tests_bec_widgets/test_scheduler_logic.py b/tests/tests_bec_widgets/test_scheduler_logic.py index e53d534..7267177 100644 --- a/tests/tests_bec_widgets/test_scheduler_logic.py +++ b/tests/tests_bec_widgets/test_scheduler_logic.py @@ -309,3 +309,12 @@ def test_schedule_from_document_never_raises(): assert schedule is None and problem schedule, problem = schedule_from_document({"schedule_name": "s", "items": []}) assert problem is None and schedule.schedule_name == "s" + + +def test_run_temperature_controller_passes_plain_values(): + dev = {"univ_temp_cont": mock.MagicMock()} + params = SAMPLE_PARAMS["temperature_controller"] + run_action(ExecutionContext(scans=None, dev=dev), "temperature_controller", params) + dev["univ_temp_cont"].load_config.assert_called_once_with( + power_mode="On", target_setpoint=120, ramp_rate=10, ramp_rate_unit="K/min" + )