mirror of
https://github.com/bec-project/bec_widgets.git
synced 2026-05-09 08:12:15 +02:00
Compare commits
310 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 389519013d | |||
| bf483dedf1 | |||
| 1e8b135b6a | |||
| 8ca0e297cf | |||
| 494c3bafb3 | |||
| 5cdd8c56f2 | |||
| 7715439d25 | |||
| f95aee2091 | |||
| f7616102d8 | |||
| 5a497c3598 | |||
| 23e3644619 | |||
| a5db2dc340 | |||
| 2e8f43fcac | |||
| 09bb1121d8 | |||
| c9aaa77b3c | |||
| f7a1ee49a4 | |||
| 8e51c1adb6 | |||
| 846b6e6968 | |||
| f562c61e3c | |||
| bda5d38965 | |||
| 9b0ec9dd79 | |||
| 1754e759f0 | |||
| 308e84d0e1 | |||
| fa2ef83bb9 | |||
| 02cb393bb0 | |||
| 1d3e0214fd | |||
| 37747babda | |||
| 32f5d486d3 | |||
| 0ff1fdc815 | |||
| c7de320ca5 | |||
| 5b23dce3d0 | |||
| 5e84d3bec6 | |||
| 9a2396ee9c | |||
| 2dab16b684 | |||
| e6c8cd0b1a | |||
| 242f8933b2 | |||
| 83ac6bcd37 | |||
| 90ecd8ea87 | |||
| 6e5f6e7fbb | |||
| 2f75aaea16 | |||
| 677550931b | |||
| 96b5179658 | |||
| e25b6604d1 | |||
| f74c5a4516 | |||
| a2923752c2 | |||
| a486c52058 | |||
| 31389a3dd0 | |||
| 1676efc1ea | |||
| 05c38d9b82 | |||
| f67b60ac98 | |||
| 5ec59d5dbb | |||
| d46ffb59f0 | |||
| da400d20b6 | |||
| 20f06d8659 | |||
| 3d29a67c0b | |||
| e7ef8a3891 | |||
| 90222f3082 | |||
| 79af15a88b | |||
| ad01011a3e | |||
| d4ecefd80a | |||
| d4afcb6832 | |||
| 2b0f575733 | |||
| 0c6f3f8352 | |||
| 48c9c83bb0 | |||
| ab223d5fdc | |||
| 137e572a94 | |||
| b14b046882 | |||
| a7a9458180 | |||
| 23c146b3e6 | |||
| df44d9b50e | |||
| de941d1bc5 | |||
| 34e80ee8f9 | |||
| d1a1d85abd | |||
| 8e53ae2d39 | |||
| 889e9c0994 | |||
| f565deb71d | |||
| 895b318990 | |||
| 3a17a249ed | |||
| 598c453a18 | |||
| 63059a4ef8 | |||
| ec58fbd6d8 | |||
| 17708730fc | |||
| 1384a329ab | |||
| da1dc85b44 | |||
| 28be696f7c | |||
| 008c3a223a | |||
| b9145d762c | |||
| 37a5dc2e9e | |||
| 1351fcd47b | |||
| 14a6b04b11 | |||
| 4c9d7fddce | |||
| 39ecb89196 | |||
| 974f25997d | |||
| e061fa31a9 | |||
| 718f99527c | |||
| bd5aafc052 | |||
| b4f6f5aa8b | |||
| 14d51b8016 | |||
| e94554b471 | |||
| 7e0e391888 | |||
| 53e5ec42b8 | |||
| 0e49828a23 | |||
| 278d8de058 | |||
| cb4c2beed4 | |||
| 4382d5c9b1 | |||
| 8463b32792 | |||
| 5aff336446 | |||
| e2daf2e89c | |||
| ef1233163c | |||
| 419c01bdd4 | |||
| d4e037f338 | |||
| e157f0d7c9 | |||
| 2136699806 | |||
| 75697f5b1f | |||
| 2697496515 | |||
| 56f16b6352 | |||
| ab3efdbd0a | |||
| 0b94ee1485 | |||
| 72e66cf57f | |||
| e6b41b4e92 | |||
| ac824f6b83 | |||
| 5e34c8a351 | |||
| 29ff45a24b | |||
| bfc9f19472 | |||
| 5bcf440be7 | |||
| 758956be09 | |||
| 010373fd5b | |||
| 0eabd0f72b | |||
| 963941a788 | |||
| f8be43741a | |||
| 4d41be61b5 | |||
| 04b448e183 | |||
| 654aeb7116 | |||
| 3d049d67a9 | |||
| de6c6284ad | |||
| 2826919c5a | |||
| a1a400f540 | |||
| fcb43066e4 | |||
| 83489b7519 | |||
| 7bcdc31f11 | |||
| 3ffdf11c3e | |||
| 0d05839e9e | |||
| a632f35c40 | |||
| 3a5317be53 | |||
| 041afc68b1 | |||
| 047ff2bef7 | |||
| 5f46fa0994 | |||
| 8b782ac302 | |||
| 00bf01c129 | |||
| 4a44ede8fe | |||
| b93fbc5cd3 | |||
| c1d4758e4c | |||
| 4fc252220d | |||
| 375d131109 | |||
| 5b15c75b88 | |||
| b29648e10b | |||
| 7507f27d68 | |||
| b798ea2340 | |||
| ab9688d2b5 | |||
| 92ae5fc7fb | |||
| cd9c7ab079 | |||
| fb55e72713 | |||
| 71ed2d353a | |||
| 338ff455cc | |||
| 48387c0ad9 | |||
| 37298c21c3 | |||
| 80c0dfa4f2 | |||
| 6c73307bb4 | |||
| 940face118 | |||
| fbddf4a284 | |||
| cfd6bde268 | |||
| dd69578b91 | |||
| 4357d984c8 | |||
| 7cce3bd542 | |||
| 3f76ade628 | |||
| 84d6653d19 | |||
| 7fd7f67857 | |||
| 2992939b0f | |||
| a84b924162 | |||
| 5435fec68a | |||
| 38eb2441cd | |||
| d9b728584f | |||
| 947bf63e03 | |||
| 3fe6a00708 | |||
| 793779db68 | |||
| de835e81d8 | |||
| fa56fc8802 | |||
| c1443fa27a | |||
| 8bbd519559 | |||
| 9c4a54493a | |||
| a9f92cf155 | |||
| 12b4d3a9e0 | |||
| 229da6244a | |||
| 4edc57158b | |||
| 72639e7e5f | |||
| b67f3a14aa | |||
| fa49322d1f | |||
| 24701c2a27 | |||
| caba3a55f3 | |||
| 94faaba24d | |||
| 332ca205c1 | |||
| 5deafb9797 | |||
| 1f363d9bd4 | |||
| c61d00e761 | |||
| 3236dfb07f | |||
| 853f16ad3a | |||
| 6cff8d7a41 | |||
| a56bd572a0 | |||
| e26a90c62f | |||
| 6113debc6c | |||
| 56b1e6687f | |||
| 168bb3cb77 | |||
| 0752f3d6a9 | |||
| 08e19858ea | |||
| f6712e8bb8 | |||
| 66a95102dd | |||
| dea73a97c9 | |||
| 7ab8e0c2ed | |||
| 6baf1962fa | |||
| 6296055c66 | |||
| 5e111cfc54 | |||
| 836fedd50e | |||
| 89d5c5abdb | |||
| 1d654bd8bd | |||
| 7805c7a191 | |||
| f827e77e87 | |||
| 36be5292da | |||
| 7c28364594 | |||
| b43b6e844b | |||
| eda30e3139 | |||
| aba67d3129 | |||
| 6883982bf6 | |||
| 013b916ca3 | |||
| be55bf20c1 | |||
| 9c66dd5991 | |||
| 8f44213ecc | |||
| 22df7bb532 | |||
| beca23e14e | |||
| 06745e0511 | |||
| 6459281387 | |||
| 3c16909a87 | |||
| a6583ad53f | |||
| 88b6e015bf | |||
| 0d6b94aaec | |||
| 7d2760eab8 | |||
| b841cfbc5f | |||
| 6b2b42f21a | |||
| 522934f8cd | |||
| 96a52a0cb0 | |||
| 7ccfcc9f52 | |||
| c9a8e64217 | |||
| d085f65153 | |||
| c53d4c0ad7 | |||
| 3631fc2649 | |||
| 31364772bd | |||
| 5e0c376774 | |||
| fa79179f89 | |||
| 7083f94f46 | |||
| a6357af8ff | |||
| 3ebac55e2d | |||
| 6fc524c819 | |||
| f98a5de7e9 | |||
| 323c8d5bc0 | |||
| 96060fca53 | |||
| c1d0e435d5 | |||
| 84c7360bb8 | |||
| 440cecddf7 | |||
| 19b7310433 | |||
| bcaf013d2b | |||
| b72bf4a0f9 | |||
| f38cd3e3a0 | |||
| 2f9d6d59ee | |||
| 7ea4352a09 | |||
| ac850ec650 | |||
| 4d40918b7c | |||
| ed0d34a60f | |||
| 58b88efcb6 | |||
| cab422777c | |||
| 7305498475 | |||
| 06cb187d1a | |||
| 1c18810e5f | |||
| 338b9e1aa7 | |||
| ed2651a914 | |||
| 0b9e5c15af | |||
| 9b753c1f24 | |||
| 17e678b0ad | |||
| bdef594b58 | |||
| 66f3e517f0 | |||
| 4c4fc25a42 | |||
| 9e4be38c0b | |||
| 5ac629de8c | |||
| 90ba505c10 | |||
| c923f79293 | |||
| b30e1e4c5e | |||
| 9c3a6e1691 | |||
| 92c15a7f82 | |||
| 4b5a45c320 | |||
| b0cd619d7d | |||
| d25314e6ee | |||
| 55c8a57e71 | |||
| 37bfad7174 | |||
| 98e29792a2 | |||
| 82dbf31da5 | |||
| db83576346 | |||
| 389a93f8d0 | |||
| b6d70c34df | |||
| d301fdfeb2 | |||
| 562001c08c | |||
| ade65dd629 | |||
| 709ffd6927 |
@@ -62,4 +62,4 @@ runs:
|
||||
uv pip install --system -e ./ophyd_devices
|
||||
uv pip install --system -e ./bec/bec_lib[dev]
|
||||
uv pip install --system -e ./bec/bec_ipython_client
|
||||
uv pip install --system -e ./bec_widgets[dev,pyside6]
|
||||
uv pip install --system -e ./bec_widgets[dev,qtermwidget]
|
||||
|
||||
@@ -55,5 +55,5 @@ jobs:
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pytest-logs
|
||||
path: ./logs/*.log
|
||||
path: ./bec/logs/*.log
|
||||
retention-days: 7
|
||||
|
||||
+3
-1
@@ -177,4 +177,6 @@ cython_debug/
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
#.idea/
|
||||
#
|
||||
tombi.toml
|
||||
|
||||
+1037
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from bec_lib import bec_logger
|
||||
|
||||
from bec_widgets.widgets.containers.auto_update.auto_updates import AutoUpdates
|
||||
@@ -9,37 +11,32 @@ logger = bec_logger.logger
|
||||
|
||||
|
||||
def dock_area(
|
||||
object_name: str | None = None, profile: str | None = None, start_empty: bool = False
|
||||
object_name: str | None = None, startup_profile: str | Literal["restore", "skip"] | None = None
|
||||
) -> BECDockArea:
|
||||
"""
|
||||
Create an advanced dock area using Qt Advanced Docking System.
|
||||
|
||||
Args:
|
||||
object_name(str): The name of the advanced dock area.
|
||||
profile(str|None): Optional profile to load; if None the "general" profile is used.
|
||||
start_empty(bool): If True, start with an empty dock area when loading specified profile.
|
||||
startup_profile(str | Literal["restore", "skip"] | None): Startup mode for
|
||||
the workspace:
|
||||
- None: start empty
|
||||
- "restore": restore last used profile
|
||||
- "skip": do not initialize profile state
|
||||
- "<name>": load specific profile
|
||||
|
||||
Returns:
|
||||
BECDockArea: The created advanced dock area.
|
||||
|
||||
Note:
|
||||
The "general" profile is mandatory and will always exist. If manually deleted,
|
||||
it will be automatically recreated.
|
||||
"""
|
||||
# Default to "general" profile when called from CLI without specifying a profile
|
||||
effective_profile = profile if profile is not None else "general"
|
||||
|
||||
widget = BECDockArea(
|
||||
object_name=object_name,
|
||||
restore_initial_profile=True,
|
||||
root_widget=True,
|
||||
profile_namespace="bec",
|
||||
init_profile=effective_profile,
|
||||
start_empty=start_empty,
|
||||
)
|
||||
logger.info(
|
||||
f"Created advanced dock area with profile: {effective_profile}, start_empty: {start_empty}"
|
||||
startup_profile=startup_profile,
|
||||
)
|
||||
logger.info(f"Created advanced dock area with startup_profile: {startup_profile}")
|
||||
return widget
|
||||
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ if TYPE_CHECKING: # pragma: no cover
|
||||
|
||||
logger = bec_logger.logger
|
||||
MODULE_PATH = os.path.dirname(bec_widgets.__file__)
|
||||
START_EMPTY_PROFILE_OPTION = "Start Empty (No Profile)"
|
||||
|
||||
|
||||
class LaunchTile(RoundedFrame):
|
||||
@@ -146,8 +147,7 @@ class LaunchTile(RoundedFrame):
|
||||
|
||||
# Action button
|
||||
self.action_button = QPushButton("Open")
|
||||
self.action_button.setStyleSheet(
|
||||
"""
|
||||
self.action_button.setStyleSheet("""
|
||||
QPushButton {
|
||||
background-color: #007AFF;
|
||||
border: none;
|
||||
@@ -159,8 +159,7 @@ class LaunchTile(RoundedFrame):
|
||||
QPushButton:hover {
|
||||
background-color: #005BB5;
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
self.layout.addWidget(self.action_button, alignment=Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
def _fit_label_to_width(self, label: QLabel, max_width: int, min_pt: int = 10):
|
||||
@@ -189,6 +188,7 @@ class LaunchTile(RoundedFrame):
|
||||
|
||||
class LaunchWindow(BECMainWindow):
|
||||
RPC = True
|
||||
PLUGIN = False
|
||||
TILE_SIZE = (250, 300)
|
||||
DEFAULT_LAUNCH_SIZE = (800, 600)
|
||||
USER_ACCESS = ["show_launcher", "hide_launcher"]
|
||||
@@ -353,7 +353,7 @@ class LaunchWindow(BECMainWindow):
|
||||
def _refresh_dock_area_profiles(self, preserve_selection: bool = True) -> None:
|
||||
"""
|
||||
Refresh the dock-area profile selector, optionally preserving the selection.
|
||||
Sets the combobox to the last used profile or "general" if no selection preserved.
|
||||
Defaults to Start Empty when no valid selection can be preserved.
|
||||
|
||||
Args:
|
||||
preserve_selection(bool): Whether to preserve the current selection or not.
|
||||
@@ -368,9 +368,10 @@ class LaunchWindow(BECMainWindow):
|
||||
)
|
||||
|
||||
profiles = list_profiles("bec")
|
||||
selector_items = [START_EMPTY_PROFILE_OPTION, *profiles]
|
||||
selector.blockSignals(True)
|
||||
selector.clear()
|
||||
for profile in profiles:
|
||||
for profile in selector_items:
|
||||
selector.addItem(profile)
|
||||
|
||||
if selected_text:
|
||||
@@ -379,21 +380,31 @@ class LaunchWindow(BECMainWindow):
|
||||
if idx >= 0:
|
||||
selector.setCurrentIndex(idx)
|
||||
else:
|
||||
# Selection no longer exists, fall back to last profile or "general"
|
||||
# Selection no longer exists, fall back to default startup selection.
|
||||
self._set_selector_to_default_profile(selector, profiles)
|
||||
else:
|
||||
# No selection to preserve, use last profile or "general"
|
||||
# No selection to preserve, use default startup selection.
|
||||
self._set_selector_to_default_profile(selector, profiles)
|
||||
selector.blockSignals(False)
|
||||
|
||||
def _set_selector_to_default_profile(self, selector: QComboBox, profiles: list[str]) -> None:
|
||||
"""
|
||||
Set the selector to the last used profile or "general" as fallback.
|
||||
Set the selector default.
|
||||
|
||||
Preference order:
|
||||
1) Start Empty option (if available)
|
||||
2) Last used profile
|
||||
3) First available profile
|
||||
|
||||
Args:
|
||||
selector(QComboBox): The combobox to set.
|
||||
profiles(list[str]): List of available profiles.
|
||||
"""
|
||||
start_empty_idx = selector.findText(START_EMPTY_PROFILE_OPTION, Qt.MatchFlag.MatchExactly)
|
||||
if start_empty_idx >= 0:
|
||||
selector.setCurrentIndex(start_empty_idx)
|
||||
return
|
||||
|
||||
# Try to get last used profile
|
||||
last_profile = get_last_profile(namespace="bec")
|
||||
if last_profile and last_profile in profiles:
|
||||
@@ -402,13 +413,6 @@ class LaunchWindow(BECMainWindow):
|
||||
selector.setCurrentIndex(idx)
|
||||
return
|
||||
|
||||
# Fall back to "general" profile
|
||||
if "general" in profiles:
|
||||
idx = selector.findText("general", Qt.MatchFlag.MatchExactly)
|
||||
if idx >= 0:
|
||||
selector.setCurrentIndex(idx)
|
||||
return
|
||||
|
||||
# If nothing else, select first item
|
||||
if selector.count() > 0:
|
||||
selector.setCurrentIndex(0)
|
||||
@@ -587,11 +591,14 @@ class LaunchWindow(BECMainWindow):
|
||||
"""
|
||||
tile = self.tiles.get("dock_area")
|
||||
if tile is None or tile.selector is None:
|
||||
profile = None
|
||||
startup_profile = None
|
||||
else:
|
||||
selection = tile.selector.currentText().strip()
|
||||
profile = selection if selection else None
|
||||
return self.launch("dock_area", profile=profile)
|
||||
if selection == START_EMPTY_PROFILE_OPTION:
|
||||
startup_profile = None
|
||||
else:
|
||||
startup_profile = selection if selection else None
|
||||
return self.launch("dock_area", startup_profile=startup_profile)
|
||||
|
||||
def _open_widget(self):
|
||||
"""
|
||||
|
||||
@@ -1,22 +1,29 @@
|
||||
from bec_qthemes import material_icon
|
||||
from qtpy.QtGui import QAction # type: ignore
|
||||
from qtpy.QtWidgets import QApplication, QHBoxLayout, QStackedWidget, QWidget
|
||||
|
||||
from bec_widgets.applications.navigation_centre.reveal_animator import ANIMATION_DURATION
|
||||
from bec_widgets.applications.navigation_centre.side_bar import SideBar
|
||||
from bec_widgets.applications.navigation_centre.side_bar_components import NavigationItem
|
||||
from bec_widgets.applications.views.admin_view.admin_view import AdminView
|
||||
from bec_widgets.applications.views.developer_view.developer_view import DeveloperView
|
||||
from bec_widgets.applications.views.device_manager_view.device_manager_view import DeviceManagerView
|
||||
from bec_widgets.applications.views.dock_area_view.dock_area_view import DockAreaView
|
||||
from bec_widgets.applications.views.view import ViewBase, WaveformViewInline, WaveformViewPopup
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
from bec_widgets.utils.guided_tour import GuidedTour
|
||||
from bec_widgets.utils.name_utils import sanitize_namespace
|
||||
from bec_widgets.utils.screen_utils import (
|
||||
apply_centered_size,
|
||||
available_screen_geometry,
|
||||
main_app_size_for_screen,
|
||||
)
|
||||
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
|
||||
from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow
|
||||
|
||||
|
||||
class BECMainApp(BECMainWindow):
|
||||
RPC = False
|
||||
PLUGIN = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -48,51 +55,58 @@ class BECMainApp(BECMainWindow):
|
||||
|
||||
self._add_views()
|
||||
|
||||
# Initialize guided tour
|
||||
self.guided_tour = GuidedTour(self)
|
||||
self._setup_guided_tour()
|
||||
|
||||
def _add_views(self):
|
||||
self.add_section("BEC Applications", "bec_apps")
|
||||
self.ads = BECDockArea(self, profile_namespace="bec", auto_profile_namespace=False)
|
||||
self.ads.setObjectName("MainWorkspace")
|
||||
self.dock_area = DockAreaView(self)
|
||||
self.device_manager = DeviceManagerView(self)
|
||||
self.developer_view = DeveloperView(self)
|
||||
# self.developer_view = DeveloperView(self) #TODO temporary disable until the bugs with BECShell are resolved
|
||||
self.admin_view = AdminView(self)
|
||||
|
||||
self.add_view(
|
||||
icon="widgets", title="Dock Area", id="dock_area", widget=self.ads, mini_text="Docks"
|
||||
)
|
||||
self.add_view(icon="widgets", title="Dock Area", widget=self.dock_area, mini_text="Docks")
|
||||
self.add_view(
|
||||
icon="display_settings",
|
||||
title="Device Manager",
|
||||
id="device_manager",
|
||||
widget=self.device_manager,
|
||||
mini_text="DM",
|
||||
)
|
||||
# TODO temporary disable until the bugs with BECShell are resolved
|
||||
# self.add_view(
|
||||
# icon="code_blocks",
|
||||
# title="IDE",
|
||||
# widget=self.developer_view,
|
||||
# mini_text="IDE",
|
||||
# exclusive=True,
|
||||
# )
|
||||
self.add_view(
|
||||
icon="code_blocks",
|
||||
title="IDE",
|
||||
widget=self.developer_view,
|
||||
id="developer_view",
|
||||
exclusive=True,
|
||||
icon="admin_panel_settings",
|
||||
title="Admin View",
|
||||
widget=self.admin_view,
|
||||
mini_text="Admin",
|
||||
from_top=False,
|
||||
)
|
||||
|
||||
if self._show_examples:
|
||||
self.add_section("Examples", "examples")
|
||||
waveform_view_popup = WaveformViewPopup(
|
||||
parent=self, id="waveform_view_popup", title="Waveform Plot"
|
||||
parent=self, view_id="waveform_view_popup", title="Waveform Plot"
|
||||
)
|
||||
waveform_view_stack = WaveformViewInline(
|
||||
parent=self, id="waveform_view_stack", title="Waveform Plot"
|
||||
parent=self, view_id="waveform_view_stack", title="Waveform Plot"
|
||||
)
|
||||
|
||||
self.add_view(
|
||||
icon="show_chart",
|
||||
title="Waveform With Popup",
|
||||
id="waveform_popup",
|
||||
widget=waveform_view_popup,
|
||||
mini_text="Popup",
|
||||
)
|
||||
self.add_view(
|
||||
icon="show_chart",
|
||||
title="Waveform InLine Stack",
|
||||
id="waveform_stack",
|
||||
widget=waveform_view_stack,
|
||||
mini_text="Stack",
|
||||
)
|
||||
@@ -100,6 +114,9 @@ class BECMainApp(BECMainWindow):
|
||||
self.set_current("dock_area")
|
||||
self.sidebar.add_dark_mode_item()
|
||||
|
||||
# Add guided tour to Help menu
|
||||
self._add_guided_tour_to_menu()
|
||||
|
||||
# --- Public API ------------------------------------------------------
|
||||
def add_section(self, title: str, id: str, position: int | None = None):
|
||||
return self.sidebar.add_section(title, id, position)
|
||||
@@ -115,7 +132,7 @@ class BECMainApp(BECMainWindow):
|
||||
*,
|
||||
icon: str,
|
||||
title: str,
|
||||
id: str,
|
||||
view_id: str | None = None,
|
||||
widget: QWidget,
|
||||
mini_text: str | None = None,
|
||||
position: int | None = None,
|
||||
@@ -129,7 +146,8 @@ class BECMainApp(BECMainWindow):
|
||||
Args:
|
||||
icon(str): Icon name for the nav item.
|
||||
title(str): Title for the nav item.
|
||||
id(str): Unique ID for the view/item.
|
||||
view_id(str, optional): Unique ID for the view/item. If omitted, uses mini_text;
|
||||
if mini_text is also omitted, uses title.
|
||||
widget(QWidget): The widget to add to the stack.
|
||||
mini_text(str, optional): Short text for the nav item when sidebar is collapsed.
|
||||
position(int, optional): Position to insert the nav item.
|
||||
@@ -142,10 +160,11 @@ class BECMainApp(BECMainWindow):
|
||||
|
||||
|
||||
"""
|
||||
resolved_id = sanitize_namespace(view_id or mini_text or title)
|
||||
item = self.sidebar.add_item(
|
||||
icon=icon,
|
||||
title=title,
|
||||
id=id,
|
||||
id=resolved_id,
|
||||
mini_text=mini_text,
|
||||
position=position,
|
||||
from_top=from_top,
|
||||
@@ -155,13 +174,15 @@ class BECMainApp(BECMainWindow):
|
||||
# Wrap plain widgets into a ViewBase so enter/exit hooks are available
|
||||
if isinstance(widget, ViewBase):
|
||||
view_widget = widget
|
||||
view_widget.view_id = id
|
||||
view_widget.view_id = resolved_id
|
||||
view_widget.view_title = title
|
||||
else:
|
||||
view_widget = ViewBase(content=widget, parent=self, id=id, title=title)
|
||||
view_widget = ViewBase(content=widget, parent=self, view_id=resolved_id, title=title)
|
||||
|
||||
view_widget.change_object_name(resolved_id)
|
||||
|
||||
idx = self.stack.addWidget(view_widget)
|
||||
self._view_index[id] = idx
|
||||
self._view_index[resolved_id] = idx
|
||||
return item
|
||||
|
||||
def set_current(self, id: str) -> None:
|
||||
@@ -170,6 +191,12 @@ class BECMainApp(BECMainWindow):
|
||||
|
||||
# Internal: route sidebar selection to the stack
|
||||
def _on_view_selected(self, vid: str) -> None:
|
||||
# Special handling for views that can not be switched to (e.g. dark mode toggle)
|
||||
# Not registered as proper view with a stack index, so we ignore any logic below
|
||||
# as it will anyways not result in a stack switch.
|
||||
idx = self._view_index.get(vid)
|
||||
if idx is None or not (0 <= idx < self.stack.count()):
|
||||
return
|
||||
# Determine current view
|
||||
current_index = self.stack.currentIndex()
|
||||
current_view = (
|
||||
@@ -195,6 +222,160 @@ class BECMainApp(BECMainWindow):
|
||||
if hasattr(new_view, "on_enter"):
|
||||
new_view.on_enter()
|
||||
|
||||
def _setup_guided_tour(self):
|
||||
"""
|
||||
Setup the guided tour for the main application.
|
||||
Registers key UI components and delegates to views for their internal components.
|
||||
"""
|
||||
tour_steps = []
|
||||
|
||||
# --- General Layout Components ---
|
||||
|
||||
# Register the sidebar toggle button
|
||||
toggle_step = self.guided_tour.register_widget(
|
||||
widget=self.sidebar.toggle,
|
||||
title="Sidebar Toggle",
|
||||
text="Click this button to expand or collapse the sidebar. When expanded, you can see full navigation item titles and section names.",
|
||||
)
|
||||
tour_steps.append(toggle_step)
|
||||
|
||||
# Register the sidebar icons
|
||||
sidebar_dock_area = self.sidebar.components.get("dock_area")
|
||||
if sidebar_dock_area:
|
||||
dock_step = self.guided_tour.register_widget(
|
||||
widget=sidebar_dock_area,
|
||||
title="Dock Area View",
|
||||
text="Click here to access the Dock Area view, where you can manage and arrange your dockable panels.",
|
||||
)
|
||||
tour_steps.append(dock_step)
|
||||
|
||||
sidebar_device_manager = self.sidebar.components.get("device_manager")
|
||||
if sidebar_device_manager:
|
||||
device_manager_step = self.guided_tour.register_widget(
|
||||
widget=sidebar_device_manager,
|
||||
title="Device Manager View",
|
||||
text="Click here to open the Device Manager view, where you can view and manage device configs.",
|
||||
)
|
||||
tour_steps.append(device_manager_step)
|
||||
|
||||
sidebar_developer_view = self.sidebar.components.get("developer_view")
|
||||
if sidebar_developer_view:
|
||||
developer_view_step = self.guided_tour.register_widget(
|
||||
widget=sidebar_developer_view,
|
||||
title="Developer View",
|
||||
text="Click here to access the Developer view to write scripts and macros.",
|
||||
)
|
||||
tour_steps.append(developer_view_step)
|
||||
|
||||
# Register the dark mode toggle
|
||||
dark_mode_item = self.sidebar.components.get("dark_mode")
|
||||
if dark_mode_item:
|
||||
dark_mode_step = self.guided_tour.register_widget(
|
||||
widget=dark_mode_item,
|
||||
title="Theme Toggle",
|
||||
text="Switch between light and dark themes. The theme preference is saved and will be applied when you restart the application.",
|
||||
)
|
||||
tour_steps.append(dark_mode_step)
|
||||
|
||||
# Register the client info label
|
||||
if hasattr(self, "_client_info_hover"):
|
||||
client_info_step = self.guided_tour.register_widget(
|
||||
widget=self._client_info_hover,
|
||||
title="Client Status",
|
||||
text="Displays status messages and information from the BEC Server.",
|
||||
)
|
||||
tour_steps.append(client_info_step)
|
||||
|
||||
# Register the scan progress bar if available
|
||||
if hasattr(self, "_scan_progress_hover"):
|
||||
progress_step = self.guided_tour.register_widget(
|
||||
widget=self._scan_progress_hover,
|
||||
title="Scan Progress",
|
||||
text="Monitor the progress of ongoing scans. Hover over the progress bar to see detailed information including elapsed time and estimated completion.",
|
||||
)
|
||||
tour_steps.append(progress_step)
|
||||
|
||||
# Register the notification indicator in the status bar
|
||||
if hasattr(self, "notification_indicator"):
|
||||
notif_step = self.guided_tour.register_widget(
|
||||
widget=self.notification_indicator,
|
||||
title="Notification Center",
|
||||
text="View system notifications, errors, and status updates. Click to filter notifications by type or expand to see all details.",
|
||||
)
|
||||
tour_steps.append(notif_step)
|
||||
|
||||
# --- View-Specific Components ---
|
||||
|
||||
# Register all views that can extend the tour
|
||||
for view_id, view_index in self._view_index.items():
|
||||
view_widget = self.stack.widget(view_index)
|
||||
if not view_widget or not hasattr(view_widget, "register_tour_steps"):
|
||||
continue
|
||||
|
||||
# Get the view's tour steps
|
||||
view_tour = view_widget.register_tour_steps(self.guided_tour, self)
|
||||
if view_tour is None:
|
||||
if hasattr(view_widget.content, "register_tour_steps"):
|
||||
view_tour = view_widget.content.register_tour_steps(self.guided_tour, self)
|
||||
if view_tour is None:
|
||||
continue
|
||||
|
||||
# Get the corresponding sidebar navigation item
|
||||
nav_item = self.sidebar.components.get(view_id)
|
||||
if not nav_item:
|
||||
continue
|
||||
|
||||
# Use the view's title for the navigation button
|
||||
nav_step = self.guided_tour.register_widget(
|
||||
widget=nav_item,
|
||||
title=view_tour.view_title,
|
||||
text=f"Let's explore the features of the {view_tour.view_title}.",
|
||||
)
|
||||
tour_steps.append(nav_step)
|
||||
tour_steps.extend(view_tour.step_ids)
|
||||
|
||||
# Create the tour with all registered steps
|
||||
if tour_steps:
|
||||
self.guided_tour.create_tour(tour_steps)
|
||||
|
||||
def start_guided_tour(self):
|
||||
"""
|
||||
Public method to start the guided tour.
|
||||
This can be called programmatically or connected to a menu/button action.
|
||||
"""
|
||||
self.guided_tour.start_tour()
|
||||
|
||||
def _add_guided_tour_to_menu(self):
|
||||
"""
|
||||
Add a 'Guided Tour' action to the Help menu.
|
||||
"""
|
||||
|
||||
# Find the Help menu
|
||||
menu_bar = self.menuBar()
|
||||
help_menu = None
|
||||
for action in menu_bar.actions():
|
||||
if action.text() == "Help":
|
||||
help_menu = action.menu()
|
||||
break
|
||||
|
||||
if help_menu:
|
||||
# Add separator before the tour action
|
||||
help_menu.addSeparator()
|
||||
|
||||
# Create and add the guided tour action
|
||||
tour_action = QAction("Start Guided Tour", self)
|
||||
tour_action.setIcon(material_icon("help"))
|
||||
tour_action.triggered.connect(self.start_guided_tour)
|
||||
tour_action.setShortcut("F1") # Add keyboard shortcut
|
||||
help_menu.addAction(tour_action)
|
||||
|
||||
def cleanup(self):
|
||||
for view_id, idx in self._view_index.items():
|
||||
view = self.stack.widget(idx)
|
||||
view.close()
|
||||
view.deleteLater()
|
||||
super().cleanup()
|
||||
|
||||
|
||||
def main(): # pragma: no cover
|
||||
"""
|
||||
@@ -213,6 +394,7 @@ def main(): # pragma: no cover
|
||||
args, qt_args = parser.parse_known_args(sys.argv[1:])
|
||||
|
||||
app = QApplication([sys.argv[0], *qt_args])
|
||||
app.setApplicationName("BEC")
|
||||
apply_theme("dark")
|
||||
w = BECMainApp(show_examples=args.examples)
|
||||
|
||||
|
||||
@@ -127,12 +127,10 @@ class NavigationItem(QWidget):
|
||||
self._icon_size_expanded = QtCore.QSize(26, 26)
|
||||
self.icon_btn.setIconSize(self._icon_size_collapsed)
|
||||
# Remove QToolButton hover/pressed background/outline
|
||||
self.icon_btn.setStyleSheet(
|
||||
"""
|
||||
self.icon_btn.setStyleSheet("""
|
||||
QToolButton:hover { background: transparent; border: none; }
|
||||
QToolButton:pressed { background: transparent; border: none; }
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
# Mini label below icon
|
||||
self.mini_lbl = QLabel(self._mini_text, self)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Module for Admin View."""
|
||||
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.applications.views.view import ViewBase
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.widgets.services.bec_atlas_admin_view.bec_atlas_admin_view import BECAtlasAdminView
|
||||
|
||||
|
||||
class AdminView(ViewBase):
|
||||
"""
|
||||
A view for administrators to change the current active experiment, manage messaging
|
||||
services, and more tasks reserved for users with admin privileges.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget | None = None,
|
||||
content: QWidget | None = None,
|
||||
*,
|
||||
view_id: str | None = None,
|
||||
title: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, content=content, view_id=view_id, title=title)
|
||||
self.admin_widget = BECAtlasAdminView(parent=self)
|
||||
self.set_content(self.admin_widget)
|
||||
|
||||
@SafeSlot()
|
||||
def on_exit(self) -> None:
|
||||
"""Called before the view is hidden.
|
||||
|
||||
Default implementation does nothing. Override in subclasses.
|
||||
"""
|
||||
self.admin_widget.logout()
|
||||
@@ -1,9 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.applications.views.developer_view.developer_widget import DeveloperWidget
|
||||
from bec_widgets.applications.views.view import ViewBase
|
||||
from bec_widgets.applications.views.view import ViewBase, ViewTourSteps
|
||||
|
||||
|
||||
class DeveloperView(ViewBase):
|
||||
@@ -16,13 +14,89 @@ class DeveloperView(ViewBase):
|
||||
parent: QWidget | None = None,
|
||||
content: QWidget | None = None,
|
||||
*,
|
||||
id: str | None = None,
|
||||
view_id: str | None = None,
|
||||
title: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, content=content, id=id, title=title)
|
||||
super().__init__(parent=parent, content=content, view_id=view_id, title=title, **kwargs)
|
||||
self.developer_widget = DeveloperWidget(parent=self)
|
||||
self.set_content(self.developer_widget)
|
||||
|
||||
def register_tour_steps(self, guided_tour, main_app) -> ViewTourSteps | None:
|
||||
"""Register Developer View components with the guided tour.
|
||||
|
||||
Args:
|
||||
guided_tour: The GuidedTour instance to register with.
|
||||
main_app: The main application instance (for accessing set_current).
|
||||
|
||||
Returns:
|
||||
ViewTourSteps | None: Model containing view title and step IDs.
|
||||
"""
|
||||
step_ids = []
|
||||
dev_widget = self.developer_widget
|
||||
|
||||
# IDE Toolbar
|
||||
def get_ide_toolbar():
|
||||
main_app.set_current("developer_view")
|
||||
return (dev_widget.toolbar, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_ide_toolbar,
|
||||
title="IDE Toolbar",
|
||||
text="Quick access to save files, execute scripts, and configure IDE settings. Use the toolbar to manage your code and execution.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
# IDE Explorer
|
||||
def get_ide_explorer():
|
||||
main_app.set_current("developer_view")
|
||||
return (dev_widget.explorer_dock.widget(), None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_ide_explorer,
|
||||
title="File Explorer",
|
||||
text="Browse and manage your macro files. Create new files, open existing ones, and organize your scripts.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
# IDE Editor
|
||||
def get_ide_editor():
|
||||
main_app.set_current("developer_view")
|
||||
return (dev_widget.monaco_dock.widget(), None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_ide_editor,
|
||||
title="Code Editor",
|
||||
text="Write and edit Python code with syntax highlighting, auto-completion, and signature help. Monaco editor provides a modern coding experience.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
# IDE Console
|
||||
def get_ide_console():
|
||||
main_app.set_current("developer_view")
|
||||
return (dev_widget.console_dock.widget(), None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_ide_console,
|
||||
title="BEC Shell Console",
|
||||
text="Interactive Python console with BEC integration. Execute commands, test code snippets, and interact with the BEC system in real-time.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
# IDE Plotting Area
|
||||
def get_ide_plotting():
|
||||
main_app.set_current("developer_view")
|
||||
return (dev_widget.plotting_ads, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_ide_plotting,
|
||||
title="Plotting Area",
|
||||
text="View plots and visualizations generated by your scripts. Arrange multiple plots in a flexible layout.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
return ViewTourSteps(view_title="Developer View", step_ids=step_ids)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
@@ -52,7 +126,11 @@ if __name__ == "__main__":
|
||||
_app.resize(width, height)
|
||||
developer_view = DeveloperView()
|
||||
_app.add_view(
|
||||
icon="code_blocks", title="IDE", widget=developer_view, id="developer_view", exclusive=True
|
||||
icon="code_blocks",
|
||||
title="IDE",
|
||||
widget=developer_view,
|
||||
view_id="developer_view",
|
||||
exclusive=True,
|
||||
)
|
||||
_app.show()
|
||||
# developer_view.show()
|
||||
|
||||
@@ -16,9 +16,9 @@ from bec_widgets.utils.toolbars.toolbar import ModularToolBar
|
||||
from bec_widgets.widgets.containers.dock_area.basic_dock_area import DockAreaWidget
|
||||
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
|
||||
from bec_widgets.widgets.containers.qt_ads import CDockWidget
|
||||
from bec_widgets.widgets.editors.bec_console.bec_console import BecConsole, BECShell
|
||||
from bec_widgets.widgets.editors.monaco.monaco_dock import MonacoDock
|
||||
from bec_widgets.widgets.editors.monaco.monaco_widget import MonacoWidget
|
||||
from bec_widgets.widgets.editors.web_console.web_console import BECShell, WebConsole
|
||||
from bec_widgets.widgets.utility.ide_explorer.ide_explorer import IDEExplorer
|
||||
|
||||
|
||||
@@ -79,6 +79,8 @@ def markdown_to_html(md_text: str) -> str:
|
||||
|
||||
|
||||
class DeveloperWidget(DockAreaWidget):
|
||||
RPC = False
|
||||
PLUGIN = False
|
||||
|
||||
def __init__(self, parent=None, **kwargs):
|
||||
super().__init__(parent=parent, variant="compact", **kwargs)
|
||||
@@ -92,11 +94,11 @@ class DeveloperWidget(DockAreaWidget):
|
||||
self.explorer = IDEExplorer(self)
|
||||
self.explorer.setObjectName("Explorer")
|
||||
|
||||
self.console = BECShell(self)
|
||||
self.console = BECShell(self, rpc_exposed=False)
|
||||
self.console.setObjectName("BEC Shell")
|
||||
self.terminal = WebConsole(self)
|
||||
self.terminal = BecConsole(self, rpc_exposed=False)
|
||||
self.terminal.setObjectName("Terminal")
|
||||
self.monaco = MonacoDock(self)
|
||||
self.monaco = MonacoDock(self, rpc_exposed=False, rpc_passthrough_children=False)
|
||||
self.monaco.setObjectName("MonacoEditor")
|
||||
self.monaco.save_enabled.connect(self._on_save_enabled_update)
|
||||
self.plotting_ads = BECDockArea(
|
||||
@@ -408,23 +410,3 @@ class DeveloperWidget(DockAreaWidget):
|
||||
"""Clean up resources used by the developer widget."""
|
||||
self.delete_all()
|
||||
return super().cleanup()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
from bec_qthemes import apply_theme
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
from bec_widgets.applications.main_app import BECMainApp
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
apply_theme("dark")
|
||||
|
||||
_app = BECMainApp()
|
||||
_app.show()
|
||||
# developer_view.show()
|
||||
# developer_view.setWindowTitle("Developer View")
|
||||
# developer_view.resize(1920, 1080)
|
||||
# developer_view.set_stretch(horizontal=[1, 3, 2], vertical=[5, 5]) #can be set during runtime
|
||||
sys.exit(app.exec_())
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ logger = bec_logger.logger
|
||||
class DeviceManagerOphydValidationDialog(QtWidgets.QDialog):
|
||||
"""Popup dialog to test Ophyd device configurations interactively."""
|
||||
|
||||
def __init__(self, parent=None, config: dict | None = None): # type:ignore
|
||||
def __init__(self, parent=None, config: dict | None = None): # type: ignore
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Device Manager Ophyd Test")
|
||||
self._config_status = ConfigStatus.UNKNOWN.value
|
||||
@@ -133,7 +133,7 @@ class DeviceFormDialog(QtWidgets.QDialog):
|
||||
# validated: config_status, connection_status
|
||||
accepted_data = QtCore.Signal(dict, int, int, str, str)
|
||||
|
||||
def __init__(self, parent=None, add_btn_text: str = "Add Device"): # type:ignore
|
||||
def __init__(self, parent=None, add_btn_text: str = "Add Device"): # type: ignore
|
||||
super().__init__(parent)
|
||||
# Track old device name if config is edited
|
||||
self._old_device_name: str = ""
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from enum import IntEnum
|
||||
from functools import partial
|
||||
from typing import TYPE_CHECKING, List, Tuple
|
||||
from typing import TYPE_CHECKING, Any, List, Tuple
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_qthemes import apply_theme, material_icon
|
||||
|
||||
+7
-11
@@ -103,16 +103,14 @@ class CustomBusyWidget(QWidget):
|
||||
button_width = int(button_height * aspect_ratio)
|
||||
self.cancel_button.setFixedSize(button_width, button_height)
|
||||
color = get_accent_colors()
|
||||
self.cancel_button.setStyleSheet(
|
||||
f"""
|
||||
self.cancel_button.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background-color: {color.emergency.name()};
|
||||
color: white;
|
||||
font-weight: 600;
|
||||
border-radius: 6px;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
# Layout
|
||||
content_layout = QVBoxLayout(self)
|
||||
@@ -128,12 +126,10 @@ class CustomBusyWidget(QWidget):
|
||||
bg_color = color._colors.get("BG", None)
|
||||
if bg_color is None: # Fallback if missing
|
||||
bg_color = QColor(50, 50, 50, 255)
|
||||
self.setStyleSheet(
|
||||
f"""
|
||||
self.setStyleSheet(f"""
|
||||
background-color: {bg_color.name()};
|
||||
border-radius: 12px;
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
def _ui_scale(self) -> int:
|
||||
parent = self.parent()
|
||||
@@ -173,7 +169,7 @@ class DeviceManagerDisplayWidget(DockAreaWidget):
|
||||
self._upload_redis_dialog: UploadRedisDialog | None = None
|
||||
self._dialog_validation_connection: QMetaObject.Connection | None = None
|
||||
|
||||
# NOTE: We need here a seperate config helper instance to avoid conflicts with
|
||||
# NOTE: We need here a separate config helper instance to avoid conflicts with
|
||||
# other communications to REDIS as uploading a config through a CommunicationConfigAction
|
||||
# will block if we use the config_helper from self.client.config._config_helper
|
||||
self._config_helper = config_helper.ConfigHelper(self.client.connector)
|
||||
@@ -611,8 +607,8 @@ class DeviceManagerDisplayWidget(DockAreaWidget):
|
||||
self.device_table_view._is_config_in_sync_with_redis()
|
||||
)
|
||||
validation_results = self.device_table_view.get_validation_results()
|
||||
for config, config_status, connnection_status in validation_results.values():
|
||||
if connnection_status == ConnectionStatus.CONNECTED.value:
|
||||
for config, config_status, connection_status in validation_results.values():
|
||||
if connection_status == ConnectionStatus.CONNECTED.value:
|
||||
self.device_table_view.update_device_validation(
|
||||
config, config_status, ConnectionStatus.CAN_CONNECT, ""
|
||||
)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""Module for Device Manager View."""
|
||||
|
||||
from qtpy.QtCore import QRect
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.applications.views.device_manager_view.device_manager_widget import (
|
||||
DeviceManagerWidget,
|
||||
)
|
||||
from bec_widgets.applications.views.view import ViewBase
|
||||
from bec_widgets.applications.views.view import ViewBase, ViewTourSteps
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
|
||||
|
||||
@@ -19,11 +20,21 @@ class DeviceManagerView(ViewBase):
|
||||
parent: QWidget | None = None,
|
||||
content: QWidget | None = None,
|
||||
*,
|
||||
id: str | None = None,
|
||||
view_id: str | None = None,
|
||||
title: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, content=content, id=id, title=title)
|
||||
self.device_manager_widget = DeviceManagerWidget(parent=self)
|
||||
super().__init__(
|
||||
parent=parent,
|
||||
content=content,
|
||||
view_id=view_id,
|
||||
title=title,
|
||||
rpc_passthrough_children=False,
|
||||
**kwargs,
|
||||
)
|
||||
self.device_manager_widget = DeviceManagerWidget(
|
||||
parent=self, rpc_exposed=False, rpc_passthrough_children=False
|
||||
)
|
||||
self.set_content(self.device_manager_widget)
|
||||
|
||||
@SafeSlot()
|
||||
@@ -34,6 +45,110 @@ class DeviceManagerView(ViewBase):
|
||||
"""
|
||||
self.device_manager_widget.on_enter()
|
||||
|
||||
def register_tour_steps(self, guided_tour, main_app) -> ViewTourSteps | None:
|
||||
"""Register Device Manager components with the guided tour.
|
||||
|
||||
Args:
|
||||
guided_tour: The GuidedTour instance to register with.
|
||||
main_app: The main application instance (for accessing set_current).
|
||||
|
||||
Returns:
|
||||
ViewTourSteps | None: Model containing view title and step IDs.
|
||||
"""
|
||||
step_ids = []
|
||||
dm_widget = self.device_manager_widget
|
||||
|
||||
# The device_manager_widget is not yet initialized, so we will register
|
||||
# tour steps for its uninitialized state.
|
||||
|
||||
# Register Load Current Config button
|
||||
def get_load_current():
|
||||
main_app.set_current("device_manager")
|
||||
if dm_widget._initialized is True:
|
||||
return (None, None)
|
||||
return (dm_widget.button_load_current_config, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_load_current,
|
||||
title="Load Current Config",
|
||||
text="Load the current device configuration from the BEC server.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
# Register Load Config From File button
|
||||
def get_load_file():
|
||||
main_app.set_current("device_manager")
|
||||
if dm_widget._initialized is True:
|
||||
return (None, None)
|
||||
return (dm_widget.button_load_config_from_file, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_load_file,
|
||||
title="Load Config From File",
|
||||
text="Load a device configuration from a YAML file on disk.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
## Register steps for the initialized state
|
||||
# Register main device table
|
||||
def get_device_table():
|
||||
main_app.set_current("device_manager")
|
||||
if dm_widget._initialized is False:
|
||||
return (None, None)
|
||||
return (dm_widget.device_manager_display.device_table_view, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_device_table,
|
||||
title="Device Table",
|
||||
text="This table displays the config that is prepared to be uploaded to the BEC server. It allows users to review and modify device config settings, and also validate them before uploading to the BEC server.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
col_text_mapping = {
|
||||
0: "Shows if a device configuration is valid. Automatically validated when adding a new device.",
|
||||
1: "Shows if a device is connectable. Validated on demand.",
|
||||
2: "Device name, unique across all devices within a config.",
|
||||
3: "Device class used to initialize the device on the BEC server.",
|
||||
4: "Defines how BEC treats readings of the device during scans. The options are 'monitored', 'baseline', 'async', 'continuous' or 'on_demand'.",
|
||||
5: "Defines how BEC reacts if a device readback fails. Options are 'raise', 'retry', or 'buffer'.",
|
||||
6: "User-defined tags associated with the device.",
|
||||
7: "A brief description of the device.",
|
||||
8: "Device is enabled when the configuration is loaded.",
|
||||
9: "Device is set to read-only.",
|
||||
10: "This flag allows to configure if the 'trigger' method of the device is called during scans.",
|
||||
}
|
||||
|
||||
# We have at least one device registered
|
||||
def get_device_table_row(column: int):
|
||||
main_app.set_current("device_manager")
|
||||
if dm_widget._initialized is False:
|
||||
return (None, None)
|
||||
table = dm_widget.device_manager_display.device_table_view.table
|
||||
header = table.horizontalHeader()
|
||||
x = header.sectionViewportPosition(column)
|
||||
table.horizontalScrollBar().setValue(x)
|
||||
# Recompute after scrolling
|
||||
x = header.sectionViewportPosition(column)
|
||||
w = header.sectionSize(column)
|
||||
h = header.height()
|
||||
rect = QRect(x, 0, w, h)
|
||||
top_left = header.viewport().mapTo(main_app, rect.topLeft())
|
||||
|
||||
return (QRect(top_left, rect.size()), col_text_mapping.get(column, ""))
|
||||
|
||||
for col, text in col_text_mapping.items():
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=lambda col=col: get_device_table_row(col),
|
||||
title=f"{dm_widget.device_manager_display.device_table_view.table.horizontalHeaderItem(col).text()}",
|
||||
text=text,
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
if not step_ids:
|
||||
return None
|
||||
|
||||
return ViewTourSteps(view_title="Device Manager", step_ids=step_ids)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import sys
|
||||
@@ -65,7 +180,7 @@ if __name__ == "__main__": # pragma: no cover
|
||||
_app.add_view(
|
||||
icon="display_settings",
|
||||
title="Device Manager",
|
||||
id="device_manager",
|
||||
view_id="device_manager",
|
||||
widget=device_manager_view.device_manager_widget,
|
||||
mini_text="DM",
|
||||
)
|
||||
|
||||
@@ -22,8 +22,8 @@ class DeviceManagerWidget(BECWidget, QtWidgets.QWidget):
|
||||
|
||||
RPC = False
|
||||
|
||||
def __init__(self, parent=None, client=None):
|
||||
super().__init__(parent=parent, client=client)
|
||||
def __init__(self, parent=None, client=None, **kwargs):
|
||||
super().__init__(parent=parent, client=client, **kwargs)
|
||||
self.stacked_layout = QtWidgets.QStackedLayout()
|
||||
self.stacked_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.stacked_layout.setSpacing(0)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.applications.views.view import ViewBase
|
||||
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
|
||||
|
||||
|
||||
class DockAreaView(ViewBase):
|
||||
"""
|
||||
Modular dock area view for arranging and managing multiple dockable widgets.
|
||||
"""
|
||||
|
||||
RPC_CONTENT_CLASS = BECDockArea
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget | None = None,
|
||||
content: QWidget | None = None,
|
||||
*,
|
||||
view_id: str | None = None,
|
||||
title: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, content=content, view_id=view_id, title=title, **kwargs)
|
||||
self.dock_area = BECDockArea(
|
||||
self,
|
||||
profile_namespace="bec",
|
||||
auto_profile_namespace=False,
|
||||
object_name="DockArea",
|
||||
rpc_exposed=False,
|
||||
)
|
||||
self.set_content(self.dock_area)
|
||||
@@ -1,5 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from qtpy.QtCore import QEventLoop
|
||||
from qtpy.QtWidgets import (
|
||||
QDialog,
|
||||
@@ -14,14 +17,26 @@ from qtpy.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from bec_widgets import BECWidget
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.toolbars.status_bar import StatusToolBar
|
||||
from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import DeviceComboBox
|
||||
from bec_widgets.widgets.control.device_input.signal_combobox.signal_combobox import SignalComboBox
|
||||
from bec_widgets.widgets.plots.waveform.waveform import Waveform
|
||||
|
||||
|
||||
class ViewBase(QWidget):
|
||||
class ViewTourSteps(BaseModel):
|
||||
"""Model representing tour steps for a view.
|
||||
|
||||
Attributes:
|
||||
view_title: The human-readable title of the view.
|
||||
step_ids: List of registered step IDs in the order they should appear.
|
||||
"""
|
||||
|
||||
view_title: str
|
||||
step_ids: List[str]
|
||||
|
||||
|
||||
class ViewBase(BECWidget, QWidget):
|
||||
"""Wrapper for a content widget used inside the main app's stacked view.
|
||||
|
||||
Subclasses can implement `on_enter` and `on_exit` to run custom logic when the view becomes visible or is about to be hidden.
|
||||
@@ -29,72 +44,43 @@ class ViewBase(QWidget):
|
||||
Args:
|
||||
content (QWidget): The actual view widget to display.
|
||||
parent (QWidget | None): Parent widget.
|
||||
id (str | None): Optional view id, useful for debugging or introspection.
|
||||
view_id (str | None): Optional view view_id, useful for debugging or introspection.
|
||||
title (str | None): Optional human-readable title.
|
||||
show_status (bool): Whether to show a status toolbar at the top of the view.
|
||||
"""
|
||||
|
||||
RPC = True
|
||||
PLUGIN = False
|
||||
USER_ACCESS = ["activate"]
|
||||
RPC_CONTENT_CLASS: type[QWidget] | None = None
|
||||
RPC_CONTENT_ATTR = "content"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget | None = None,
|
||||
content: QWidget | None = None,
|
||||
*,
|
||||
id: str | None = None,
|
||||
view_id: str | None = None,
|
||||
title: str | None = None,
|
||||
show_status: bool = False,
|
||||
status_names: list[str] | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent)
|
||||
super().__init__(parent=parent, **kwargs)
|
||||
self.content: QWidget | None = None
|
||||
self.view_id = id
|
||||
self.view_id = view_id
|
||||
self.view_title = title
|
||||
|
||||
lay = QVBoxLayout(self)
|
||||
lay.setContentsMargins(0, 0, 0, 0)
|
||||
lay.setSpacing(0)
|
||||
|
||||
self.status_bar: StatusToolBar | None = None
|
||||
if show_status:
|
||||
# If explicit status names are provided, default to showing only those.
|
||||
show_all = status_names is None
|
||||
self.setup_status_bar(show_all_status=show_all, status_names=status_names)
|
||||
|
||||
if content is not None:
|
||||
self.set_content(content)
|
||||
|
||||
def set_content(self, content: QWidget) -> None:
|
||||
"""Replace the current content widget with a new one."""
|
||||
if self.content is not None:
|
||||
self.layout().removeWidget(self.content)
|
||||
self.content.setParent(None)
|
||||
self.content.close()
|
||||
self.content.deleteLater()
|
||||
self.content = content
|
||||
if self.status_bar is not None:
|
||||
insert_at = self.layout().indexOf(self.status_bar) + 1
|
||||
self.layout().insertWidget(insert_at, content)
|
||||
else:
|
||||
self.layout().addWidget(content)
|
||||
|
||||
def setup_status_bar(
|
||||
self, *, show_all_status: bool = True, status_names: list[str] | None = None
|
||||
) -> None:
|
||||
"""Create and attach a status toolbar managed by the status broker."""
|
||||
if self.status_bar is not None:
|
||||
return
|
||||
names_arg = None if show_all_status else status_names
|
||||
self.status_bar = StatusToolBar(parent=self, names=names_arg)
|
||||
self.layout().addWidget(self.status_bar)
|
||||
|
||||
def set_status(
|
||||
self, name: str = "main", *, state=None, text: str | None = None, tooltip: str | None = None
|
||||
) -> None:
|
||||
"""Manually set a status item on the status bar."""
|
||||
if self.status_bar is None:
|
||||
self.setup_status_bar(show_all_status=True)
|
||||
if self.status_bar is None:
|
||||
return
|
||||
self.status_bar.set_status(name=name, state=state, text=text, tooltip=tooltip)
|
||||
self.layout().addWidget(content)
|
||||
|
||||
@SafeSlot()
|
||||
def on_enter(self) -> None:
|
||||
@@ -113,6 +99,41 @@ class ViewBase(QWidget):
|
||||
"""
|
||||
return True
|
||||
|
||||
@SafeSlot()
|
||||
def activate(self) -> None:
|
||||
"""Switch the parent application to this view."""
|
||||
if not self.view_id:
|
||||
raise ValueError("Cannot switch view without a view_id.")
|
||||
|
||||
parent = self.parent()
|
||||
while parent is not None:
|
||||
if hasattr(parent, "set_current"):
|
||||
parent.set_current(self.view_id)
|
||||
return
|
||||
parent = parent.parent()
|
||||
raise RuntimeError("Could not find a parent application with set_current().")
|
||||
|
||||
def cleanup(self):
|
||||
if self.content is not None:
|
||||
self.content.close()
|
||||
self.content.deleteLater()
|
||||
super().cleanup()
|
||||
|
||||
def register_tour_steps(self, guided_tour, main_app) -> ViewTourSteps | None:
|
||||
"""Register this view's components with the guided tour.
|
||||
|
||||
Args:
|
||||
guided_tour: The GuidedTour instance to register with.
|
||||
main_app: The main application instance (for accessing set_current).
|
||||
|
||||
Returns:
|
||||
ViewTourSteps | None: A model containing the view title and step IDs,
|
||||
or None if this view has no tour steps.
|
||||
|
||||
Override this method in subclasses to register view-specific components.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
####################################################################################################
|
||||
# Example views for demonstration/testing purposes
|
||||
@@ -139,17 +160,17 @@ class WaveformViewPopup(ViewBase): # pragma: no cover
|
||||
self.device_edit.insertItem(0, "")
|
||||
self.device_edit.setEditable(True)
|
||||
self.device_edit.setCurrentIndex(0)
|
||||
self.entry_edit = SignalComboBox(parent=self)
|
||||
self.entry_edit.include_config_signals = False
|
||||
self.entry_edit.insertItem(0, "")
|
||||
self.entry_edit.setEditable(True)
|
||||
self.device_edit.currentTextChanged.connect(self.entry_edit.set_device)
|
||||
self.device_edit.device_reset.connect(self.entry_edit.reset_selection)
|
||||
self.signal_edit = SignalComboBox(parent=self)
|
||||
self.signal_edit.include_config_signals = False
|
||||
self.signal_edit.insertItem(0, "")
|
||||
self.signal_edit.setEditable(True)
|
||||
self.device_edit.currentTextChanged.connect(self.signal_edit.set_device)
|
||||
self.device_edit.device_reset.connect(self.signal_edit.reset_selection)
|
||||
|
||||
form = QFormLayout()
|
||||
form.addRow(label)
|
||||
form.addRow("Device", self.device_edit)
|
||||
form.addRow("Signal", self.entry_edit)
|
||||
form.addRow("Signal", self.signal_edit)
|
||||
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, parent=dialog)
|
||||
buttons.accepted.connect(dialog.accept)
|
||||
@@ -161,7 +182,7 @@ class WaveformViewPopup(ViewBase): # pragma: no cover
|
||||
|
||||
if dialog.exec_() == QDialog.Accepted:
|
||||
self.waveform.plot(
|
||||
y_name=self.device_edit.currentText(), y_entry=self.entry_edit.currentText()
|
||||
device_y=self.device_edit.currentText(), signal_y=self.signal_edit.currentText()
|
||||
)
|
||||
|
||||
@SafeSlot()
|
||||
@@ -286,7 +307,7 @@ class WaveformViewInline(ViewBase): # pragma: no cover
|
||||
dev = self.device_edit.currentText()
|
||||
sig = self.entry_edit.currentText()
|
||||
if dev and sig:
|
||||
self.waveform.plot(y_name=dev, y_entry=sig)
|
||||
self.waveform.plot(device_y=dev, signal_y=sig)
|
||||
self.stack.setCurrentIndex(1)
|
||||
|
||||
def _show_waveform_without_changes(self):
|
||||
|
||||
+586
-169
File diff suppressed because it is too large
Load Diff
@@ -10,9 +10,9 @@ import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
|
||||
from typing import TYPE_CHECKING, Callable, Literal, TypeAlias, cast
|
||||
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from bec_lib.endpoints import EndpointInfo, MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.utils.import_utils import lazy_import, lazy_import_from
|
||||
from rich.console import Console
|
||||
@@ -232,6 +232,11 @@ class BECGuiClient(RPCBase):
|
||||
"""The launcher object."""
|
||||
return RPCBase(gui_id=f"{self._gui_id}:launcher", parent=self, object_name="launcher")
|
||||
|
||||
def _safe_register_stream(self, endpoint: EndpointInfo, cb: Callable, **kwargs):
|
||||
"""Check if already registered for registration in idempotent functions."""
|
||||
if not self._client.connector.any_stream_is_registered(endpoint, cb=cb):
|
||||
self._client.connector.register(endpoint, cb=cb, **kwargs)
|
||||
|
||||
def connect_to_gui_server(self, gui_id: str) -> None:
|
||||
"""Connect to a GUI server"""
|
||||
# Unregister the old callback
|
||||
@@ -247,10 +252,9 @@ class BECGuiClient(RPCBase):
|
||||
self._ipython_registry = {}
|
||||
|
||||
# Register the new callback
|
||||
self._client.connector.register(
|
||||
self._safe_register_stream(
|
||||
MessageEndpoints.gui_registry_state(self._gui_id),
|
||||
cb=self._handle_registry_update,
|
||||
parent=self,
|
||||
from_start=True,
|
||||
)
|
||||
|
||||
@@ -297,14 +301,32 @@ class BECGuiClient(RPCBase):
|
||||
return self._raise_all()
|
||||
return self._start(wait=wait)
|
||||
|
||||
def change_theme(self, theme: Literal["light", "dark"] | None = None) -> None:
|
||||
"""
|
||||
Apply a GUI theme or toggle between dark and light.
|
||||
|
||||
Args:
|
||||
theme(Literal["light", "dark"] | None): Theme to apply. If None, the current
|
||||
theme is fetched from the GUI and toggled.
|
||||
"""
|
||||
if not self._check_if_server_is_alive():
|
||||
self._start(wait=True)
|
||||
|
||||
with wait_for_server(self):
|
||||
if theme is None:
|
||||
current_theme = self.launcher._run_rpc("fetch_theme")
|
||||
next_theme = "light" if current_theme == "dark" else "dark"
|
||||
else:
|
||||
next_theme = theme
|
||||
self.launcher._run_rpc("change_theme", theme=next_theme)
|
||||
|
||||
def new(
|
||||
self,
|
||||
name: str | None = None,
|
||||
wait: bool = True,
|
||||
geometry: tuple[int, int, int, int] | None = None,
|
||||
launch_script: str = "dock_area",
|
||||
profile: str | None = None,
|
||||
start_empty: bool = False,
|
||||
startup_profile: str | Literal["restore", "skip"] | None = None,
|
||||
**kwargs,
|
||||
) -> client.AdvancedDockArea:
|
||||
"""Create a new top-level dock area.
|
||||
@@ -314,48 +336,81 @@ class BECGuiClient(RPCBase):
|
||||
wait(bool, optional): Whether to wait for the server to start. Defaults to True.
|
||||
geometry(tuple[int, int, int, int] | None): The geometry of the dock area (pos_x, pos_y, w, h).
|
||||
launch_script(str): The launch script to use. Defaults to "dock_area".
|
||||
profile(str | None): The profile name to load. If None, loads the "general" profile.
|
||||
Use a profile name to load a specific saved profile.
|
||||
start_empty(bool): If True, start with an empty dock area when loading specified profile.
|
||||
startup_profile(str | Literal["restore", "skip"] | None): Startup mode for
|
||||
the dock area:
|
||||
- None: start in transient empty workspace
|
||||
- "restore": restore last-used profile
|
||||
- "skip": skip profile initialization
|
||||
- "<name>": load the named profile
|
||||
**kwargs: Additional keyword arguments passed to the dock area.
|
||||
|
||||
Returns:
|
||||
client.AdvancedDockArea: The new dock area.
|
||||
|
||||
Note:
|
||||
The "general" profile is mandatory and will always exist. If manually deleted,
|
||||
it will be automatically recreated.
|
||||
|
||||
Examples:
|
||||
>>> gui.new() # Start with the "general" profile
|
||||
>>> gui.new(profile="my_profile") # Load specific profile, if profile does not exist, the new profile is created empty with specified name
|
||||
>>> gui.new(start_empty=True) # Start with "general" profile but empty dock area
|
||||
>>> gui.new(profile="my_profile", start_empty=True) # Start with "my_profile" profile but empty dock area
|
||||
>>> gui.new() # Start with an empty unsaved workspace
|
||||
>>> gui.new(startup_profile="restore") # Restore last profile
|
||||
>>> gui.new(startup_profile="my_profile") # Load explicit profile
|
||||
"""
|
||||
if "profile" in kwargs or "start_empty" in kwargs:
|
||||
raise TypeError(
|
||||
"gui.new() no longer accepts 'profile' or 'start_empty'. Use 'startup_profile' instead."
|
||||
)
|
||||
|
||||
if not self._check_if_server_is_alive():
|
||||
self.start(wait=True)
|
||||
if wait:
|
||||
with wait_for_server(self):
|
||||
widget = self.launcher._run_rpc(
|
||||
"launch",
|
||||
launch_script=launch_script,
|
||||
return self._new_impl(
|
||||
name=name,
|
||||
geometry=geometry,
|
||||
profile=profile,
|
||||
start_empty=start_empty,
|
||||
launch_script=launch_script,
|
||||
startup_profile=startup_profile,
|
||||
**kwargs,
|
||||
) # pylint: disable=protected-access
|
||||
return widget
|
||||
widget = self.launcher._run_rpc(
|
||||
)
|
||||
return self._new_impl(
|
||||
name=name,
|
||||
geometry=geometry,
|
||||
launch_script=launch_script,
|
||||
startup_profile=startup_profile,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _new_impl(
|
||||
self,
|
||||
*,
|
||||
name: str | None,
|
||||
geometry: tuple[int, int, int, int] | None,
|
||||
launch_script: str,
|
||||
startup_profile: str | Literal["restore", "skip"] | None,
|
||||
**kwargs,
|
||||
):
|
||||
if launch_script == "dock_area":
|
||||
try:
|
||||
return self.launcher._run_rpc(
|
||||
"system.launch_dock_area",
|
||||
name=name,
|
||||
geometry=geometry,
|
||||
startup_profile=startup_profile,
|
||||
**kwargs,
|
||||
)
|
||||
except ValueError as exc:
|
||||
error = str(exc)
|
||||
if (
|
||||
"Unknown system RPC method: system.launch_dock_area" not in error
|
||||
and "has no attribute 'system.launch_dock_area'" not in error
|
||||
):
|
||||
raise
|
||||
logger.debug("Server does not support system.launch_dock_area; using launcher RPC")
|
||||
|
||||
return self.launcher._run_rpc(
|
||||
"launch",
|
||||
launch_script=launch_script,
|
||||
name=name,
|
||||
geometry=geometry,
|
||||
profile=profile,
|
||||
start_empty=start_empty,
|
||||
startup_profile=startup_profile,
|
||||
**kwargs,
|
||||
) # pylint: disable=protected-access
|
||||
return widget
|
||||
|
||||
def delete(self, name: str) -> None:
|
||||
"""Delete a dock area and its parent window.
|
||||
@@ -480,20 +535,14 @@ class BECGuiClient(RPCBase):
|
||||
|
||||
def _start(self, wait: bool = False) -> None:
|
||||
self._killed = False
|
||||
self._client.connector.register(
|
||||
MessageEndpoints.gui_registry_state(self._gui_id),
|
||||
cb=self._handle_registry_update,
|
||||
parent=self,
|
||||
self._safe_register_stream(
|
||||
MessageEndpoints.gui_registry_state(self._gui_id), cb=self._handle_registry_update
|
||||
)
|
||||
return self._start_server(wait=wait)
|
||||
|
||||
@staticmethod
|
||||
def _handle_registry_update(
|
||||
msg: dict[str, GUIRegistryStateMessage], parent: BECGuiClient
|
||||
) -> None:
|
||||
def _handle_registry_update(self, msg: dict[str, GUIRegistryStateMessage]) -> None:
|
||||
# This was causing a deadlock during shutdown, not sure why.
|
||||
# with self._lock:
|
||||
self = parent
|
||||
self._server_registry = cast(dict[str, RegistryState], msg["data"].state)
|
||||
self._update_dynamic_namespace(self._server_registry)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import inspect
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import get_overloads
|
||||
|
||||
import black
|
||||
import isort
|
||||
@@ -18,20 +19,6 @@ from bec_widgets.utils.plugin_utils import BECClassContainer, get_custom_classes
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import get_overloads
|
||||
else:
|
||||
print(
|
||||
"Python version is less than 3.11, using dummy function for get_overloads. "
|
||||
"If you want to use the real function 'typing.get_overloads()', please use Python 3.11 or later."
|
||||
)
|
||||
|
||||
def get_overloads(_obj):
|
||||
"""
|
||||
Dummy function for Python versions before 3.11.
|
||||
"""
|
||||
return []
|
||||
|
||||
|
||||
class ClientGenerator:
|
||||
def __init__(self, base=False):
|
||||
@@ -54,7 +41,7 @@ from __future__ import annotations
|
||||
from bec_lib.logger import bec_logger
|
||||
|
||||
from bec_widgets.cli.rpc.rpc_base import RPCBase, rpc_call, rpc_timeout
|
||||
{"from bec_widgets.utils.bec_plugin_helper import get_all_plugin_widgets, get_plugin_client_module" if self._base else ""}
|
||||
{"from bec_widgets.utils.bec_plugin_helper import get_plugin_client_module" if self._base else ""}
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
@@ -94,7 +81,7 @@ logger = bec_logger.logger
|
||||
if self._base:
|
||||
self.content += """
|
||||
class _WidgetsEnumType(str, enum.Enum):
|
||||
\"\"\" Enum for the available widgets, to be generated programatically \"\"\"
|
||||
\"\"\" Enum for the available widgets, to be generated programmatically \"\"\"
|
||||
...
|
||||
"""
|
||||
|
||||
@@ -111,27 +98,19 @@ _Widgets = {
|
||||
self.content += """
|
||||
|
||||
try:
|
||||
_plugin_widgets = get_all_plugin_widgets().as_dict()
|
||||
plugin_client = get_plugin_client_module()
|
||||
Widgets = _WidgetsEnumType("Widgets", {name: name for name in _plugin_widgets} | _Widgets)
|
||||
|
||||
if (_overlap := _Widgets.keys() & _plugin_widgets.keys()) != set():
|
||||
for _widget in _overlap:
|
||||
logger.warning(f"Detected duplicate widget {_widget} in plugin repo file: {inspect.getfile(_plugin_widgets[_widget])} !")
|
||||
for plugin_name, plugin_class in inspect.getmembers(plugin_client, inspect.isclass):
|
||||
if issubclass(plugin_class, RPCBase) and plugin_class is not RPCBase:
|
||||
if plugin_name not in _Widgets:
|
||||
_Widgets[plugin_name] = plugin_name
|
||||
if plugin_name in globals():
|
||||
conflicting_file = (
|
||||
inspect.getfile(_plugin_widgets[plugin_name])
|
||||
if plugin_name in _plugin_widgets
|
||||
else f"{plugin_client}"
|
||||
)
|
||||
logger.warning(
|
||||
f"Plugin widget {plugin_name} from {conflicting_file} conflicts with a built-in class!"
|
||||
f"Plugin widget {plugin_name} in {plugin_class._IMPORT_MODULE} conflicts with a built-in class!"
|
||||
)
|
||||
continue
|
||||
if plugin_name not in _overlap:
|
||||
else:
|
||||
globals()[plugin_name] = plugin_class
|
||||
Widgets = _WidgetsEnumType("Widgets", _Widgets)
|
||||
except ImportError as e:
|
||||
logger.error(f"Failed loading plugins: \\n{reduce(add, traceback.format_exception(e))}")
|
||||
"""
|
||||
@@ -146,12 +125,8 @@ except ImportError as e:
|
||||
|
||||
class_name = cls.__name__
|
||||
|
||||
if class_name == "BECDockArea":
|
||||
self.content += f"""
|
||||
class {class_name}(RPCBase):"""
|
||||
else:
|
||||
self.content += f"""
|
||||
class {class_name}(RPCBase):"""
|
||||
self.content += f"""
|
||||
class {class_name}(RPCBase):\n"""
|
||||
|
||||
if cls.__doc__:
|
||||
# We only want the first line of the docstring
|
||||
@@ -162,19 +137,11 @@ class {class_name}(RPCBase):"""
|
||||
else:
|
||||
class_docs = cls.__doc__.split("\n")[1]
|
||||
self.content += f"""
|
||||
\"\"\"{class_docs}\"\"\"
|
||||
"""
|
||||
if not cls.USER_ACCESS:
|
||||
self.content += """...
|
||||
"""
|
||||
|
||||
for method in cls.USER_ACCESS:
|
||||
is_property_setter = False
|
||||
obj = getattr(cls, method, None)
|
||||
if obj is None:
|
||||
obj = getattr(cls, method.split(".setter")[0], None)
|
||||
is_property_setter = True
|
||||
method = method.split(".setter")[0]
|
||||
\"\"\"{class_docs}\"\"\"\n"""
|
||||
user_access_entries = self._get_user_access_entries(cls)
|
||||
self.content += f' _IMPORT_MODULE="{cls.__module__}"\n'
|
||||
for method_entry in user_access_entries:
|
||||
method, obj, is_property_setter = self._resolve_method_object(cls, method_entry)
|
||||
if obj is None:
|
||||
raise AttributeError(
|
||||
f"Method {method} not found in class {cls.__name__}. "
|
||||
@@ -216,6 +183,34 @@ class {class_name}(RPCBase):"""
|
||||
{doc}
|
||||
\"\"\""""
|
||||
|
||||
@staticmethod
|
||||
def _get_user_access_entries(cls) -> list[str]:
|
||||
entries = list(getattr(cls, "USER_ACCESS", []))
|
||||
content_cls = getattr(cls, "RPC_CONTENT_CLASS", None)
|
||||
if content_cls is not None:
|
||||
entries.extend(getattr(content_cls, "USER_ACCESS", []))
|
||||
return list(dict.fromkeys(entries))
|
||||
|
||||
@staticmethod
|
||||
def _resolve_method_object(cls, method_entry: str):
|
||||
method_name = method_entry
|
||||
is_property_setter = False
|
||||
|
||||
if method_entry.endswith(".setter"):
|
||||
is_property_setter = True
|
||||
method_name = method_entry.split(".setter")[0]
|
||||
|
||||
candidate_classes = [cls]
|
||||
content_cls = getattr(cls, "RPC_CONTENT_CLASS", None)
|
||||
if content_cls is not None:
|
||||
candidate_classes.append(content_cls)
|
||||
|
||||
for candidate_cls in candidate_classes:
|
||||
obj = getattr(candidate_cls, method_name, None)
|
||||
if obj is not None:
|
||||
return method_name, obj, is_property_setter
|
||||
return method_name, None, is_property_setter
|
||||
|
||||
def _rpc_call(self, timeout_info: dict[str, float | None]):
|
||||
"""
|
||||
Decorator to mark a method as an RPC call.
|
||||
@@ -291,7 +286,8 @@ def main():
|
||||
|
||||
client_path = module_dir / client_subdir / "client.py"
|
||||
|
||||
rpc_classes = get_custom_classes(module_name)
|
||||
packages = ("widgets", "applications") if module_name == "bec_widgets" else ("widgets",)
|
||||
rpc_classes = get_custom_classes(module_name, packages=packages)
|
||||
logger.info(f"Obtained classes with RPC objects: {rpc_classes!r}")
|
||||
|
||||
generator = ClientGenerator(base=module_name == "bec_widgets")
|
||||
|
||||
@@ -248,9 +248,7 @@ class RPCBase:
|
||||
self._rpc_response = None
|
||||
self._msg_wait_event.clear()
|
||||
self._client.connector.register(
|
||||
MessageEndpoints.gui_instruction_response(request_id),
|
||||
cb=self._on_rpc_response,
|
||||
parent=self,
|
||||
MessageEndpoints.gui_instruction_response(request_id), cb=self._on_rpc_response
|
||||
)
|
||||
|
||||
self._client.connector.set_and_publish(MessageEndpoints.gui_instructions(receiver), rpc_msg)
|
||||
@@ -276,11 +274,10 @@ class RPCBase:
|
||||
self._rpc_response = None
|
||||
return self._create_widget_from_msg_result(msg_result)
|
||||
|
||||
@staticmethod
|
||||
def _on_rpc_response(msg_obj: MessageObject, parent: RPCBase) -> None:
|
||||
def _on_rpc_response(self, msg_obj: MessageObject) -> None:
|
||||
msg = cast(messages.RequestResponseMessage, msg_obj.value)
|
||||
parent._rpc_response = msg
|
||||
parent._msg_wait_event.set()
|
||||
self._rpc_response = msg
|
||||
self._msg_wait_event.set()
|
||||
|
||||
def _create_widget_from_msg_result(self, msg_result):
|
||||
if msg_result is None:
|
||||
@@ -292,6 +289,11 @@ class RPCBase:
|
||||
return {
|
||||
key: self._create_widget_from_msg_result(val) for key, val in msg_result.items()
|
||||
}
|
||||
rpc_enabled = msg_result.get("__rpc__", True)
|
||||
if rpc_enabled is False:
|
||||
return None
|
||||
|
||||
msg_result = dict(msg_result)
|
||||
cls = msg_result.pop("widget_class", None)
|
||||
msg_result.pop("__rpc__", None)
|
||||
|
||||
|
||||
@@ -32,7 +32,8 @@ class RPCWidgetHandler:
|
||||
None
|
||||
"""
|
||||
self._widget_classes = (
|
||||
get_custom_classes("bec_widgets") + get_all_plugin_widgets()
|
||||
get_custom_classes("bec_widgets", packages=("widgets", "applications"))
|
||||
+ get_all_plugin_widgets()
|
||||
).as_dict(IGNORE_WIDGETS)
|
||||
|
||||
def create_widget(self, widget_type, **kwargs) -> BECWidget:
|
||||
|
||||
@@ -8,6 +8,7 @@ import sys
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
|
||||
import darkdetect
|
||||
import shiboken6
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.service_config import ServiceConfig
|
||||
from bec_qthemes import apply_theme
|
||||
@@ -93,6 +94,7 @@ class GUIServer:
|
||||
"""
|
||||
Run the GUI server.
|
||||
"""
|
||||
logger.info("Starting GUIServer", repr(self))
|
||||
self.app = QApplication(sys.argv)
|
||||
if darkdetect.isDark():
|
||||
apply_theme("dark")
|
||||
@@ -101,11 +103,11 @@ class GUIServer:
|
||||
|
||||
self.app.setApplicationName("BEC")
|
||||
self.app.gui_id = self.gui_id # type: ignore
|
||||
self.app.gui_server = self # type: ignore # make server accessible from QApplication for getattr in widgets
|
||||
self.setup_bec_icon()
|
||||
|
||||
service_config = self._get_service_config()
|
||||
self.dispatcher = BECDispatcher(config=service_config, gui_id=self.gui_id)
|
||||
# self.dispatcher.start_cli_server(gui_id=self.gui_id)
|
||||
|
||||
if self.gui_class:
|
||||
self.launcher_window = LaunchWindow(
|
||||
@@ -118,7 +120,7 @@ class GUIServer:
|
||||
self.launcher_window.setAttribute(Qt.WA_ShowWithoutActivating) # type: ignore
|
||||
|
||||
self.app.aboutToQuit.connect(self.shutdown)
|
||||
self.app.setQuitOnLastWindowClosed(False)
|
||||
self.app.setQuitOnLastWindowClosed(True)
|
||||
|
||||
def sigint_handler(*args):
|
||||
# display message, for people to let it terminate gracefully
|
||||
@@ -127,8 +129,7 @@ class GUIServer:
|
||||
with RPCRegister.delayed_broadcast():
|
||||
for widget in QApplication.instance().topLevelWidgets(): # type: ignore
|
||||
widget.close()
|
||||
if self.app:
|
||||
self.app.quit()
|
||||
self.shutdown()
|
||||
|
||||
signal.signal(signal.SIGINT, sigint_handler)
|
||||
signal.signal(signal.SIGTERM, sigint_handler)
|
||||
@@ -149,9 +150,10 @@ class GUIServer:
|
||||
self.app.setWindowIcon(icon)
|
||||
|
||||
def shutdown(self):
|
||||
"""
|
||||
Shutdown the GUI server.
|
||||
"""
|
||||
logger.info("Shutdown GUIServer", repr(self))
|
||||
if self.launcher_window and shiboken6.isValid(self.launcher_window):
|
||||
self.launcher_window.close()
|
||||
self.launcher_window.deleteLater()
|
||||
if pylsp_server.is_running():
|
||||
pylsp_server.stop()
|
||||
if self.dispatcher:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# pylint: skip-file
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from bec_lib.config_helper import ConfigHelper
|
||||
from bec_lib.device import Device as BECDevice
|
||||
from bec_lib.device import Positioner as BECPositioner
|
||||
from bec_lib.device import ReadoutPriority
|
||||
@@ -219,7 +220,9 @@ class Device(FakeDevice):
|
||||
|
||||
|
||||
class DMMock:
|
||||
def __init__(self):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._service = args[0]
|
||||
self.config_helper = ConfigHelper(self._service.connector, self._service._service_name)
|
||||
self.devices = DeviceContainer()
|
||||
self.enabled_devices = [device for device in self.devices if device.enabled]
|
||||
|
||||
@@ -273,6 +276,10 @@ class DMMock:
|
||||
configs.append(device._config)
|
||||
return configs
|
||||
|
||||
def initialize(*_): ...
|
||||
|
||||
def shutdown(self): ...
|
||||
|
||||
|
||||
DEVICES = [
|
||||
FakePositioner("samx", limits=[-10, 10], read_value=2.0),
|
||||
|
||||
@@ -12,7 +12,7 @@ import shiboken6 as shb
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.utils.import_utils import lazy_import_from
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from qtpy.QtCore import Property, QObject, QRunnable, QThreadPool, QTimer, Signal
|
||||
from qtpy.QtCore import Property, QObject, QRunnable, QThreadPool, Signal
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
from bec_widgets.cli.rpc.rpc_register import RPCRegister
|
||||
@@ -23,7 +23,6 @@ from bec_widgets.utils.yaml_dialog import load_yaml, load_yaml_gui, save_yaml, s
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
from bec_widgets.widgets.containers.dock import BECDock
|
||||
else:
|
||||
BECDispatcher = lazy_import_from("bec_widgets.utils.bec_dispatcher", ("BECDispatcher",))
|
||||
|
||||
@@ -89,6 +88,8 @@ class BECConnector:
|
||||
gui_id: str | None = None,
|
||||
object_name: str | None = None,
|
||||
root_widget: bool = False,
|
||||
rpc_exposed: bool = True,
|
||||
rpc_passthrough_children: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
@@ -100,6 +101,10 @@ class BECConnector:
|
||||
gui_id(str, optional): The GUI ID.
|
||||
object_name(str, optional): The object name.
|
||||
root_widget(bool, optional): If set to True, the parent_id will be always set to None, thus enforcing that the widget is accessible as a root widget of the BECGuiClient object.
|
||||
rpc_exposed(bool, optional): If set to False, this instance is excluded from RPC registry broadcast and CLI namespace discovery.
|
||||
rpc_passthrough_children(bool, optional): Only relevant when ``rpc_exposed=False``.
|
||||
If True, RPC-visible children rebind to the next visible ancestor.
|
||||
If False (default), children stay hidden behind this widget.
|
||||
**kwargs:
|
||||
"""
|
||||
# Extract object_name from kwargs to not pass it to Qt class
|
||||
@@ -128,8 +133,13 @@ class BECConnector:
|
||||
# the function depends on BECClient, and BECDispatcher
|
||||
@SafeSlot()
|
||||
def terminate(client=self.client, dispatcher=self.bec_dispatcher):
|
||||
app = QApplication.instance()
|
||||
gui_server = getattr(app, "gui_server", None)
|
||||
if gui_server and hasattr(gui_server, "shutdown"):
|
||||
gui_server.shutdown()
|
||||
logger.info("Disconnecting", repr(dispatcher))
|
||||
dispatcher.disconnect_all()
|
||||
dispatcher.stop_cli_server()
|
||||
|
||||
try: # shutdown ophyd threads if any
|
||||
from ophyd._pyepics_shim import _dispatcher
|
||||
@@ -157,7 +167,7 @@ class BECConnector:
|
||||
)
|
||||
self.config = ConnectionConfig(widget_class=self.__class__.__name__)
|
||||
|
||||
# If the gui_id is passed, it should be respected. However, this should be revisted since
|
||||
# If the gui_id is passed, it should be respected. However, this should be revisited since
|
||||
# the gui_id has to be unique, and may no longer be.
|
||||
if gui_id:
|
||||
self.config.gui_id = gui_id
|
||||
@@ -185,6 +195,11 @@ class BECConnector:
|
||||
|
||||
# If set to True, the parent_id will be always set to None, thus enforcing that the widget is accessible as a root widget of the BECGuiClient object.
|
||||
self.root_widget = root_widget
|
||||
# If set to False, this instance is not exposed through RPC at all.
|
||||
self.rpc_exposed = bool(rpc_exposed)
|
||||
# If True on a hidden parent (rpc_exposed=False), children can bubble up to
|
||||
# the next visible RPC ancestor.
|
||||
self.rpc_passthrough_children = bool(rpc_passthrough_children)
|
||||
|
||||
self._update_object_name()
|
||||
|
||||
@@ -193,11 +208,41 @@ class BECConnector:
|
||||
try:
|
||||
if self.root_widget:
|
||||
return None
|
||||
connector_parent = WidgetHierarchy._get_becwidget_ancestor(self)
|
||||
connector_parent = self._get_rpc_parent_ancestor()
|
||||
return connector_parent.gui_id if connector_parent else None
|
||||
except:
|
||||
logger.error(f"Error getting parent_id for {self.__class__.__name__}")
|
||||
|
||||
def _get_rpc_parent_ancestor(self) -> BECConnector | None:
|
||||
"""
|
||||
Find the nearest ancestor that is RPC-addressable.
|
||||
|
||||
Rules:
|
||||
- If an ancestor has ``rpc_exposed=False``, it is an explicit visibility
|
||||
boundary unless ``rpc_passthrough_children=True``.
|
||||
- If an ancestor has ``RPC=False`` (but remains rpc_exposed), it is treated
|
||||
as structural and children continue to the next ancestor.
|
||||
- Lookup always happens through ``WidgetHierarchy.get_becwidget_ancestor``
|
||||
so plain ``QWidget`` nodes between connectors are ignored.
|
||||
"""
|
||||
current = self
|
||||
while True:
|
||||
parent = WidgetHierarchy.get_becwidget_ancestor(current)
|
||||
if parent is None:
|
||||
return None
|
||||
|
||||
if not getattr(parent, "rpc_exposed", True):
|
||||
if getattr(parent, "rpc_passthrough_children", False):
|
||||
current = parent
|
||||
continue
|
||||
return parent
|
||||
|
||||
if getattr(parent, "RPC", True):
|
||||
return parent
|
||||
|
||||
current = parent
|
||||
return None
|
||||
|
||||
def change_object_name(self, name: str) -> None:
|
||||
"""
|
||||
Change the object name of the widget. Unregister old name and register the new one.
|
||||
@@ -216,8 +261,9 @@ class BECConnector:
|
||||
"""
|
||||
# 1) Enforce unique objectName among siblings with the same BECConnector parent
|
||||
self._enforce_unique_sibling_name()
|
||||
# 2) Register the object for RPC
|
||||
self.rpc_register.add_rpc(self)
|
||||
# 2) Register the object for RPC unless instance-level exposure is disabled.
|
||||
if getattr(self, "rpc_exposed", True):
|
||||
self.rpc_register.add_rpc(self)
|
||||
try:
|
||||
self.name_established.emit(self.object_name)
|
||||
except RuntimeError as e:
|
||||
@@ -235,7 +281,7 @@ class BECConnector:
|
||||
if not shb.isValid(self):
|
||||
return
|
||||
|
||||
parent_bec = WidgetHierarchy._get_becwidget_ancestor(self)
|
||||
parent_bec = WidgetHierarchy.get_becwidget_ancestor(self)
|
||||
|
||||
if parent_bec:
|
||||
# We have a parent => only compare with siblings under that parent
|
||||
@@ -245,7 +291,7 @@ class BECConnector:
|
||||
# Use RPCRegister to avoid QApplication.allWidgets() during event processing.
|
||||
connections = self.rpc_register.list_all_connections().values()
|
||||
all_bec = [w for w in connections if isinstance(w, BECConnector) and shb.isValid(w)]
|
||||
siblings = [w for w in all_bec if WidgetHierarchy._get_becwidget_ancestor(w) is None]
|
||||
siblings = [w for w in all_bec if WidgetHierarchy.get_becwidget_ancestor(w) is None]
|
||||
|
||||
# Collect used names among siblings
|
||||
used_names = {sib.objectName() for sib in siblings if sib is not self}
|
||||
@@ -273,6 +319,8 @@ class BECConnector:
|
||||
Args:
|
||||
name (str): The new object name.
|
||||
"""
|
||||
# sanitize before setting to avoid issues with Qt object names and RPC namespaces
|
||||
name = sanitize_namespace(name)
|
||||
super().setObjectName(name)
|
||||
self.object_name = name
|
||||
if self.rpc_register.object_is_registered(self):
|
||||
@@ -351,7 +399,7 @@ class BECConnector:
|
||||
"""
|
||||
self.config = config
|
||||
|
||||
# FIXME some thoughts are required to decide how thhis should work with rpc registry
|
||||
# FIXME some thoughts are required to decide how this should work with rpc registry
|
||||
def apply_config(self, config: dict, generate_new_id: bool = True) -> None:
|
||||
"""
|
||||
Apply the configuration to the widget.
|
||||
@@ -369,7 +417,7 @@ class BECConnector:
|
||||
else:
|
||||
self.gui_id = self.config.gui_id
|
||||
|
||||
# FIXME some thoughts are required to decide how thhis should work with rpc registry
|
||||
# FIXME some thoughts are required to decide how this should work with rpc registry
|
||||
def load_config(self, path: str | None = None, gui: bool = False):
|
||||
"""
|
||||
Load the configuration of the widget from YAML.
|
||||
|
||||
@@ -123,17 +123,16 @@ class BECDispatcher:
|
||||
self._registered_slots: DefaultDict[Hashable, QtThreadSafeCallback] = (
|
||||
collections.defaultdict()
|
||||
)
|
||||
self.client = client
|
||||
|
||||
if self.client is None:
|
||||
if config is not None:
|
||||
if not isinstance(config, ServiceConfig):
|
||||
# config is supposed to be a path
|
||||
config = ServiceConfig(config)
|
||||
if client is None:
|
||||
if config is not None and not isinstance(config, ServiceConfig):
|
||||
# config is supposed to be a path
|
||||
config = ServiceConfig(config)
|
||||
self.client = BECClient(
|
||||
config=config, connector_cls=QtRedisConnector, name="BECWidgets"
|
||||
)
|
||||
else:
|
||||
self.client = client
|
||||
if self.client.started:
|
||||
# have to reinitialize client to use proper connector
|
||||
logger.info("Shutting down BECClient to switch to QtRedisConnector")
|
||||
@@ -176,12 +175,15 @@ class BECDispatcher:
|
||||
cb_info (dict | None): A dictionary containing information about the callback. Defaults to None.
|
||||
"""
|
||||
qt_slot = QtThreadSafeCallback(cb=slot, cb_info=cb_info)
|
||||
if qt_slot not in self._registered_slots:
|
||||
self._registered_slots[qt_slot] = qt_slot
|
||||
qt_slot = self._registered_slots[qt_slot]
|
||||
self.client.connector.register(topics, cb=qt_slot, **kwargs)
|
||||
topics_str, _ = self.client.connector._convert_endpointinfo(topics)
|
||||
qt_slot.topics.update(set(topics_str))
|
||||
if not self.client.connector.any_stream_is_registered(topics, qt_slot):
|
||||
if qt_slot not in self._registered_slots:
|
||||
self._registered_slots[qt_slot] = qt_slot
|
||||
qt_slot = self._registered_slots[qt_slot]
|
||||
self.client.connector.register(topics, cb=qt_slot, **kwargs)
|
||||
topics_str, _ = self.client.connector._convert_endpointinfo(topics)
|
||||
qt_slot.topics.update(set(topics_str))
|
||||
else:
|
||||
logger.warning(f"Attempted to create duplicate stream subscription for {topics=}")
|
||||
|
||||
def disconnect_slot(
|
||||
self, slot: Callable, topics: EndpointInfo | str | list[EndpointInfo] | list[str]
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
Login dialog for user authentication.
|
||||
The Login Widget is styled in a Material Design style and emits
|
||||
the entered credentials through a signal for further processing.
|
||||
"""
|
||||
|
||||
from qtpy.QtCore import Qt, Signal
|
||||
from qtpy.QtWidgets import QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class BECLogin(QWidget):
|
||||
"""Login dialog for user authentication in Material Design style."""
|
||||
|
||||
credentials_entered = Signal(str, str)
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent=parent)
|
||||
# Only displayed if this widget as standalone widget, and not embedded in another widget
|
||||
self.setWindowTitle("Login")
|
||||
|
||||
title = QLabel("Sign in", parent=self)
|
||||
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
title.setStyleSheet("""
|
||||
#QLabel
|
||||
{
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
""")
|
||||
|
||||
self.username = QLineEdit(parent=self)
|
||||
self.username.setPlaceholderText("Username")
|
||||
|
||||
self.password = QLineEdit(parent=self)
|
||||
self.password.setPlaceholderText("Password")
|
||||
self.password.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
|
||||
self.ok_btn = QPushButton("Sign in", parent=self)
|
||||
self.ok_btn.setDefault(True)
|
||||
self.ok_btn.clicked.connect(self._emit_credentials)
|
||||
# If the user presses Enter in the password field, trigger the OK button click
|
||||
self.password.returnPressed.connect(self.ok_btn.click)
|
||||
|
||||
# Build Layout
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(32, 32, 32, 32)
|
||||
layout.setSpacing(16)
|
||||
|
||||
layout.addWidget(title)
|
||||
layout.addSpacing(8)
|
||||
layout.addWidget(self.username)
|
||||
layout.addWidget(self.password)
|
||||
layout.addSpacing(12)
|
||||
layout.addWidget(self.ok_btn)
|
||||
|
||||
self.username.setFocus()
|
||||
|
||||
self.setStyleSheet("""
|
||||
QLineEdit {
|
||||
padding: 8px;
|
||||
}
|
||||
""")
|
||||
|
||||
def _clear_password(self):
|
||||
"""Clear the password field."""
|
||||
self.password.clear()
|
||||
|
||||
def _emit_credentials(self):
|
||||
"""Emit credentials and clear the password field."""
|
||||
self.credentials_entered.emit(self.username.text().strip(), self.password.text())
|
||||
self._clear_password()
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import sys
|
||||
|
||||
from bec_qthemes import apply_theme
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
apply_theme("light")
|
||||
|
||||
dialog = BECLogin()
|
||||
|
||||
dialog.credentials_entered.connect(lambda u, p: print(f"Username: {u}, Password: {p}"))
|
||||
dialog.show()
|
||||
sys.exit(app.exec_())
|
||||
@@ -43,7 +43,7 @@ class WidgetContainerUtils:
|
||||
if list_of_names is None:
|
||||
list_of_names = []
|
||||
ii = 0
|
||||
while ii < 1000: # 1000 is arbritrary!
|
||||
while ii < 1000: # 1000 is arbitrary!
|
||||
name_candidate = f"{name}_{ii}"
|
||||
if name_candidate not in list_of_names:
|
||||
return name_candidate
|
||||
|
||||
@@ -106,7 +106,9 @@ class TypedForm(BECWidget, QWidget):
|
||||
|
||||
def _add_griditem(self, item: FormItemSpec, row: int):
|
||||
grid = self._form_grid.layout()
|
||||
label = QLabel(parent=self._form_grid, text=item.name)
|
||||
# Use title from FieldInfo if available, otherwise use the property name
|
||||
label_text = item.info.title if item.info.title else item.name
|
||||
label = QLabel(parent=self._form_grid, text=label_text)
|
||||
label.setProperty("_model_field_name", item.name)
|
||||
label.setToolTip(item.info.description or item.name)
|
||||
grid.addWidget(label, row, 0)
|
||||
|
||||
@@ -71,7 +71,7 @@ class FormItemSpec(BaseModel):
|
||||
"""
|
||||
The specification for an item in a dynamically generated form. Uses a pydantic FieldInfo
|
||||
to store most annotation info, since one of the main purposes is to store data for
|
||||
forms genrated from pydantic models, but can also be composed from other sources or by hand.
|
||||
forms generated from pydantic models, but can also be composed from other sources or by hand.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True)
|
||||
@@ -192,7 +192,7 @@ class DynamicFormItem(QWidget):
|
||||
@abstractmethod
|
||||
def _add_main_widget(self) -> None:
|
||||
self._main_widget: QWidget
|
||||
"""Add the main data entry widget to self._main_widget and appply any
|
||||
"""Add the main data entry widget to self._main_widget and apply any
|
||||
constraints from the field info"""
|
||||
|
||||
@SafeSlot()
|
||||
@@ -231,6 +231,8 @@ class StrFormItem(DynamicFormItem):
|
||||
def __init__(self, parent: QWidget | None = None, *, spec: FormItemSpec) -> None:
|
||||
super().__init__(parent=parent, spec=spec)
|
||||
self._main_widget.textChanged.connect(self._value_changed)
|
||||
if spec.info.description:
|
||||
self._main_widget.setPlaceholderText(spec.info.description)
|
||||
|
||||
def _add_main_widget(self) -> None:
|
||||
self._main_widget = QLineEdit()
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Module providing fuzzy search utilities for the BEC widgets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from thefuzz import fuzz
|
||||
|
||||
FUZZY_SEARCH_THRESHOLD = 80
|
||||
|
||||
|
||||
def is_match(
|
||||
text: str, row_data: dict[str, Any], relevant_keys: list[str], enable_fuzzy: bool
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the text matches any of the relevant keys in the row data.
|
||||
|
||||
Args:
|
||||
text (str): The text to search for.
|
||||
row_data (dict[str, Any]): The row data to search in.
|
||||
relevant_keys (list[str]): The keys to consider for searching.
|
||||
enable_fuzzy (bool): Whether to use fuzzy matching.
|
||||
Returns:
|
||||
bool: True if a match is found, False otherwise.
|
||||
"""
|
||||
for key in relevant_keys:
|
||||
data = str(row_data.get(key, "") or "")
|
||||
if enable_fuzzy:
|
||||
match_ratio = fuzz.partial_ratio(text.lower(), data.lower())
|
||||
if match_ratio >= FUZZY_SEARCH_THRESHOLD:
|
||||
return True
|
||||
else:
|
||||
if text.lower() in data.lower():
|
||||
return True
|
||||
return False
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import weakref
|
||||
from typing import Callable, Dict, List, TypedDict
|
||||
from typing import Callable, Dict, List, Literal, TypedDict
|
||||
from uuid import uuid4
|
||||
|
||||
import louie
|
||||
@@ -12,15 +12,18 @@ from bec_lib.logger import bec_logger
|
||||
from bec_qthemes import material_icon
|
||||
from louie import saferef
|
||||
from qtpy.QtCore import QEvent, QObject, QRect, Qt, Signal
|
||||
from qtpy.QtGui import QAction, QColor, QPainter, QPen
|
||||
from qtpy.QtGui import QAction, QColor, QKeySequence, QPainter, QPen, QShortcut
|
||||
from qtpy.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QApplication,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMainWindow,
|
||||
QMenu,
|
||||
QMenuBar,
|
||||
QPushButton,
|
||||
QTableWidgetItem,
|
||||
QToolBar,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
@@ -40,9 +43,9 @@ class TourStep(TypedDict):
|
||||
widget_ref: (
|
||||
louie.saferef.BoundMethodWeakref
|
||||
| weakref.ReferenceType[
|
||||
QWidget | QAction | Callable[[], tuple[QWidget | QAction, str | None]]
|
||||
QWidget | QAction | QRect | Callable[[], tuple[QWidget | QAction | QRect, str | None]]
|
||||
]
|
||||
| Callable[[], tuple[QWidget | QAction, str | None]]
|
||||
| Callable[[], tuple[QWidget | QAction | QRect, str | None]]
|
||||
| None
|
||||
)
|
||||
text: str
|
||||
@@ -64,15 +67,13 @@ class TutorialOverlay(QWidget):
|
||||
box = QFrame(self)
|
||||
app = QApplication.instance()
|
||||
bg_color = app.palette().window().color()
|
||||
box.setStyleSheet(
|
||||
f"""
|
||||
box.setStyleSheet(f"""
|
||||
QFrame {{
|
||||
background-color: {bg_color.name()};
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
layout = QVBoxLayout(box)
|
||||
|
||||
# Top layout with close button (left) and step indicator (right)
|
||||
@@ -103,10 +104,12 @@ class TutorialOverlay(QWidget):
|
||||
# Back button with material icon
|
||||
self.back_btn = QPushButton("Back")
|
||||
self.back_btn.setIcon(material_icon("arrow_back"))
|
||||
self.back_btn.setToolTip("Press Backspace to go back")
|
||||
|
||||
# Next button with material icon
|
||||
self.next_btn = QPushButton("Next")
|
||||
self.next_btn.setIcon(material_icon("arrow_forward"))
|
||||
self.next_btn.setToolTip("Press Enter to continue")
|
||||
|
||||
btn_layout.addStretch()
|
||||
btn_layout.addWidget(self.back_btn)
|
||||
@@ -115,6 +118,15 @@ class TutorialOverlay(QWidget):
|
||||
layout.addLayout(top_layout)
|
||||
layout.addWidget(self.label)
|
||||
layout.addLayout(btn_layout)
|
||||
|
||||
# Escape closes the tour
|
||||
QShortcut(QKeySequence(Qt.Key.Key_Escape), self, activated=self.close_btn.click)
|
||||
# Enter and Return activates the next button
|
||||
QShortcut(QKeySequence(Qt.Key.Key_Return), self, activated=self.next_btn.click)
|
||||
QShortcut(QKeySequence(Qt.Key.Key_Enter), self, activated=self.next_btn.click)
|
||||
# Map Backspace to the back button
|
||||
QShortcut(QKeySequence(Qt.Key.Key_Backspace), self, activated=self.back_btn.click)
|
||||
|
||||
return box
|
||||
|
||||
def paintEvent(self, event): # pylint: disable=unused-argument
|
||||
@@ -223,6 +235,9 @@ class TutorialOverlay(QWidget):
|
||||
self.message_box.show()
|
||||
self.update()
|
||||
|
||||
# Update the focus policy of the buttons
|
||||
self.back_btn.setEnabled(current_step > 1)
|
||||
|
||||
def eventFilter(self, obj, event):
|
||||
if event.type() == QEvent.Type.Resize:
|
||||
self.setGeometry(obj.rect())
|
||||
@@ -262,7 +277,9 @@ class GuidedTour(QObject):
|
||||
def register_widget(
|
||||
self,
|
||||
*,
|
||||
widget: QWidget | QAction | Callable[[], tuple[QWidget | QAction, str | None]],
|
||||
widget: (
|
||||
QWidget | QAction | QRect | Callable[[], tuple[QWidget | QAction | QRect, str | None]]
|
||||
),
|
||||
text: str = "",
|
||||
title: str = "",
|
||||
) -> str:
|
||||
@@ -270,7 +287,7 @@ class GuidedTour(QObject):
|
||||
Register a widget with help text for tours.
|
||||
|
||||
Args:
|
||||
widget (QWidget | QAction | Callable[[], tuple[QWidget | QAction, str | None]]): The target widget or a callable that returns the widget and its help text.
|
||||
widget (QWidget | QAction | QRect | Callable[[], tuple[QWidget | QAction | QRect, str | None]]): The target widget or a callable that returns the widget and its help text.
|
||||
text (str): The help text for the widget. This will be shown during the tour.
|
||||
title (str, optional): A title for the widget (defaults to its class name or action text).
|
||||
|
||||
@@ -293,6 +310,9 @@ class GuidedTour(QObject):
|
||||
|
||||
widget_ref = _resolve_toolbar_button
|
||||
default_title = getattr(widget, "tooltip", "Toolbar Menu")
|
||||
elif isinstance(widget, QRect):
|
||||
widget_ref = widget
|
||||
default_title = "Area"
|
||||
else:
|
||||
widget_ref = saferef.safe_ref(widget)
|
||||
default_title = widget.__class__.__name__ if hasattr(widget, "__class__") else "Widget"
|
||||
@@ -327,11 +347,14 @@ class GuidedTour(QObject):
|
||||
if mb and mb not in menubars:
|
||||
menubars.append(mb)
|
||||
menubars += [mb for mb in mw.findChildren(QMenuBar) if mb not in menubars]
|
||||
menubars += [mb for mb in mw.findChildren(QMenu) if mb not in menubars]
|
||||
|
||||
for mb in menubars:
|
||||
if action in mb.actions():
|
||||
ar = mb.actionGeometry(action)
|
||||
top_left = mb.mapTo(mw, ar.topLeft())
|
||||
return QRect(top_left, ar.size())
|
||||
|
||||
return None
|
||||
|
||||
def unregister_widget(self, step_id: str) -> bool:
|
||||
@@ -452,9 +475,9 @@ class GuidedTour(QObject):
|
||||
|
||||
if self._current_index > 0:
|
||||
self._current_index -= 1
|
||||
self._show_current_step()
|
||||
self._show_current_step(direction="prev")
|
||||
|
||||
def _show_current_step(self):
|
||||
def _show_current_step(self, direction: Literal["next"] | Literal["prev"] = "next"):
|
||||
"""Display the current step."""
|
||||
if not self._active or not self.overlay:
|
||||
return
|
||||
@@ -464,7 +487,9 @@ class GuidedTour(QObject):
|
||||
|
||||
target, step_text = self._resolve_step_target(step)
|
||||
if target is None:
|
||||
self._advance_past_invalid_step(step_title, reason="Step target no longer exists.")
|
||||
self._advance_past_invalid_step(
|
||||
step_title, reason="Step target no longer exists.", direction=direction
|
||||
)
|
||||
return
|
||||
|
||||
main_window = self.main_window
|
||||
@@ -473,7 +498,9 @@ class GuidedTour(QObject):
|
||||
self.stop_tour()
|
||||
return
|
||||
|
||||
highlight_rect = self._get_highlight_rect(main_window, target, step_title)
|
||||
highlight_rect = self._get_highlight_rect(
|
||||
main_window, target, step_title, direction=direction
|
||||
)
|
||||
if highlight_rect is None:
|
||||
return
|
||||
|
||||
@@ -483,9 +510,6 @@ class GuidedTour(QObject):
|
||||
|
||||
self.overlay.show_step(highlight_rect, step_title, step_text, current_step, total_steps)
|
||||
|
||||
# Update button states
|
||||
self.overlay.back_btn.setEnabled(self._current_index > 0)
|
||||
|
||||
# Update next button text and state
|
||||
is_last_step = self._current_index >= len(self._tour_steps) - 1
|
||||
if is_last_step:
|
||||
@@ -499,7 +523,7 @@ class GuidedTour(QObject):
|
||||
|
||||
self.step_changed.emit(self._current_index + 1, len(self._tour_steps))
|
||||
|
||||
def _resolve_step_target(self, step: TourStep) -> tuple[QWidget | QAction | None, str]:
|
||||
def _resolve_step_target(self, step: TourStep) -> tuple[QWidget | QAction | QRect | None, str]:
|
||||
"""
|
||||
Resolve the target widget/action for the given step.
|
||||
|
||||
@@ -507,7 +531,7 @@ class GuidedTour(QObject):
|
||||
step(TourStep): The tour step to resolve.
|
||||
|
||||
Returns:
|
||||
tuple[QWidget | QAction | None, str]: The resolved target and the step text.
|
||||
tuple[QWidget | QAction | QRect | None, str]: The resolved target, optional QRect, and the step text.
|
||||
"""
|
||||
widget_ref = step.get("widget_ref")
|
||||
step_text = step.get("text", "")
|
||||
@@ -520,7 +544,7 @@ class GuidedTour(QObject):
|
||||
if target is None:
|
||||
return None, step_text
|
||||
|
||||
if callable(target) and not isinstance(target, (QWidget, QAction)):
|
||||
if callable(target) and not isinstance(target, (QWidget, QAction, QRect)):
|
||||
result = target()
|
||||
if isinstance(result, tuple):
|
||||
target, alt_text = result
|
||||
@@ -532,7 +556,11 @@ class GuidedTour(QObject):
|
||||
return target, step_text
|
||||
|
||||
def _get_highlight_rect(
|
||||
self, main_window: QWidget, target: QWidget | QAction, step_title: str
|
||||
self,
|
||||
main_window: QWidget,
|
||||
target: QWidget | QAction | QRect,
|
||||
step_title: str,
|
||||
direction: Literal["next"] | Literal["prev"] = "next",
|
||||
) -> QRect | None:
|
||||
"""
|
||||
Get the QRect in main_window coordinates to highlight for the given target.
|
||||
@@ -545,12 +573,15 @@ class GuidedTour(QObject):
|
||||
Returns:
|
||||
QRect | None: The rectangle to highlight, or None if not found/visible.
|
||||
"""
|
||||
if isinstance(target, QRect):
|
||||
return target
|
||||
if isinstance(target, QAction):
|
||||
rect = self._action_highlight_rect(target)
|
||||
if rect is None:
|
||||
self._advance_past_invalid_step(
|
||||
step_title,
|
||||
reason=f"Could not find visible widget or menu for QAction {target.text()!r}.",
|
||||
direction=direction,
|
||||
)
|
||||
return None
|
||||
return rect
|
||||
@@ -559,28 +590,60 @@ class GuidedTour(QObject):
|
||||
if self._visible_check:
|
||||
if not target.isVisible():
|
||||
self._advance_past_invalid_step(
|
||||
step_title, reason=f"Widget {target!r} is not visible."
|
||||
step_title, reason=f"Widget {target!r} is not visible.", direction=direction
|
||||
)
|
||||
return None
|
||||
rect = target.rect()
|
||||
top_left = target.mapTo(main_window, rect.topLeft())
|
||||
return QRect(top_left, rect.size())
|
||||
|
||||
if isinstance(target, QTableWidgetItem):
|
||||
# NOTE: On header items (which are also QTableWidgetItems), this does not work,
|
||||
# Header items are just used as data containers by Qt, thus, we have to directly
|
||||
# pass the QRect through the method (+ make sure the appropriate header section
|
||||
# is visible). This can be handled in the callable method.)
|
||||
table = target.tableWidget()
|
||||
|
||||
if self._visible_check:
|
||||
if not table.isVisible():
|
||||
self._advance_past_invalid_step(
|
||||
step_title,
|
||||
reason=f"Table widget {table!r} is not visible.",
|
||||
direction=direction,
|
||||
)
|
||||
return None
|
||||
|
||||
# Table item
|
||||
if table.item(target.row(), target.column()) == target:
|
||||
table.scrollToItem(target, QAbstractItemView.ScrollHint.PositionAtCenter)
|
||||
rect = table.visualItemRect(target)
|
||||
top_left = table.viewport().mapTo(main_window, rect.topLeft())
|
||||
return QRect(top_left, rect.size())
|
||||
|
||||
self._advance_past_invalid_step(
|
||||
step_title, reason=f"Unsupported step target type: {type(target)}"
|
||||
step_title, reason=f"Unsupported step target type: {type(target)}", direction=direction
|
||||
)
|
||||
return None
|
||||
|
||||
def _advance_past_invalid_step(self, step_title: str, *, reason: str):
|
||||
def _advance_past_invalid_step(
|
||||
self, step_title: str, *, reason: str, direction: Literal["next"] | Literal["prev"] = "next"
|
||||
):
|
||||
"""
|
||||
Skip the current step (or stop the tour) when the target cannot be visualised.
|
||||
"""
|
||||
logger.warning("%s Skipping step %r.", reason, step_title)
|
||||
if self._current_index < len(self._tour_steps) - 1:
|
||||
self._current_index += 1
|
||||
self._show_current_step()
|
||||
else:
|
||||
self.stop_tour()
|
||||
logger.warning(f"{reason} Skipping step {step_title!r}.")
|
||||
if direction == "next":
|
||||
if self._current_index < len(self._tour_steps) - 1:
|
||||
self._current_index += 1
|
||||
self._show_current_step()
|
||||
else:
|
||||
self.stop_tour()
|
||||
elif direction == "prev":
|
||||
if self._current_index > 0:
|
||||
self._current_index -= 1
|
||||
self._show_current_step(direction="prev")
|
||||
else:
|
||||
self.stop_tour()
|
||||
|
||||
def get_registered_widgets(self) -> Dict[str, TourStep]:
|
||||
"""Get all registered widgets."""
|
||||
@@ -663,8 +726,33 @@ class MainWindow(QMainWindow): # pragma: no cover
|
||||
title="Tools Menu",
|
||||
)
|
||||
|
||||
sub_menu_action = self.tools_menu_actions["notes"].action
|
||||
|
||||
def get_sub_menu_action():
|
||||
# open the tools menu
|
||||
menu_button = self.tools_menu_action._button_ref()
|
||||
if menu_button:
|
||||
menu_button.showMenu()
|
||||
|
||||
return (
|
||||
self.tools_menu_action.actions["notes"].action,
|
||||
"This action allows you to add notes.",
|
||||
)
|
||||
|
||||
sub_menu = self.guided_help.register_widget(
|
||||
widget=get_sub_menu_action,
|
||||
text="This is a sub-action within the tools menu.",
|
||||
title="Add Note Action",
|
||||
)
|
||||
|
||||
# Create tour from registered widgets
|
||||
self.tour_step_ids = [primary_step, secondary_step, toolbar_action_step, tools_menu_step]
|
||||
self.tour_step_ids = [
|
||||
sub_menu,
|
||||
primary_step,
|
||||
secondary_step,
|
||||
toolbar_action_step,
|
||||
tools_menu_step,
|
||||
]
|
||||
widget_ids = self.tour_step_ids
|
||||
self.guided_help.create_tour(widget_ids)
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ class HelpInspector(BECWidget, QtWidgets.QWidget):
|
||||
# TODO check what happens if the HELP Inspector itself is embedded in another BECWidget
|
||||
# I suppose we would like to get the first ancestor that is a BECWidget, not the topmost one
|
||||
if not isinstance(widget, BECWidget):
|
||||
widget = WidgetHierarchy._get_becwidget_ancestor(widget)
|
||||
widget = WidgetHierarchy.get_becwidget_ancestor(widget)
|
||||
if widget:
|
||||
if widget is self:
|
||||
self._toggle_mode(False)
|
||||
|
||||
@@ -15,7 +15,7 @@ class Kind(IFBase):
|
||||
"""
|
||||
This is used in the .kind attribute of all OphydObj (Signals, Devices).
|
||||
|
||||
A Device examines its components' .kind atttribute to decide whether to
|
||||
A Device examines its components' .kind attribute to decide whether to
|
||||
traverse it in read(), read_configuration(), or neither. Additionally, if
|
||||
decides whether to include its name in `hints['fields']`.
|
||||
"""
|
||||
|
||||
@@ -22,7 +22,7 @@ class {plugin_name_pascal}Plugin(QDesignerCustomWidgetInterface): # pragma: no
|
||||
|
||||
def createWidget(self, parent):
|
||||
if parent is None:
|
||||
return QWidget()
|
||||
return QWidget()
|
||||
t = {plugin_name_pascal}(parent)
|
||||
return t
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Iterable
|
||||
|
||||
from bec_lib.plugin_helper import _get_available_plugins
|
||||
from qtpy.QtWidgets import QGraphicsWidget, QWidget
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.utils import BECConnector
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
@@ -166,18 +166,17 @@ class BECClassContainer:
|
||||
return [info.obj for info in self.collection]
|
||||
|
||||
|
||||
def get_custom_classes(repo_name: str) -> BECClassContainer:
|
||||
"""
|
||||
Get all RPC-enabled classes in the specified repository.
|
||||
|
||||
Args:
|
||||
repo_name(str): The name of the repository.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary with keys "connector_classes" and "top_level_classes" and values as lists of classes.
|
||||
"""
|
||||
def _collect_classes_from_package(repo_name: str, package: str) -> BECClassContainer:
|
||||
"""Collect classes from a package subtree (for example ``widgets`` or ``applications``)."""
|
||||
collection = BECClassContainer()
|
||||
anchor_module = importlib.import_module(f"{repo_name}.widgets")
|
||||
try:
|
||||
anchor_module = importlib.import_module(f"{repo_name}.{package}")
|
||||
except ModuleNotFoundError as exc:
|
||||
# Some plugin repositories expose only one subtree. Skip gracefully if it does not exist.
|
||||
if exc.name == f"{repo_name}.{package}":
|
||||
return collection
|
||||
raise
|
||||
|
||||
directory = os.path.dirname(anchor_module.__file__)
|
||||
for root, _, files in sorted(os.walk(directory)):
|
||||
for file in files:
|
||||
@@ -185,13 +184,13 @@ def get_custom_classes(repo_name: str) -> BECClassContainer:
|
||||
continue
|
||||
|
||||
path = os.path.join(root, file)
|
||||
subs = os.path.dirname(os.path.relpath(path, directory)).split("/")
|
||||
if len(subs) == 1 and not subs[0]:
|
||||
rel_dir = os.path.dirname(os.path.relpath(path, directory))
|
||||
if rel_dir in ("", "."):
|
||||
module_name = file.split(".")[0]
|
||||
else:
|
||||
module_name = ".".join(subs + [file.split(".")[0]])
|
||||
module_name = ".".join(rel_dir.split(os.sep) + [file.split(".")[0]])
|
||||
|
||||
module = importlib.import_module(f"{repo_name}.widgets.{module_name}")
|
||||
module = importlib.import_module(f"{repo_name}.{package}.{module_name}")
|
||||
|
||||
for name in dir(module):
|
||||
obj = getattr(module, name)
|
||||
@@ -203,12 +202,30 @@ def get_custom_classes(repo_name: str) -> BECClassContainer:
|
||||
class_info.is_connector = True
|
||||
if issubclass(obj, QWidget) or issubclass(obj, BECWidget):
|
||||
class_info.is_widget = True
|
||||
if len(subs) == 1 and (
|
||||
issubclass(obj, QWidget) or issubclass(obj, QGraphicsWidget)
|
||||
):
|
||||
class_info.is_top_level = True
|
||||
if hasattr(obj, "PLUGIN") and obj.PLUGIN:
|
||||
class_info.is_plugin = True
|
||||
collection.add_class(class_info)
|
||||
|
||||
return collection
|
||||
|
||||
|
||||
def get_custom_classes(
|
||||
repo_name: str, packages: tuple[str, ...] | None = None
|
||||
) -> BECClassContainer:
|
||||
"""
|
||||
Get all relevant classes for RPC/CLI in the specified repository.
|
||||
|
||||
By default, discovery is limited to ``<repo>.widgets`` for backward compatibility.
|
||||
Additional package subtrees (for example ``applications``) can be included explicitly.
|
||||
|
||||
Args:
|
||||
repo_name(str): The name of the repository.
|
||||
packages(tuple[str, ...] | None): Optional tuple of package names to scan. Defaults to ("widgets",) for backward compatibility.
|
||||
|
||||
Returns:
|
||||
BECClassContainer: Container with collected class information.
|
||||
"""
|
||||
selected_packages = packages or ("widgets",)
|
||||
collection = BECClassContainer()
|
||||
for package in selected_packages:
|
||||
collection += _collect_classes_from_package(repo_name, package)
|
||||
return collection
|
||||
|
||||
@@ -69,13 +69,11 @@ class RoundedFrame(QFrame):
|
||||
"""
|
||||
Update the style of the frame based on the background color.
|
||||
"""
|
||||
self.setStyleSheet(
|
||||
f"""
|
||||
self.setStyleSheet(f"""
|
||||
QFrame#roundedFrame {{
|
||||
border-radius: {self._radius}px;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
self.apply_plot_widget_style()
|
||||
|
||||
def apply_plot_widget_style(self, border: str = "none"):
|
||||
|
||||
@@ -4,20 +4,24 @@ import functools
|
||||
import traceback
|
||||
import types
|
||||
from contextlib import contextmanager
|
||||
from typing import TYPE_CHECKING, Callable, TypeVar
|
||||
from typing import TYPE_CHECKING, Callable, Literal, TypeVar
|
||||
|
||||
from bec_lib.client import BECClient
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.utils.import_utils import lazy_import
|
||||
from qtpy.QtCore import Qt, QTimer
|
||||
from qtpy.QtWidgets import QWidget
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from bec_widgets.cli.rpc.rpc_register import RPCRegister
|
||||
from bec_widgets.utils import BECDispatcher
|
||||
from bec_widgets.utils.bec_connector import BECConnector
|
||||
from bec_widgets.utils.container_utils import WidgetContainerUtils
|
||||
from bec_widgets.utils.error_popups import ErrorPopupUtility
|
||||
from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow
|
||||
from bec_widgets.utils.screen_utils import apply_window_geometry
|
||||
from bec_widgets.widgets.containers.dock_area.dock_area import BECDockArea
|
||||
from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow, BECMainWindowNoRPC
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from bec_lib import messages
|
||||
@@ -114,11 +118,14 @@ class RPCServer:
|
||||
logger.debug(f"Received RPC instruction: {msg}, metadata: {metadata}")
|
||||
with rpc_exception_hook(functools.partial(self.send_response, request_id, False)):
|
||||
try:
|
||||
obj = self.get_object_from_config(msg["parameter"])
|
||||
method = msg["action"]
|
||||
args = msg["parameter"].get("args", [])
|
||||
kwargs = msg["parameter"].get("kwargs", {})
|
||||
res = self.run_rpc(obj, method, args, kwargs)
|
||||
if method.startswith("system."):
|
||||
res = self.run_system_rpc(method, args, kwargs)
|
||||
else:
|
||||
obj = self.get_object_from_config(msg["parameter"])
|
||||
res = self.run_rpc(obj, method, args, kwargs)
|
||||
except Exception:
|
||||
content = traceback.format_exc()
|
||||
logger.error(f"Error while executing RPC instruction: {content}")
|
||||
@@ -149,7 +156,7 @@ class RPCServer:
|
||||
if method == "raise" and hasattr(
|
||||
obj, "setWindowState"
|
||||
): # special case for raising windows, should work even if minimized
|
||||
# this is a special case for raising windows for gnome on rethat 9 systems where changing focus is supressed by default
|
||||
# this is a special case for raising windows for gnome on Red Hat (RHEL) 9 systems where changing focus is suppressed by default
|
||||
# The procedure is as follows:
|
||||
# 1. Get the current window state to check if the window is minimized and remove minimized flag
|
||||
# 2. Then in order to force gnome to raise the window, we set the window to stay on top temporarily
|
||||
@@ -174,18 +181,96 @@ class RPCServer:
|
||||
obj.show()
|
||||
res = None
|
||||
else:
|
||||
method_obj = getattr(obj, method)
|
||||
target_obj, method_obj = self._resolve_rpc_target(obj, method)
|
||||
# check if the method accepts args and kwargs
|
||||
if not callable(method_obj):
|
||||
if not args:
|
||||
res = method_obj
|
||||
else:
|
||||
setattr(obj, method, args[0])
|
||||
setattr(target_obj, method, args[0])
|
||||
res = None
|
||||
else:
|
||||
res = method_obj(*args, **kwargs)
|
||||
return res
|
||||
|
||||
def _resolve_rpc_target(self, obj, method: str) -> tuple[object, object]:
|
||||
"""
|
||||
Resolve a method/property access target for RPC execution.
|
||||
|
||||
Primary target is the object itself. If not found there and the class defines
|
||||
``RPC_CONTENT_CLASS``, unresolved method names can be delegated to the content
|
||||
widget referenced by ``RPC_CONTENT_ATTR`` (default ``content``), but only when
|
||||
the method is explicitly listed in the content class ``USER_ACCESS``.
|
||||
"""
|
||||
if hasattr(obj, method):
|
||||
return obj, getattr(obj, method)
|
||||
|
||||
content_cls = getattr(type(obj), "RPC_CONTENT_CLASS", None)
|
||||
if content_cls is None:
|
||||
raise AttributeError(f"{type(obj).__name__} has no attribute '{method}'")
|
||||
|
||||
content_user_access = set()
|
||||
for entry in getattr(content_cls, "USER_ACCESS", []):
|
||||
if entry.endswith(".setter"):
|
||||
content_user_access.add(entry.split(".setter")[0])
|
||||
else:
|
||||
content_user_access.add(entry)
|
||||
|
||||
if method not in content_user_access:
|
||||
raise AttributeError(f"{type(obj).__name__} has no attribute '{method}'")
|
||||
|
||||
content_attr = getattr(type(obj), "RPC_CONTENT_ATTR", "content")
|
||||
target_obj = getattr(obj, content_attr, None)
|
||||
if target_obj is None:
|
||||
raise AttributeError(
|
||||
f"{type(obj).__name__} has no content target '{content_attr}' for RPC delegation"
|
||||
)
|
||||
if not isinstance(target_obj, content_cls):
|
||||
raise AttributeError(
|
||||
f"{type(obj).__name__}.{content_attr} is not instance of {content_cls.__name__}"
|
||||
)
|
||||
if not hasattr(target_obj, method):
|
||||
raise AttributeError(f"{content_cls.__name__} has no attribute '{method}'")
|
||||
return target_obj, getattr(target_obj, method)
|
||||
|
||||
def run_system_rpc(self, method: str, args: list, kwargs: dict):
|
||||
if method == "system.launch_dock_area":
|
||||
return self._launch_dock_area(*args, **kwargs)
|
||||
if method == "system.list_capabilities":
|
||||
return {"system.launch_dock_area": True}
|
||||
raise ValueError(f"Unknown system RPC method: {method}")
|
||||
|
||||
@staticmethod
|
||||
def _launch_dock_area(
|
||||
name: str | None = None,
|
||||
geometry: tuple[int, int, int, int] | None = None,
|
||||
startup_profile: str | Literal["restore", "skip"] | None = None,
|
||||
) -> QWidget | None:
|
||||
from bec_widgets.applications import bw_launch
|
||||
|
||||
with RPCRegister.delayed_broadcast() as rpc_register:
|
||||
existing_dock_areas = rpc_register.get_names_of_rpc_by_class_type(BECDockArea)
|
||||
if name is not None:
|
||||
WidgetContainerUtils.raise_for_invalid_name(name)
|
||||
if name in existing_dock_areas:
|
||||
name = WidgetContainerUtils.generate_unique_name(name, existing_dock_areas)
|
||||
else:
|
||||
name = WidgetContainerUtils.generate_unique_name("dock_area", existing_dock_areas)
|
||||
|
||||
result_widget = bw_launch.dock_area(object_name=name, startup_profile=startup_profile)
|
||||
result_widget.window().setWindowTitle(f"BEC - {name}")
|
||||
|
||||
if isinstance(result_widget, BECMainWindow):
|
||||
apply_window_geometry(result_widget, geometry)
|
||||
result_widget.show()
|
||||
else:
|
||||
window = BECMainWindowNoRPC()
|
||||
window.setCentralWidget(result_widget)
|
||||
window.setWindowTitle(f"BEC - {result_widget.objectName()}")
|
||||
apply_window_geometry(window, geometry)
|
||||
window.show()
|
||||
return result_widget
|
||||
|
||||
def serialize_result_and_send(self, request_id: str, res: object):
|
||||
"""
|
||||
Serialize the result of an RPC call and send it back to the client.
|
||||
@@ -255,6 +340,9 @@ class RPCServer:
|
||||
# Respect RPC = False
|
||||
if getattr(obj, "RPC", True) is False:
|
||||
return None
|
||||
# Respect rpc_exposed = False
|
||||
if getattr(obj, "rpc_exposed", True) is False:
|
||||
return None
|
||||
return self._serialize_bec_connector(obj, wait=True)
|
||||
|
||||
def emit_heartbeat(self) -> None:
|
||||
@@ -283,6 +371,8 @@ class RPCServer:
|
||||
continue
|
||||
if not getattr(val, "RPC", True):
|
||||
continue
|
||||
if not getattr(val, "rpc_exposed", True):
|
||||
continue
|
||||
data[key] = self._serialize_bec_connector(val)
|
||||
if self._broadcasted_data == data:
|
||||
return
|
||||
@@ -333,23 +423,9 @@ class RPCServer:
|
||||
"widget_class": widget_class,
|
||||
"config": config_dict,
|
||||
"container_proxy": container_proxy,
|
||||
"__rpc__": True,
|
||||
"__rpc__": getattr(connector, "rpc_exposed", True),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_becwidget_ancestor(widget: QObject) -> BECConnector | None:
|
||||
"""
|
||||
Traverse up the parent chain to find the nearest BECConnector.
|
||||
Returns None if none is found.
|
||||
"""
|
||||
|
||||
parent = widget.parent()
|
||||
while parent is not None:
|
||||
if isinstance(parent, BECConnector):
|
||||
return parent
|
||||
parent = parent.parent()
|
||||
return None
|
||||
|
||||
# Suppose clients register callbacks to receive updates
|
||||
def add_registry_update_callback(self, cb: Callable) -> None:
|
||||
"""
|
||||
@@ -366,5 +442,5 @@ class RPCServer:
|
||||
self.status = messages.BECStatus.IDLE
|
||||
self._heartbeat_timer.stop()
|
||||
self.emit_heartbeat()
|
||||
logger.info("Succeded in shutting down CLI server")
|
||||
logger.info("Succeeded in shutting down CLI server")
|
||||
self.client.shutdown()
|
||||
|
||||
@@ -5,8 +5,7 @@ import os
|
||||
import weakref
|
||||
from abc import ABC, abstractmethod
|
||||
from contextlib import contextmanager
|
||||
from enum import Enum
|
||||
from typing import Dict, Literal, Union
|
||||
from typing import Dict, Literal
|
||||
|
||||
from bec_lib.device import ReadoutPriority
|
||||
from bec_lib.logger import bec_logger
|
||||
@@ -16,7 +15,6 @@ from qtpy.QtGui import QAction, QColor, QIcon # type: ignore
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QComboBox,
|
||||
QGraphicsDropShadowEffect,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMenu,
|
||||
@@ -28,7 +26,6 @@ from qtpy.QtWidgets import (
|
||||
)
|
||||
|
||||
import bec_widgets
|
||||
from bec_widgets.utils.colors import AccentColors, get_accent_colors
|
||||
from bec_widgets.utils.toolbars.splitter import ResizableSpacer
|
||||
from bec_widgets.widgets.control.device_input.base_classes.device_input_base import BECDeviceFilter
|
||||
from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import DeviceComboBox
|
||||
@@ -38,16 +35,19 @@ logger = bec_logger.logger
|
||||
MODULE_PATH = os.path.dirname(bec_widgets.__file__)
|
||||
|
||||
|
||||
def create_action_with_text(toolbar_action, toolbar: QToolBar):
|
||||
def create_action_with_text(toolbar_action, toolbar: QToolBar, min_size: QSize | None = None):
|
||||
"""
|
||||
Helper function to create a toolbar button with text beside or under the icon.
|
||||
|
||||
Args:
|
||||
toolbar_action(ToolBarAction): The toolbar action to create the button for.
|
||||
toolbar(ModularToolBar): The toolbar to add the button to.
|
||||
min_size(QSize, optional): The minimum size for the button. Defaults to None.
|
||||
"""
|
||||
|
||||
btn = QToolButton(parent=toolbar)
|
||||
if min_size is not None:
|
||||
btn.setMinimumSize(min_size)
|
||||
if getattr(toolbar_action, "label_text", None):
|
||||
toolbar_action.action.setText(toolbar_action.label_text)
|
||||
if getattr(toolbar_action, "tooltip", None):
|
||||
@@ -105,205 +105,6 @@ class LongPressToolButton(QToolButton):
|
||||
self.showMenu()
|
||||
|
||||
|
||||
class StatusState(str, Enum):
|
||||
DEFAULT = "default"
|
||||
HIGHLIGHT = "highlight"
|
||||
WARNING = "warning"
|
||||
EMERGENCY = "emergency"
|
||||
SUCCESS = "success"
|
||||
|
||||
|
||||
class StatusIndicatorWidget(QWidget):
|
||||
"""Pill-shaped status indicator with icon + label using accent colors."""
|
||||
|
||||
def __init__(
|
||||
self, parent=None, text: str = "Ready", state: StatusState | str = StatusState.DEFAULT
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("StatusIndicatorWidget")
|
||||
self._text = text
|
||||
self._state = self._normalize_state(state)
|
||||
self._theme_connected = False
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(6, 2, 8, 2)
|
||||
layout.setSpacing(6)
|
||||
|
||||
self._icon_label = QLabel(self)
|
||||
self._icon_label.setFixedSize(18, 18)
|
||||
|
||||
self._text_label = QLabel(self)
|
||||
self._text_label.setText(self._text)
|
||||
|
||||
layout.addWidget(self._icon_label)
|
||||
layout.addWidget(self._text_label)
|
||||
|
||||
# Give it a consistent pill height
|
||||
self.setMinimumHeight(24)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
|
||||
|
||||
# Soft shadow similar to notification banners
|
||||
self._shadow = QGraphicsDropShadowEffect(self)
|
||||
self._shadow.setBlurRadius(18)
|
||||
self._shadow.setOffset(0, 2)
|
||||
self.setGraphicsEffect(self._shadow)
|
||||
|
||||
self._apply_state(self._state)
|
||||
self._connect_theme_change()
|
||||
|
||||
def set_state(self, state: Union[StatusState, str]):
|
||||
"""Update state and refresh visuals."""
|
||||
self._state = self._normalize_state(state)
|
||||
self._apply_state(self._state)
|
||||
|
||||
def set_text(self, text: str):
|
||||
"""Update the displayed text."""
|
||||
self._text = text
|
||||
self._text_label.setText(text)
|
||||
|
||||
def _apply_state(self, state: StatusState):
|
||||
palette = self._resolve_accent_colors()
|
||||
color_attr = {
|
||||
StatusState.DEFAULT: "default",
|
||||
StatusState.HIGHLIGHT: "highlight",
|
||||
StatusState.WARNING: "warning",
|
||||
StatusState.EMERGENCY: "emergency",
|
||||
StatusState.SUCCESS: "success",
|
||||
}.get(state, "default")
|
||||
base_color = getattr(palette, color_attr, None) or getattr(
|
||||
palette, "default", QColor("gray")
|
||||
)
|
||||
|
||||
# Apply style first (returns text color for label)
|
||||
text_color = self._update_style(base_color, self._theme_fg_color())
|
||||
theme_name = self._theme_name()
|
||||
|
||||
# Choose icon per state
|
||||
icon_name_map = {
|
||||
StatusState.DEFAULT: "check_circle",
|
||||
StatusState.HIGHLIGHT: "check_circle",
|
||||
StatusState.SUCCESS: "check_circle",
|
||||
StatusState.WARNING: "warning",
|
||||
StatusState.EMERGENCY: "dangerous",
|
||||
}
|
||||
icon_name = icon_name_map.get(state, "check_circle")
|
||||
|
||||
# Icon color:
|
||||
# - Dark mode: follow text color (usually white) for high contrast.
|
||||
# - Light mode: use a stronger version of the accent color for a colored glyph
|
||||
# that stands out on the pastel pill background.
|
||||
if theme_name == "light":
|
||||
icon_q = QColor(base_color)
|
||||
icon_color = icon_q.name(QColor.HexRgb)
|
||||
else:
|
||||
icon_color = text_color
|
||||
|
||||
icon = material_icon(
|
||||
icon_name, size=(18, 18), convert_to_pixmap=False, filled=True, color=icon_color
|
||||
)
|
||||
if not icon.isNull():
|
||||
self._icon_label.setPixmap(icon.pixmap(18, 18))
|
||||
|
||||
def _update_style(self, color: QColor, fg_color: QColor) -> str:
|
||||
# Ensure the widget actually paints its own background
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
|
||||
fg = QColor(fg_color)
|
||||
text_color = fg.name(QColor.HexRgb)
|
||||
|
||||
theme_name = self._theme_name()
|
||||
|
||||
base = QColor(color)
|
||||
|
||||
start = QColor(base)
|
||||
end = QColor(base)
|
||||
border = QColor(base)
|
||||
|
||||
if theme_name == "light":
|
||||
start.setAlphaF(0.20)
|
||||
end.setAlphaF(0.06)
|
||||
else:
|
||||
start.setAlphaF(0.35)
|
||||
end.setAlphaF(0.12)
|
||||
border = border.darker(120)
|
||||
|
||||
# shadow color tuned per theme to match notification banners
|
||||
if hasattr(self, "_shadow"):
|
||||
if theme_name == "light":
|
||||
shadow_color = QColor(15, 23, 42, 60) # softer shadow on light bg
|
||||
else:
|
||||
shadow_color = QColor(0, 0, 0, 160)
|
||||
self._shadow.setColor(shadow_color)
|
||||
|
||||
# Use a fixed radius for a stable pill look inside toolbars
|
||||
radius = 10
|
||||
|
||||
self.setStyleSheet(
|
||||
f"""
|
||||
#StatusIndicatorWidget {{
|
||||
background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1,
|
||||
stop:0 {start.name(QColor.HexArgb)}, stop:1 {end.name(QColor.HexArgb)});
|
||||
border: 1px solid {border.name(QColor.HexRgb)};
|
||||
border-radius: {radius}px;
|
||||
padding: 2px 8px;
|
||||
}}
|
||||
#StatusIndicatorWidget QLabel {{
|
||||
color: {text_color};
|
||||
background: transparent;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
return text_color
|
||||
|
||||
def _theme_fg_color(self) -> QColor:
|
||||
app = QApplication.instance()
|
||||
theme = getattr(app, "theme", None)
|
||||
if theme is not None and hasattr(theme, "color"):
|
||||
try:
|
||||
fg = theme.color("FG")
|
||||
if isinstance(fg, QColor):
|
||||
return fg
|
||||
except Exception:
|
||||
pass
|
||||
palette = self._resolve_accent_colors()
|
||||
base = getattr(palette, "default", QColor("white"))
|
||||
luminance = (0.299 * base.red() + 0.587 * base.green() + 0.114 * base.blue()) / 255
|
||||
return QColor("#000000") if luminance > 0.65 else QColor("#ffffff")
|
||||
|
||||
def _theme_name(self) -> str:
|
||||
app = QApplication.instance()
|
||||
theme = getattr(app, "theme", None)
|
||||
name = getattr(theme, "theme", None)
|
||||
if isinstance(name, str):
|
||||
return name.lower()
|
||||
return "dark"
|
||||
|
||||
def _connect_theme_change(self):
|
||||
if self._theme_connected:
|
||||
return
|
||||
app = QApplication.instance()
|
||||
theme = getattr(app, "theme", None)
|
||||
if theme is not None and hasattr(theme, "theme_changed"):
|
||||
try:
|
||||
theme.theme_changed.connect(lambda _: self._apply_state(self._state))
|
||||
self._theme_connected = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _normalize_state(state: Union[StatusState, str]) -> StatusState:
|
||||
if isinstance(state, StatusState):
|
||||
return state
|
||||
try:
|
||||
return StatusState(state)
|
||||
except ValueError:
|
||||
return StatusState.DEFAULT
|
||||
|
||||
@staticmethod
|
||||
def _resolve_accent_colors() -> AccentColors:
|
||||
return get_accent_colors()
|
||||
|
||||
|
||||
class ToolBarAction(ABC):
|
||||
"""
|
||||
Abstract base class for toolbar actions.
|
||||
@@ -350,54 +151,6 @@ class SeparatorAction(ToolBarAction):
|
||||
toolbar.addSeparator()
|
||||
|
||||
|
||||
class StatusIndicatorAction(ToolBarAction):
|
||||
"""Toolbar action hosting a LED indicator and status text."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
text: str = "Ready",
|
||||
state: Union[StatusState, str] = StatusState.DEFAULT,
|
||||
tooltip: str | None = None,
|
||||
):
|
||||
super().__init__(icon_path=None, tooltip=tooltip or "View status", checkable=False)
|
||||
self._text = text
|
||||
self._state: StatusState = StatusIndicatorWidget._normalize_state(state)
|
||||
self.widget: StatusIndicatorWidget | None = None
|
||||
self.tooltip = tooltip or ""
|
||||
|
||||
def add_to_toolbar(self, toolbar: QToolBar, target: QWidget):
|
||||
if (
|
||||
self.widget is None
|
||||
or self.widget.parent() is None
|
||||
or self.widget.parent() is not toolbar
|
||||
):
|
||||
self.widget = StatusIndicatorWidget(parent=toolbar, text=self._text, state=self._state)
|
||||
self.action = toolbar.addWidget(self.widget)
|
||||
self.action.setText(self._text)
|
||||
self.set_tooltip(self.tooltip)
|
||||
|
||||
def set_state(self, state: Union[StatusState, str]):
|
||||
self._state = StatusIndicatorWidget._normalize_state(state)
|
||||
if self.widget is not None:
|
||||
self.widget.set_state(self._state)
|
||||
|
||||
def set_text(self, text: str):
|
||||
self._text = text
|
||||
if self.widget is not None:
|
||||
self.widget.set_text(text)
|
||||
if hasattr(self, "action") and self.action is not None:
|
||||
self.action.setText(text)
|
||||
|
||||
def set_tooltip(self, tooltip: str | None):
|
||||
"""Set tooltip on both the underlying widget and the QWidgetAction."""
|
||||
self.tooltip = tooltip or ""
|
||||
if self.widget is not None:
|
||||
self.widget.setToolTip(self.tooltip)
|
||||
if hasattr(self, "action") and self.action is not None:
|
||||
self.action.setToolTip(self.tooltip)
|
||||
|
||||
|
||||
class QtIconAction(IconAction):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -849,16 +602,14 @@ class ExpandableMenuAction(ToolBarAction):
|
||||
button.setIcon(QIcon(self.icon_path))
|
||||
button.setText(self.tooltip)
|
||||
button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
|
||||
button.setStyleSheet(
|
||||
"""
|
||||
button.setStyleSheet("""
|
||||
QToolButton {
|
||||
font-size: 14px;
|
||||
}
|
||||
QMenu {
|
||||
font-size: 14px;
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
menu = QMenu(button)
|
||||
for action_container in self.actions.values():
|
||||
action: QAction = action_container.action
|
||||
|
||||
@@ -106,8 +106,7 @@ class ResizableSpacer(QWidget):
|
||||
|
||||
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
|
||||
self.setStyleSheet(
|
||||
"""
|
||||
self.setStyleSheet("""
|
||||
ResizableSpacer {
|
||||
background-color: transparent;
|
||||
margin: 0px;
|
||||
@@ -117,8 +116,7 @@ class ResizableSpacer(QWidget):
|
||||
ResizableSpacer:hover {
|
||||
background-color: rgba(100, 100, 200, 80);
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
self.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.messages import BeamlineStateConfig
|
||||
from qtpy.QtCore import QObject, QTimer, Signal
|
||||
|
||||
from bec_widgets.utils.bec_connector import BECConnector
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.toolbars.actions import StatusIndicatorAction, StatusState
|
||||
from bec_widgets.utils.toolbars.toolbar import ModularToolBar
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class BECStatusBroker(BECConnector, QObject):
|
||||
"""Listen to BEC beamline state endpoints and emit structured signals."""
|
||||
|
||||
_instance: "BECStatusBroker | None" = None
|
||||
_initialized: bool = False
|
||||
|
||||
available_updated = Signal(list) # list of states available
|
||||
status_updated = Signal(str, dict) # name, status update
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, parent=None, gui_id: str | None = None, client=None, **kwargs):
|
||||
if self._initialized:
|
||||
return
|
||||
super().__init__(parent=parent, gui_id=gui_id, client=client, **kwargs)
|
||||
self._watched: set[str] = set()
|
||||
self.bec_dispatcher.connect_slot(
|
||||
self.on_available, MessageEndpoints.available_beamline_states()
|
||||
)
|
||||
|
||||
self._initialized = True
|
||||
self.refresh_available()
|
||||
|
||||
def refresh_available(self):
|
||||
"""Fetch the current set of beamline conditions once."""
|
||||
try:
|
||||
msg = self.client.connector.get_last(MessageEndpoints.available_beamline_states())
|
||||
logger.info(f"StatusBroker: fetched available conditions payload: {msg}")
|
||||
if msg:
|
||||
self.on_available(msg.get("data").content, None)
|
||||
except Exception as exc: # pragma: no cover - runtime env
|
||||
logger.debug(f"Could not fetch available conditions: {exc}")
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def on_available(self, data: dict, meta: dict | None = None):
|
||||
state_list = data.get("states") # latest one from the stream
|
||||
self.available_updated.emit(state_list)
|
||||
for state in state_list:
|
||||
name = state.name
|
||||
if name:
|
||||
self.watch_state(name)
|
||||
|
||||
def watch_state(self, name: str):
|
||||
"""Subscribe to updates for a single beamline state."""
|
||||
if name in self._watched:
|
||||
return
|
||||
self._watched.add(name)
|
||||
endpoint = MessageEndpoints.beamline_state(name)
|
||||
logger.info(f"StatusBroker: watching state '{name}' on {endpoint.endpoint}")
|
||||
self.bec_dispatcher.connect_slot(self.on_state, endpoint)
|
||||
self.fetch_state(name)
|
||||
|
||||
def fetch_state(self, name: str):
|
||||
"""Fetch the current value of a beamline state once."""
|
||||
endpoint = MessageEndpoints.beamline_state(name)
|
||||
try:
|
||||
msg = self.client.connector.get_last(endpoint)
|
||||
logger.info(f"StatusBroker: fetched state '{name}' payload: {msg}")
|
||||
if msg:
|
||||
self.on_state(msg.get("data").content, None)
|
||||
except Exception as exc: # pragma: no cover - runtime env
|
||||
logger.debug(f"Could not fetch state {name}: {exc}")
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def on_state(self, data: dict, meta: dict | None = None):
|
||||
name = data.get("name")
|
||||
if not name:
|
||||
return
|
||||
logger.info(f"StatusBroker: state update for '{name}' -> {data}")
|
||||
self.status_updated.emit(str(name), data)
|
||||
|
||||
@classmethod
|
||||
def reset_singleton(cls):
|
||||
"""
|
||||
Reset the singleton instance of the BECStatusBroker.
|
||||
"""
|
||||
cls._instance = None
|
||||
cls._initialized = False
|
||||
|
||||
|
||||
class StatusToolBar(ModularToolBar):
|
||||
"""Status toolbar that auto-manages beamline state indicators."""
|
||||
|
||||
STATUS_MAP: dict[str, StatusState] = {
|
||||
"valid": StatusState.SUCCESS,
|
||||
"warning": StatusState.WARNING,
|
||||
"invalid": StatusState.EMERGENCY,
|
||||
}
|
||||
|
||||
def __init__(self, parent=None, names: list[str] | None = None, **kwargs):
|
||||
super().__init__(parent=parent, orientation="horizontal", **kwargs)
|
||||
self.setObjectName("StatusToolbar")
|
||||
self._status_bundle = self.new_bundle("status")
|
||||
self.show_bundles(["status"])
|
||||
self._apply_status_toolbar_style()
|
||||
|
||||
self.allowed_names: set[str] | None = set(names) if names is not None else None
|
||||
logger.info(f"StatusToolbar init allowed_names={self.allowed_names}")
|
||||
|
||||
self.broker = BECStatusBroker()
|
||||
self.broker.available_updated.connect(self.on_available_updated)
|
||||
self.broker.status_updated.connect(self.on_status_updated)
|
||||
|
||||
QTimer.singleShot(0, self.refresh_from_broker)
|
||||
|
||||
def refresh_from_broker(self) -> None:
|
||||
|
||||
if self.allowed_names is None:
|
||||
self.broker.refresh_available()
|
||||
else:
|
||||
for name in self.allowed_names:
|
||||
if not self.components.exists(name):
|
||||
# Pre-create a placeholder pill so it is visible even before data arrives.
|
||||
self.add_status_item(
|
||||
name=name, text=name, state=StatusState.DEFAULT, tooltip=None
|
||||
)
|
||||
self.broker.watch_state(name)
|
||||
|
||||
def _apply_status_toolbar_style(self) -> None:
|
||||
self.setStyleSheet(
|
||||
"QToolBar#StatusToolbar {"
|
||||
f" background-color: {self.background_color};"
|
||||
" border: none;"
|
||||
" border-bottom: 1px solid palette(mid);"
|
||||
"}"
|
||||
)
|
||||
|
||||
# -------- Slots for updates --------
|
||||
@SafeSlot(list)
|
||||
def on_available_updated(self, available_states: list):
|
||||
"""Process the available states stream and start watching them."""
|
||||
# Keep track of current names from the broker to remove stale ones.
|
||||
current_names: set[str] = set()
|
||||
for state in available_states:
|
||||
if not isinstance(state, BeamlineStateConfig):
|
||||
continue
|
||||
name = state.name
|
||||
title = state.title or name
|
||||
if not name:
|
||||
continue
|
||||
current_names.add(name)
|
||||
logger.info(f"StatusToolbar: discovered state '{name}' title='{title}'")
|
||||
# auto-add unless filtered out
|
||||
if self.allowed_names is None or name in self.allowed_names:
|
||||
self.add_status_item(name=name, text=title, state=StatusState.DEFAULT, tooltip=None)
|
||||
else:
|
||||
# keep hidden but present for context menu toggling
|
||||
self.add_status_item(name=name, text=title, state=StatusState.DEFAULT, tooltip=None)
|
||||
act = self.components.get_action(name)
|
||||
if act and act.action:
|
||||
act.action.setVisible(False)
|
||||
|
||||
# Remove actions that are no longer present in available_states.
|
||||
known_actions = [
|
||||
n for n in self.components._components.keys() if n not in ("separator",)
|
||||
] # direct access used for clean-up
|
||||
for name in known_actions:
|
||||
if name not in current_names:
|
||||
logger.info(f"StatusToolbar: removing stale state '{name}'")
|
||||
try:
|
||||
self.components.remove_action(name)
|
||||
except Exception as exc:
|
||||
logger.warning(f"Failed to remove stale state '{name}': {exc}")
|
||||
self.refresh()
|
||||
|
||||
@SafeSlot(str, dict)
|
||||
def on_status_updated(self, name: str, payload: dict): # TODO finish update logic
|
||||
"""Update a status pill when a state update arrives."""
|
||||
state = self.STATUS_MAP.get(str(payload.get("status", "")).lower(), StatusState.DEFAULT)
|
||||
action = self.components.get_action(name) if self.components.exists(name) else None
|
||||
|
||||
# Only update the label when a title is explicitly provided; otherwise keep current text.
|
||||
title = payload.get("title") or None
|
||||
text = title
|
||||
if text is None and action is None:
|
||||
text = payload.get("name") or name
|
||||
|
||||
if "label" in payload:
|
||||
tooltip = payload.get("label") or ""
|
||||
else:
|
||||
tooltip = None
|
||||
logger.info(
|
||||
f"StatusToolbar: update state '{name}' -> state={state} text='{text}' tooltip='{tooltip}'"
|
||||
)
|
||||
self.set_status(name=name, text=text, state=state, tooltip=tooltip)
|
||||
|
||||
# -------- Items Management --------
|
||||
def add_status_item(
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
text: str = "Ready",
|
||||
state: StatusState | str = StatusState.DEFAULT,
|
||||
tooltip: str | None = None,
|
||||
) -> StatusIndicatorAction | None:
|
||||
"""
|
||||
Add or update a named status item in the toolbar.
|
||||
After you added all actions, call `toolbar.refresh()` to update the display.
|
||||
|
||||
Args:
|
||||
name(str): Unique name for the status item.
|
||||
text(str): Text to display in the status item.
|
||||
state(StatusState | str): State of the status item.
|
||||
tooltip(str | None): Optional tooltip for the status item.
|
||||
|
||||
Returns:
|
||||
StatusIndicatorAction | None: The created or updated status action, or None if toolbar is not initialized.
|
||||
"""
|
||||
if self._status_bundle is None:
|
||||
return
|
||||
if self.components.exists(name):
|
||||
return
|
||||
|
||||
action = StatusIndicatorAction(text=text, state=state, tooltip=tooltip)
|
||||
return self.add_status_action(name, action)
|
||||
|
||||
def add_status_action(
|
||||
self, name: str, action: StatusIndicatorAction
|
||||
) -> StatusIndicatorAction | None:
|
||||
"""
|
||||
Attach an existing StatusIndicatorAction to the status toolbar.
|
||||
After you added all actions, call `toolbar.refresh()` to update the display.
|
||||
|
||||
Args:
|
||||
name(str): Unique name for the status item.
|
||||
action(StatusIndicatorAction): The status action to add.
|
||||
|
||||
Returns:
|
||||
StatusIndicatorAction | None: The added status action, or None if toolbar is not initialized.
|
||||
"""
|
||||
self.components.add_safe(name, action)
|
||||
self.get_bundle("status").add_action(name)
|
||||
self.refresh()
|
||||
self.broker.fetch_state(name)
|
||||
return action
|
||||
|
||||
def set_status(
|
||||
self,
|
||||
name: str = "main",
|
||||
*,
|
||||
state: StatusState | str | None = None,
|
||||
text: str | None = None,
|
||||
tooltip: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Update the status item with the given name, creating it if necessary.
|
||||
|
||||
Args:
|
||||
name(str): Unique name for the status item.
|
||||
state(StatusState | str | None): New state for the status item.
|
||||
text(str | None): New text for the status item.
|
||||
"""
|
||||
action = self.components.get_action(name) if self.components.exists(name) else None
|
||||
if action is None:
|
||||
action = self.add_status_item(
|
||||
name, text=text or "Ready", state=state or "default", tooltip=tooltip
|
||||
)
|
||||
if action is None:
|
||||
return
|
||||
if state is not None:
|
||||
action.set_state(state)
|
||||
if text is not None:
|
||||
action.set_text(text)
|
||||
if tooltip is not None and hasattr(action, "set_tooltip"):
|
||||
action.set_tooltip(tooltip)
|
||||
@@ -291,8 +291,7 @@ class ModularToolBar(QToolBar):
|
||||
menu = QMenu(self)
|
||||
theme = get_theme_name()
|
||||
if theme == "dark":
|
||||
menu.setStyleSheet(
|
||||
"""
|
||||
menu.setStyleSheet("""
|
||||
QMenu {
|
||||
background-color: rgba(50, 50, 50, 0.9);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
@@ -300,12 +299,10 @@ class ModularToolBar(QToolBar):
|
||||
QMenu::item:selected {
|
||||
background-color: rgba(0, 0, 255, 0.2);
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
else:
|
||||
# Light theme styling
|
||||
menu.setStyleSheet(
|
||||
"""
|
||||
menu.setStyleSheet("""
|
||||
QMenu {
|
||||
background-color: rgba(255, 255, 255, 0.9);
|
||||
border: 1px solid rgba(0, 0, 0, 0.2);
|
||||
@@ -313,8 +310,7 @@ class ModularToolBar(QToolBar):
|
||||
QMenu::item:selected {
|
||||
background-color: rgba(0, 0, 255, 0.2);
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
for ii, bundle in enumerate(self.shown_bundles):
|
||||
self.handle_bundle_context_menu(menu, bundle)
|
||||
if ii < len(self.shown_bundles) - 1:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import shiboken6
|
||||
from qtpy.QtCore import QPropertyAnimation, QRect, QSequentialAnimationGroup, Qt
|
||||
from qtpy.QtWidgets import QFrame, QWidget
|
||||
|
||||
|
||||
class WidgetHighlighter:
|
||||
"""
|
||||
Utility that highlights widgets by drawing a temporary frame around them.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
frame_parent: QWidget | None = None,
|
||||
window_flags: Qt.WindowType | Qt.WindowFlags = Qt.WindowType.Tool
|
||||
| Qt.WindowType.FramelessWindowHint
|
||||
| Qt.WindowType.WindowStaysOnTopHint,
|
||||
style_sheet: str = "border: 2px solid #FF00FF; border-radius: 6px; background: transparent;",
|
||||
) -> None:
|
||||
self._frame_parent = frame_parent
|
||||
self._window_flags = window_flags
|
||||
self._style_sheet = style_sheet
|
||||
self._frame: QFrame | None = None
|
||||
self._animation_group: QSequentialAnimationGroup | None = None
|
||||
|
||||
def highlight(self, widget: QWidget | None) -> None:
|
||||
"""
|
||||
Highlight the given widget with a pulsing frame.
|
||||
"""
|
||||
if widget is None or not shiboken6.isValid(widget):
|
||||
return
|
||||
|
||||
frame = self._ensure_frame()
|
||||
frame.hide()
|
||||
|
||||
geom = widget.frameGeometry()
|
||||
top_left = widget.mapToGlobal(widget.rect().topLeft())
|
||||
frame.setGeometry(top_left.x(), top_left.y(), geom.width(), geom.height())
|
||||
frame.setWindowOpacity(1.0)
|
||||
frame.show()
|
||||
|
||||
start_rect = QRect(
|
||||
top_left.x() - 5, top_left.y() - 5, geom.width() + 10, geom.height() + 10
|
||||
)
|
||||
|
||||
pulse = QPropertyAnimation(frame, b"geometry", frame)
|
||||
pulse.setDuration(300)
|
||||
pulse.setStartValue(start_rect)
|
||||
pulse.setEndValue(QRect(top_left.x(), top_left.y(), geom.width(), geom.height()))
|
||||
|
||||
fade = QPropertyAnimation(frame, b"windowOpacity", frame)
|
||||
fade.setDuration(2000)
|
||||
fade.setStartValue(1.0)
|
||||
fade.setEndValue(0.0)
|
||||
fade.finished.connect(frame.hide)
|
||||
|
||||
if self._animation_group is not None:
|
||||
old_group = self._animation_group
|
||||
self._animation_group = None
|
||||
old_group.stop()
|
||||
old_group.deleteLater()
|
||||
|
||||
animation = QSequentialAnimationGroup(frame)
|
||||
animation.addAnimation(pulse)
|
||||
animation.addAnimation(fade)
|
||||
animation.start()
|
||||
|
||||
self._animation_group = animation
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""
|
||||
Delete the highlight frame and cancel pending animations.
|
||||
"""
|
||||
if self._animation_group is not None:
|
||||
self._animation_group.stop()
|
||||
self._animation_group.deleteLater()
|
||||
self._animation_group = None
|
||||
if self._frame is not None:
|
||||
self._frame.hide()
|
||||
self._frame.deleteLater()
|
||||
self._frame = None
|
||||
|
||||
@property
|
||||
def frame(self) -> QFrame | None:
|
||||
"""Return the currently allocated highlight frame (if any)."""
|
||||
return self._frame
|
||||
|
||||
def _ensure_frame(self) -> QFrame:
|
||||
if self._frame is None:
|
||||
self._frame = QFrame(self._frame_parent, self._window_flags)
|
||||
self._frame.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
|
||||
self._frame.setStyleSheet(self._style_sheet)
|
||||
return self._frame
|
||||
+111
-49
@@ -2,10 +2,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Type, TypeVar, cast
|
||||
|
||||
import shiboken6 as shb
|
||||
from bec_lib import bec_logger
|
||||
from qtpy.QtCore import Qt
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QCheckBox,
|
||||
@@ -31,6 +33,14 @@ logger = bec_logger.logger
|
||||
TAncestor = TypeVar("TAncestor", bound=QWidget)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WidgetTreeNode:
|
||||
widget: QWidget
|
||||
parent: QWidget | None
|
||||
depth: int
|
||||
prefix: str
|
||||
|
||||
|
||||
class WidgetHandler(ABC):
|
||||
"""Abstract base class for all widget handlers."""
|
||||
|
||||
@@ -320,6 +330,72 @@ class WidgetIO:
|
||||
|
||||
|
||||
class WidgetHierarchy:
|
||||
@staticmethod
|
||||
def iter_widget_tree(widget: QWidget, *, exclude_internal_widgets: bool = True):
|
||||
"""
|
||||
Yield WidgetTreeNode entries for the widget hierarchy.
|
||||
"""
|
||||
visited: set[int] = set()
|
||||
yield from WidgetHierarchy._iter_widget_tree_nodes(
|
||||
widget, None, exclude_internal_widgets, visited, [], 0
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _iter_widget_tree_nodes(
|
||||
widget: QWidget,
|
||||
parent: QWidget | None,
|
||||
exclude_internal_widgets: bool,
|
||||
visited: set[int],
|
||||
branch_flags: list[bool],
|
||||
depth: int,
|
||||
):
|
||||
if widget is None or not shb.isValid(widget):
|
||||
return
|
||||
widget_id = id(widget)
|
||||
if widget_id in visited:
|
||||
return
|
||||
visited.add(widget_id)
|
||||
|
||||
prefix = WidgetHierarchy._build_prefix(branch_flags)
|
||||
yield WidgetTreeNode(widget=widget, parent=parent, depth=depth, prefix=prefix)
|
||||
|
||||
children = WidgetHierarchy._filtered_children(widget, exclude_internal_widgets)
|
||||
for idx, child in enumerate(children):
|
||||
is_last = idx == len(children) - 1
|
||||
yield from WidgetHierarchy._iter_widget_tree_nodes(
|
||||
child,
|
||||
widget,
|
||||
exclude_internal_widgets,
|
||||
visited,
|
||||
branch_flags + [is_last],
|
||||
depth + 1,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _build_prefix(branch_flags: list[bool]) -> str:
|
||||
if not branch_flags:
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for flag in branch_flags[:-1]:
|
||||
parts.append(" " if flag else "│ ")
|
||||
parts.append("└─ " if branch_flags[-1] else "├─ ")
|
||||
return "".join(parts)
|
||||
|
||||
@staticmethod
|
||||
def _filtered_children(widget: QWidget, exclude_internal_widgets: bool) -> list[QWidget]:
|
||||
children: list[QWidget] = []
|
||||
for child in widget.findChildren(QWidget, options=Qt.FindDirectChildrenOnly):
|
||||
if not shb.isValid(child):
|
||||
continue
|
||||
if (
|
||||
exclude_internal_widgets
|
||||
and isinstance(widget, QComboBox)
|
||||
and child.__class__.__name__ in ["QFrame", "QBoxLayout", "QListView"]
|
||||
):
|
||||
continue
|
||||
children.append(child)
|
||||
return children
|
||||
|
||||
@staticmethod
|
||||
def print_widget_hierarchy(
|
||||
widget,
|
||||
@@ -345,52 +421,33 @@ class WidgetHierarchy:
|
||||
from bec_widgets.utils import BECConnector
|
||||
from bec_widgets.widgets.plots.waveform.waveform import Waveform
|
||||
|
||||
# 1) Filter out widgets that are not BECConnectors (if 'only_bec_widgets' is True)
|
||||
is_bec = isinstance(widget, BECConnector)
|
||||
if only_bec_widgets and not is_bec:
|
||||
return
|
||||
|
||||
# 2) Determine and print the parent's info (closest BECConnector)
|
||||
parent_info = ""
|
||||
if show_parent and is_bec:
|
||||
ancestor = WidgetHierarchy._get_becwidget_ancestor(widget)
|
||||
if ancestor:
|
||||
parent_label = ancestor.objectName() or ancestor.__class__.__name__
|
||||
parent_info = f" parent={parent_label}"
|
||||
else:
|
||||
parent_info = " parent=None"
|
||||
|
||||
widget_info = f"{widget.__class__.__name__} ({widget.objectName()}){parent_info}"
|
||||
print(prefix + widget_info)
|
||||
|
||||
# 3) If it's a Waveform, explicitly print the curves
|
||||
if isinstance(widget, Waveform):
|
||||
for curve in widget.curves:
|
||||
curve_prefix = prefix + " └─ "
|
||||
print(
|
||||
f"{curve_prefix}{curve.__class__.__name__} ({curve.objectName()}) "
|
||||
f"parent={widget.objectName()}"
|
||||
)
|
||||
|
||||
# 4) Recursively handle each child if:
|
||||
# - It's a QWidget
|
||||
# - It is a BECConnector (or we don't care about filtering)
|
||||
# - Its closest BECConnector parent is the current widget
|
||||
for child in widget.findChildren(QWidget):
|
||||
if only_bec_widgets and not isinstance(child, BECConnector):
|
||||
for node in WidgetHierarchy.iter_widget_tree(
|
||||
widget, exclude_internal_widgets=exclude_internal_widgets
|
||||
):
|
||||
current = node.widget
|
||||
is_bec = isinstance(current, BECConnector)
|
||||
if only_bec_widgets and not is_bec:
|
||||
continue
|
||||
|
||||
# if WidgetHierarchy._get_becwidget_ancestor(child) == widget:
|
||||
child_prefix = prefix + " └─ "
|
||||
WidgetHierarchy.print_widget_hierarchy(
|
||||
child,
|
||||
indent=indent + 1,
|
||||
grab_values=grab_values,
|
||||
prefix=child_prefix,
|
||||
exclude_internal_widgets=exclude_internal_widgets,
|
||||
only_bec_widgets=only_bec_widgets,
|
||||
show_parent=show_parent,
|
||||
)
|
||||
parent_info = ""
|
||||
if show_parent and is_bec:
|
||||
ancestor = WidgetHierarchy.get_becwidget_ancestor(current)
|
||||
if ancestor:
|
||||
parent_label = ancestor.objectName() or ancestor.__class__.__name__
|
||||
parent_info = f" parent={parent_label}"
|
||||
else:
|
||||
parent_info = " parent=None"
|
||||
|
||||
widget_info = f"{current.__class__.__name__} ({current.objectName()}){parent_info}"
|
||||
print(node.prefix + widget_info)
|
||||
|
||||
if isinstance(current, Waveform):
|
||||
for curve in current.curves:
|
||||
curve_prefix = node.prefix + " "
|
||||
print(
|
||||
f"{curve_prefix}└─ {curve.__class__.__name__} ({curve.objectName()}) "
|
||||
f"parent={current.objectName()}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def print_becconnector_hierarchy_from_app():
|
||||
@@ -430,7 +487,7 @@ class WidgetHierarchy:
|
||||
# 3) Build a map of (closest BECConnector parent) -> list of children
|
||||
parent_map = defaultdict(list)
|
||||
for w in bec_widgets:
|
||||
parent_bec = WidgetHierarchy._get_becwidget_ancestor(w)
|
||||
parent_bec = WidgetHierarchy.get_becwidget_ancestor(w)
|
||||
parent_map[parent_bec].append(w)
|
||||
|
||||
# 4) Define a recursive printer to show each object's children
|
||||
@@ -467,10 +524,15 @@ class WidgetHierarchy:
|
||||
print_tree(root, prefix=" ")
|
||||
|
||||
@staticmethod
|
||||
def _get_becwidget_ancestor(widget):
|
||||
def get_becwidget_ancestor(widget):
|
||||
"""
|
||||
Traverse up the parent chain to find the nearest BECConnector.
|
||||
Returns None if none is found.
|
||||
|
||||
Args:
|
||||
widget: Starting widget to find the ancestor for.
|
||||
|
||||
Returns:
|
||||
The nearest ancestor that is a BECConnector, or None if not found.
|
||||
"""
|
||||
from bec_widgets.utils import BECConnector
|
||||
|
||||
@@ -580,7 +642,7 @@ class WidgetHierarchy:
|
||||
if isinstance(widget, BECConnector):
|
||||
connectors.append(widget)
|
||||
for child in widget.findChildren(BECConnector):
|
||||
if WidgetHierarchy._get_becwidget_ancestor(child) is widget:
|
||||
if WidgetHierarchy.get_becwidget_ancestor(child) is widget:
|
||||
connectors.append(child)
|
||||
return connectors
|
||||
|
||||
@@ -611,7 +673,7 @@ class WidgetHierarchy:
|
||||
is_bec_target = issubclass(ancestor_class, BECConnector)
|
||||
|
||||
if is_bec_target:
|
||||
ancestor = WidgetHierarchy._get_becwidget_ancestor(widget)
|
||||
ancestor = WidgetHierarchy.get_becwidget_ancestor(widget)
|
||||
return cast(TAncestor, ancestor)
|
||||
except Exception as e:
|
||||
logger.error(f"Error importing BECConnector: {e}")
|
||||
|
||||
@@ -41,12 +41,12 @@ class AutoUpdates(BECMainWindow):
|
||||
parent=self,
|
||||
object_name="dock_area",
|
||||
enable_profile_management=False,
|
||||
restore_initial_profile=False,
|
||||
startup_profile="skip",
|
||||
)
|
||||
self.setCentralWidget(self.dock_area)
|
||||
self._auto_update_selected_device: str | None = None
|
||||
|
||||
self._default_dock = None # type:ignore
|
||||
self._default_dock = None # type: ignore
|
||||
self.current_widget: BECWidget | None = None
|
||||
self.dock_name = None
|
||||
self._enabled = True
|
||||
@@ -63,7 +63,7 @@ class AutoUpdates(BECMainWindow):
|
||||
Disconnect all connections for the auto updates.
|
||||
"""
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self._on_scan_status, MessageEndpoints.scan_status() # type:ignore
|
||||
self._on_scan_status, MessageEndpoints.scan_status() # type: ignore
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -244,10 +244,10 @@ class AutoUpdates(BECMainWindow):
|
||||
wf = self.set_dock_to_widget("Waveform")
|
||||
|
||||
# Get the scan report devices reported by the scan
|
||||
dev_x = info.scan_report_devices[0] # type:ignore
|
||||
dev_x = info.scan_report_devices[0] # type: ignore
|
||||
|
||||
# For the y axis, get the selected device
|
||||
dev_y = self.get_selected_device(info.readout_priority["monitored"]) # type:ignore
|
||||
dev_y = self.get_selected_device(info.readout_priority["monitored"]) # type: ignore
|
||||
if not dev_y:
|
||||
return
|
||||
|
||||
@@ -256,8 +256,8 @@ class AutoUpdates(BECMainWindow):
|
||||
# as the label and title
|
||||
wf.clear_all()
|
||||
wf.plot(
|
||||
x_name=dev_x,
|
||||
y_name=dev_y,
|
||||
device_x=dev_x,
|
||||
device_y=dev_y,
|
||||
label=f"Scan {info.scan_number} - {dev_y}",
|
||||
title=f"Scan {info.scan_number}",
|
||||
x_label=dev_x,
|
||||
@@ -265,7 +265,7 @@ class AutoUpdates(BECMainWindow):
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Auto Update [simple_line_scan]: Started plot with: x_name={dev_x}, y_name={dev_y}"
|
||||
f"Auto Update [simple_line_scan]: Started plot with: device_x={dev_x}, device_y={dev_y}"
|
||||
)
|
||||
|
||||
def simple_grid_scan(self, info: ScanStatusMessage) -> None:
|
||||
@@ -279,8 +279,8 @@ class AutoUpdates(BECMainWindow):
|
||||
scatter = self.set_dock_to_widget("ScatterWaveform")
|
||||
|
||||
# Get the scan report devices reported by the scan
|
||||
dev_x, dev_y = info.scan_report_devices[0], info.scan_report_devices[1] # type:ignore
|
||||
dev_z = self.get_selected_device(info.readout_priority["monitored"]) # type:ignore
|
||||
dev_x, dev_y = info.scan_report_devices[0], info.scan_report_devices[1] # type: ignore
|
||||
dev_z = self.get_selected_device(info.readout_priority["monitored"]) # type: ignore
|
||||
|
||||
if None in (dev_x, dev_y, dev_z):
|
||||
return
|
||||
@@ -288,11 +288,14 @@ class AutoUpdates(BECMainWindow):
|
||||
# Clear the scatter waveform widget and plot the data
|
||||
scatter.clear_all()
|
||||
scatter.plot(
|
||||
x_name=dev_x, y_name=dev_y, z_name=dev_z, label=f"Scan {info.scan_number} - {dev_z}"
|
||||
device_x=dev_x,
|
||||
device_y=dev_y,
|
||||
device_z=dev_z,
|
||||
label=f"Scan {info.scan_number} - {dev_z}",
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Auto Update [simple_grid_scan]: Started plot with: x_name={dev_x}, y_name={dev_y}, z_name={dev_z}"
|
||||
f"Auto Update [simple_grid_scan]: Started plot with: device_x={dev_x}, device_y={dev_y}, device_z={dev_z}"
|
||||
)
|
||||
|
||||
def best_effort(self, info: ScanStatusMessage) -> None:
|
||||
@@ -306,8 +309,8 @@ class AutoUpdates(BECMainWindow):
|
||||
# If the scan report devices are empty, there is nothing we can do
|
||||
if not info.scan_report_devices:
|
||||
return
|
||||
dev_x = info.scan_report_devices[0] # type:ignore
|
||||
dev_y = self.get_selected_device(info.readout_priority["monitored"]) # type:ignore
|
||||
dev_x = info.scan_report_devices[0] # type: ignore
|
||||
dev_y = self.get_selected_device(info.readout_priority["monitored"]) # type: ignore
|
||||
if not dev_y:
|
||||
return
|
||||
|
||||
@@ -317,15 +320,17 @@ class AutoUpdates(BECMainWindow):
|
||||
# Clear the waveform widget and plot the data
|
||||
wf.clear_all()
|
||||
wf.plot(
|
||||
x_name=dev_x,
|
||||
y_name=dev_y,
|
||||
device_x=dev_x,
|
||||
device_y=dev_y,
|
||||
label=f"Scan {info.scan_number} - {dev_y}",
|
||||
title=f"Scan {info.scan_number}",
|
||||
x_label=dev_x,
|
||||
y_label=dev_y,
|
||||
)
|
||||
|
||||
logger.info(f"Auto Update [best_effort]: Started plot with: x_name={dev_x}, y_name={dev_y}")
|
||||
logger.info(
|
||||
f"Auto Update [best_effort]: Started plot with: device_x={dev_x}, device_y={dev_y}"
|
||||
)
|
||||
|
||||
#######################################################################
|
||||
################# GUI Callbacks #######################################
|
||||
|
||||
@@ -14,6 +14,7 @@ from shiboken6 import isValid
|
||||
import bec_widgets.widgets.containers.qt_ads as QtAds
|
||||
from bec_widgets import BECWidget, SafeSlot
|
||||
from bec_widgets.cli.rpc.rpc_widget_handler import widget_handler
|
||||
from bec_widgets.utils.bec_connector import BECConnector
|
||||
from bec_widgets.utils.property_editor import PropertyEditor
|
||||
from bec_widgets.utils.toolbars.actions import MaterialIconAction
|
||||
from bec_widgets.widgets.containers.qt_ads import (
|
||||
@@ -112,6 +113,7 @@ class DockAreaWidget(BECWidget, QWidget):
|
||||
)
|
||||
|
||||
self._root_layout.addWidget(self.dock_manager, 1)
|
||||
self._install_manager_parent_guards()
|
||||
|
||||
################################################################################
|
||||
# Dock Utility Helpers
|
||||
@@ -254,6 +256,54 @@ class DockAreaWidget(BECWidget, QWidget):
|
||||
|
||||
return lambda dock: self._default_close_handler(dock, widget)
|
||||
|
||||
def _install_manager_parent_guards(self) -> None:
|
||||
"""
|
||||
Track ADS structural changes so drag/drop-created tab areas keep stable parenting.
|
||||
"""
|
||||
self.dock_manager.dockAreaCreated.connect(self._normalize_all_dock_parents)
|
||||
self.dock_manager.dockWidgetAdded.connect(self._normalize_all_dock_parents)
|
||||
self.dock_manager.stateRestored.connect(self._normalize_all_dock_parents)
|
||||
self.dock_manager.restoringState.connect(self._normalize_all_dock_parents)
|
||||
self.dock_manager.focusedDockWidgetChanged.connect(self._normalize_all_dock_parents)
|
||||
self._normalize_all_dock_parents()
|
||||
|
||||
def _iter_all_dock_areas(self) -> list[CDockAreaWidget]:
|
||||
"""Return all dock areas from all known dock containers."""
|
||||
areas: list[CDockAreaWidget] = []
|
||||
for i in range(self.dock_manager.dockAreaCount()):
|
||||
area = self.dock_manager.dockArea(i)
|
||||
if area is None or not isValid(area):
|
||||
continue
|
||||
areas.append(area)
|
||||
return areas
|
||||
|
||||
def _connect_dock_area_parent_guards(self) -> None:
|
||||
"""Bind area-level tab/view events to parent normalization."""
|
||||
for area in self._iter_all_dock_areas():
|
||||
try:
|
||||
area.currentChanged.connect(
|
||||
self._normalize_all_dock_parents, Qt.ConnectionType.UniqueConnection
|
||||
)
|
||||
area.viewToggled.connect(
|
||||
self._normalize_all_dock_parents, Qt.ConnectionType.UniqueConnection
|
||||
)
|
||||
except TypeError:
|
||||
area.currentChanged.connect(self._normalize_all_dock_parents)
|
||||
area.viewToggled.connect(self._normalize_all_dock_parents)
|
||||
|
||||
def _normalize_all_dock_parents(self, *_args) -> None:
|
||||
"""
|
||||
Ensure each dock has a stable parent after tab switches, re-docking, or restore.
|
||||
"""
|
||||
self._connect_dock_area_parent_guards()
|
||||
for dock in self.dock_list():
|
||||
if dock is None or not isValid(dock):
|
||||
continue
|
||||
area_widget = dock.dockAreaWidget()
|
||||
target_parent = area_widget if area_widget is not None else self.dock_manager
|
||||
if dock.parent() is not target_parent:
|
||||
dock.setParent(target_parent)
|
||||
|
||||
def _make_dock(
|
||||
self,
|
||||
widget: QWidget,
|
||||
@@ -356,6 +406,7 @@ class DockAreaWidget(BECWidget, QWidget):
|
||||
self._apply_floating_state_to_dock(dock, floating_state)
|
||||
if resolved_icon is not None:
|
||||
dock.setIcon(resolved_icon)
|
||||
self._normalize_all_dock_parents()
|
||||
return dock
|
||||
|
||||
def _delete_dock(self, dock: CDockWidget) -> None:
|
||||
@@ -1264,7 +1315,7 @@ class DockAreaWidget(BECWidget, QWidget):
|
||||
or a sequence of button names to hide.
|
||||
show_settings_action(bool | None): Control whether a dock settings/property action should
|
||||
be installed. Defaults to ``False`` for the basic dock area; subclasses
|
||||
such as `AdvancedDockArea` override the default to ``True``.
|
||||
such as `BECDockArea` override the default to ``True``.
|
||||
promote_central(bool): When True, promote the created dock to be the dock manager's
|
||||
central widget (useful for editor stacks or other root content).
|
||||
dock_icon(QIcon | None): Optional icon applied to the dock via ``CDockWidget.setIcon``.
|
||||
@@ -1334,37 +1385,40 @@ class DockAreaWidget(BECWidget, QWidget):
|
||||
dock = self._create_dock_from_spec(spec)
|
||||
return dock if return_dock else widget
|
||||
|
||||
def _iter_all_docks(self) -> list[CDockWidget]:
|
||||
"""Return all docks, including those hosted in floating containers."""
|
||||
docks = list(self.dock_manager.dockWidgets())
|
||||
seen = {id(d) for d in docks}
|
||||
for container in self.dock_manager.floatingWidgets():
|
||||
if container is None:
|
||||
continue
|
||||
for dock in container.dockWidgets():
|
||||
if dock is None:
|
||||
continue
|
||||
if id(dock) in seen:
|
||||
continue
|
||||
docks.append(dock)
|
||||
seen.add(id(dock))
|
||||
return docks
|
||||
|
||||
def dock_map(self) -> dict[str, CDockWidget]:
|
||||
"""Return the dock widgets map as dictionary with names as keys."""
|
||||
return {dock.objectName(): dock for dock in self._iter_all_docks() if dock.objectName()}
|
||||
return self.dock_manager.dockWidgetsMap()
|
||||
|
||||
def dock_list(self) -> list[CDockWidget]:
|
||||
"""Return the list of dock widgets."""
|
||||
return self._iter_all_docks()
|
||||
return list(self.dock_map().values())
|
||||
|
||||
def widget_map(self) -> dict[str, QWidget]:
|
||||
"""Return a dictionary mapping widget names to their corresponding widgets."""
|
||||
return {dock.objectName(): dock.widget() for dock in self.dock_list()}
|
||||
def widget_map(self, bec_widgets_only: bool = True) -> dict[str, QWidget]:
|
||||
"""
|
||||
Return a dictionary mapping widget names to their corresponding widgets.
|
||||
|
||||
def widget_list(self) -> list[QWidget]:
|
||||
"""Return a list of all widgets contained in the dock area."""
|
||||
return [dock.widget() for dock in self.dock_list() if isinstance(dock.widget(), QWidget)]
|
||||
Args:
|
||||
bec_widgets_only(bool): If True, only include widgets that are BECConnector instances.
|
||||
"""
|
||||
|
||||
widgets: dict[str, QWidget] = {}
|
||||
for dock in self.dock_list():
|
||||
widget = dock.widget()
|
||||
if not isinstance(widget, QWidget):
|
||||
continue
|
||||
if bec_widgets_only and not isinstance(widget, BECConnector):
|
||||
continue
|
||||
widgets[dock.objectName()] = widget
|
||||
return widgets
|
||||
|
||||
def widget_list(self, bec_widgets_only: bool = True) -> list[QWidget]:
|
||||
"""
|
||||
Return a list of widgets contained in the dock area.
|
||||
|
||||
Args:
|
||||
bec_widgets_only(bool): If True, only include widgets that are BECConnector instances.
|
||||
"""
|
||||
return list(self.widget_map(bec_widgets_only=bec_widgets_only).values())
|
||||
|
||||
@SafeSlot()
|
||||
def attach_all(self):
|
||||
|
||||
@@ -19,6 +19,7 @@ from qtpy.QtWidgets import (
|
||||
|
||||
import bec_widgets.widgets.containers.qt_ads as QtAds
|
||||
from bec_widgets import BECWidget, SafeProperty, SafeSlot
|
||||
from bec_widgets.applications.views.view import ViewTourSteps
|
||||
from bec_widgets.cli.rpc.rpc_widget_handler import widget_handler
|
||||
from bec_widgets.utils import BECDispatcher
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
@@ -68,7 +69,7 @@ from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow
|
||||
from bec_widgets.widgets.containers.qt_ads import CDockWidget
|
||||
from bec_widgets.widgets.control.device_control.positioner_box import PositionerBox, PositionerBox2D
|
||||
from bec_widgets.widgets.control.scan_control import ScanControl
|
||||
from bec_widgets.widgets.editors.web_console.web_console import BECShell, WebConsole
|
||||
from bec_widgets.widgets.editors.bec_console.bec_console import BecConsole, BECShell
|
||||
from bec_widgets.widgets.plots.heatmap.heatmap import Heatmap
|
||||
from bec_widgets.widgets.plots.image.image import Image
|
||||
from bec_widgets.widgets.plots.motor_map.motor_map import MotorMap
|
||||
@@ -78,7 +79,7 @@ from bec_widgets.widgets.plots.waveform.waveform import Waveform
|
||||
from bec_widgets.widgets.progress.ring_progress_bar.ring_progress_bar import RingProgressBar
|
||||
from bec_widgets.widgets.services.bec_queue.bec_queue import BECQueue
|
||||
from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECStatusBox
|
||||
from bec_widgets.widgets.utility.logpanel import LogPanel
|
||||
from bec_widgets.widgets.utility.logpanel.logpanel import LogPanel
|
||||
from bec_widgets.widgets.utility.visual.dark_mode_button.dark_mode_button import DarkModeButton
|
||||
|
||||
logger = bec_logger.logger
|
||||
@@ -86,6 +87,7 @@ logger = bec_logger.logger
|
||||
_PROFILE_NAMESPACE_UNSET = object()
|
||||
|
||||
PROFILE_STATE_KEYS = {key: SETTINGS_KEYS[key] for key in ("geom", "state", "ads_state")}
|
||||
StartupProfile = Literal["restore", "skip"] | str | None
|
||||
|
||||
|
||||
class BECDockArea(DockAreaWidget):
|
||||
@@ -123,9 +125,7 @@ class BECDockArea(DockAreaWidget):
|
||||
instance_id: str | None = None,
|
||||
auto_save_upon_exit: bool = True,
|
||||
enable_profile_management: bool = True,
|
||||
restore_initial_profile: bool = True,
|
||||
init_profile: str | None = None,
|
||||
start_empty: bool = False,
|
||||
startup_profile: StartupProfile = "restore",
|
||||
**kwargs,
|
||||
):
|
||||
self._profile_namespace_hint = profile_namespace
|
||||
@@ -134,14 +134,9 @@ class BECDockArea(DockAreaWidget):
|
||||
self._instance_id = slugify.slugify(instance_id, separator="_") if instance_id else None
|
||||
self._auto_save_upon_exit = auto_save_upon_exit
|
||||
self._profile_management_enabled = enable_profile_management
|
||||
self._restore_initial_profile = restore_initial_profile
|
||||
self._init_profile = init_profile
|
||||
self._start_empty = start_empty
|
||||
self._startup_profile = self._normalize_startup_profile(startup_profile)
|
||||
super().__init__(
|
||||
parent,
|
||||
default_add_direction=default_add_direction,
|
||||
title="Advanced Dock Area",
|
||||
**kwargs,
|
||||
parent, default_add_direction=default_add_direction, title="BEC Dock Area", **kwargs
|
||||
)
|
||||
|
||||
# Initialize mode property first (before toolbar setup)
|
||||
@@ -161,14 +156,16 @@ class BECDockArea(DockAreaWidget):
|
||||
self._root_layout.insertWidget(0, self.toolbar)
|
||||
|
||||
# Populate and hook the workspace combo
|
||||
self._refresh_workspace_list()
|
||||
self._current_profile_name = None
|
||||
self._empty_profile_active = False
|
||||
self._empty_profile_consumed = False
|
||||
self._pending_autosave_skip: tuple[str, str] | None = None
|
||||
self._exit_snapshot_written = False
|
||||
self._refresh_workspace_list()
|
||||
|
||||
# State manager
|
||||
self.state_manager = WidgetStateManager(
|
||||
self, serialize_from_root=True, root_id="AdvancedDockArea"
|
||||
self, serialize_from_root=True, root_id="BECDockArea"
|
||||
)
|
||||
|
||||
# Developer mode state
|
||||
@@ -176,84 +173,85 @@ class BECDockArea(DockAreaWidget):
|
||||
# Initialize default editable state based on current lock
|
||||
self._set_editable(True) # default to editable; will sync toolbar toggle below
|
||||
|
||||
if self._ensure_initial_profile():
|
||||
self._refresh_workspace_list()
|
||||
|
||||
# Apply the requested mode after everything is set up
|
||||
self.mode = mode
|
||||
if self._restore_initial_profile:
|
||||
self._fetch_initial_profile()
|
||||
self._fetch_initial_profile()
|
||||
|
||||
def _ensure_initial_profile(self) -> bool:
|
||||
@staticmethod
|
||||
def _normalize_startup_profile(startup_profile: StartupProfile) -> StartupProfile:
|
||||
"""
|
||||
Ensure the "general" workspace profile always exists for the current namespace.
|
||||
The "general" profile is mandatory and will be recreated if deleted.
|
||||
If list_profile fails due to file permission or corrupted profiles, no action taken.
|
||||
|
||||
Returns:
|
||||
bool: True if a profile was created, False otherwise.
|
||||
Normalize startup profile values.
|
||||
"""
|
||||
namespace = self.profile_namespace
|
||||
try:
|
||||
existing_profiles = list_profiles(namespace)
|
||||
except Exception as exc: # pragma: no cover - defensive guard
|
||||
logger.warning(f"Unable to enumerate profiles for namespace '{namespace}': {exc}")
|
||||
return False
|
||||
if startup_profile == "":
|
||||
return None
|
||||
return startup_profile
|
||||
|
||||
# Always ensure "general" profile exists
|
||||
name = "general"
|
||||
if name in existing_profiles:
|
||||
return False
|
||||
|
||||
logger.info(
|
||||
f"Profile '{name}' not found in namespace '{namespace}'. Creating mandatory '{name}' workspace."
|
||||
)
|
||||
|
||||
self._write_profile_settings(name, namespace, save_preview=False)
|
||||
set_quick_select(name, True, namespace=namespace)
|
||||
set_last_profile(name, namespace=namespace, instance=self._last_profile_instance_id())
|
||||
return True
|
||||
|
||||
def _fetch_initial_profile(self):
|
||||
# Restore last-used profile if available; otherwise fall back to combo selection
|
||||
def _resolve_restore_startup_profile(self) -> str | None:
|
||||
"""
|
||||
Resolve the profile name when startup profile is set to "restore".
|
||||
"""
|
||||
combo = self.toolbar.components.get_action("workspace_combo").widget
|
||||
namespace = self.profile_namespace
|
||||
init_profile = None
|
||||
|
||||
# First priority: use init_profile if explicitly provided
|
||||
if self._init_profile:
|
||||
init_profile = self._init_profile
|
||||
else:
|
||||
# Try to restore from last used profile
|
||||
instance_id = self._last_profile_instance_id()
|
||||
if instance_id:
|
||||
inst_profile = get_last_profile(
|
||||
namespace=namespace, instance=instance_id, allow_namespace_fallback=False
|
||||
)
|
||||
if inst_profile and self._profile_exists(inst_profile, namespace):
|
||||
init_profile = inst_profile
|
||||
if not init_profile:
|
||||
last = get_last_profile(namespace=namespace)
|
||||
if last and self._profile_exists(last, namespace):
|
||||
init_profile = last
|
||||
else:
|
||||
text = combo.currentText()
|
||||
init_profile = text if text else None
|
||||
if not init_profile:
|
||||
# Fall back to "general" profile which is guaranteed to exist
|
||||
if self._profile_exists("general", namespace):
|
||||
init_profile = "general"
|
||||
if init_profile:
|
||||
self._load_initial_profile(init_profile)
|
||||
instance_id = self._last_profile_instance_id()
|
||||
if instance_id:
|
||||
inst_profile = get_last_profile(
|
||||
namespace=namespace, instance=instance_id, allow_namespace_fallback=False
|
||||
)
|
||||
if inst_profile and self._profile_exists(inst_profile, namespace):
|
||||
return inst_profile
|
||||
|
||||
last = get_last_profile(namespace=namespace)
|
||||
if last and self._profile_exists(last, namespace):
|
||||
return last
|
||||
|
||||
combo_text = combo.currentText().strip()
|
||||
if combo_text and self._profile_exists(combo_text, namespace):
|
||||
return combo_text
|
||||
|
||||
return None
|
||||
|
||||
def _fetch_initial_profile(self):
|
||||
startup_profile = self._startup_profile
|
||||
|
||||
if startup_profile == "skip":
|
||||
logger.debug("Skipping startup profile initialization.")
|
||||
return
|
||||
|
||||
if startup_profile == "restore":
|
||||
restored = self._resolve_restore_startup_profile()
|
||||
if restored:
|
||||
self._load_initial_profile(restored)
|
||||
return
|
||||
self._start_empty_workspace()
|
||||
return
|
||||
|
||||
if startup_profile is None:
|
||||
self._start_empty_workspace()
|
||||
return
|
||||
|
||||
self._load_initial_profile(startup_profile)
|
||||
|
||||
def _load_initial_profile(self, name: str) -> None:
|
||||
"""Load the initial profile."""
|
||||
self.load_profile(name, start_empty=self._start_empty)
|
||||
self.load_profile(name)
|
||||
combo = self.toolbar.components.get_action("workspace_combo").widget
|
||||
combo.blockSignals(True)
|
||||
combo.setCurrentText(name)
|
||||
if not self._empty_profile_active:
|
||||
combo.setCurrentText(name)
|
||||
combo.blockSignals(False)
|
||||
|
||||
def _start_empty_workspace(self) -> None:
|
||||
"""
|
||||
Initialize the dock area in transient empty-profile mode.
|
||||
"""
|
||||
if (
|
||||
getattr(self, "_current_profile_name", None) is None
|
||||
and not self._empty_profile_consumed
|
||||
):
|
||||
self.delete_all()
|
||||
self._enter_empty_profile_state()
|
||||
|
||||
def _customize_dock(self, dock: CDockWidget, widget: QWidget) -> None:
|
||||
prefs = getattr(dock, "_dock_preferences", {}) or {}
|
||||
if prefs.get("show_settings_action") is None:
|
||||
@@ -303,7 +301,7 @@ class BECDockArea(DockAreaWidget):
|
||||
or a sequence of button names to hide.
|
||||
show_settings_action(bool | None): Control whether a dock settings/property action should
|
||||
be installed. Defaults to ``False`` for the basic dock area; subclasses
|
||||
such as `AdvancedDockArea` override the default to ``True``.
|
||||
such as `BECDockArea` override the default to ``True``.
|
||||
promote_central(bool): When True, promote the created dock to be the dock manager's
|
||||
central widget (useful for editor stacks or other root content).
|
||||
object_name(str | None): Optional object name to assign to the created widget.
|
||||
@@ -374,10 +372,11 @@ class BECDockArea(DockAreaWidget):
|
||||
"Add Circular ProgressBar",
|
||||
"RingProgressBar",
|
||||
),
|
||||
"terminal": (WebConsole.ICON_NAME, "Add Terminal", "WebConsole"),
|
||||
"terminal": (BecConsole.ICON_NAME, "Add Terminal", "BecConsole"),
|
||||
"bec_shell": (BECShell.ICON_NAME, "Add BEC Shell", "BECShell"),
|
||||
"log_panel": (LogPanel.ICON_NAME, "Add LogPanel - Disabled", "LogPanel"),
|
||||
"sbb_monitor": ("train", "Add SBB Monitor", "SBBMonitor"),
|
||||
"log_panel": (LogPanel.ICON_NAME, "Add LogPanel", "LogPanel"),
|
||||
}
|
||||
|
||||
# Create expandable menu actions (original behavior)
|
||||
@@ -489,9 +488,7 @@ class BECDockArea(DockAreaWidget):
|
||||
# first two items not needed for this part
|
||||
for key, (_, _, widget_type) in mapping.items():
|
||||
act = menu.actions[key].action
|
||||
if widget_type == "LogPanel":
|
||||
act.setEnabled(False) # keep disabled per issue #644
|
||||
elif key == "terminal":
|
||||
if key == "terminal":
|
||||
act.triggered.connect(
|
||||
lambda _, t=widget_type: self.new(widget=t, closable=True, startup_cmd=None)
|
||||
)
|
||||
@@ -512,10 +509,7 @@ class BECDockArea(DockAreaWidget):
|
||||
for action_id, (_, _, widget_type) in mapping.items():
|
||||
flat_action_id = f"flat_{action_id}"
|
||||
flat_action = self.toolbar.components.get_action(flat_action_id).action
|
||||
if widget_type == "LogPanel":
|
||||
flat_action.setEnabled(False) # keep disabled per issue #644
|
||||
else:
|
||||
flat_action.triggered.connect(lambda _, t=widget_type: self.new(t))
|
||||
flat_action.triggered.connect(lambda _, t=widget_type: self.new(t))
|
||||
|
||||
_connect_flat_actions(self._ACTION_MAPPINGS["menu_plots"])
|
||||
_connect_flat_actions(self._ACTION_MAPPINGS["menu_devices"])
|
||||
@@ -600,13 +594,6 @@ class BECDockArea(DockAreaWidget):
|
||||
"""Namespace used to scope user/default profile files for this dock area."""
|
||||
return self._resolve_profile_namespace()
|
||||
|
||||
def _active_profile_name_or_default(self) -> str:
|
||||
name = getattr(self, "_current_profile_name", None)
|
||||
if not name:
|
||||
name = "general"
|
||||
self._current_profile_name = name
|
||||
return name
|
||||
|
||||
def _profile_exists(self, name: str, namespace: str | None) -> bool:
|
||||
return any(
|
||||
os.path.exists(path) for path in user_profile_candidates(name, namespace)
|
||||
@@ -674,12 +661,26 @@ class BECDockArea(DockAreaWidget):
|
||||
name: The profile name.
|
||||
namespace: The profile namespace.
|
||||
"""
|
||||
self._empty_profile_active = False
|
||||
self._empty_profile_consumed = True
|
||||
self._current_profile_name = name
|
||||
self.profile_changed.emit(name)
|
||||
set_last_profile(name, namespace=namespace, instance=self._last_profile_instance_id())
|
||||
combo = self.toolbar.components.get_action("workspace_combo").widget
|
||||
combo.refresh_profiles(active_profile=name)
|
||||
|
||||
def _enter_empty_profile_state(self) -> None:
|
||||
"""
|
||||
Switch to the transient empty workspace state.
|
||||
|
||||
In this mode there is no active profile name, the toolbar shows an
|
||||
explicit blank profile entry, and no autosave on shutdown is performed.
|
||||
"""
|
||||
self._empty_profile_active = True
|
||||
self._current_profile_name = None
|
||||
self._pending_autosave_skip = None
|
||||
self._refresh_workspace_list()
|
||||
|
||||
@SafeSlot()
|
||||
def list_profiles(self) -> list[str]:
|
||||
"""
|
||||
@@ -813,10 +814,10 @@ class BECDockArea(DockAreaWidget):
|
||||
"""
|
||||
self.save_profile(name, show_dialog=True)
|
||||
|
||||
@SafeSlot()
|
||||
@SafeSlot(str)
|
||||
@SafeSlot(str, bool)
|
||||
@rpc_timeout(None)
|
||||
def load_profile(self, name: str | None = None, start_empty: bool = False):
|
||||
def load_profile(self, name: str | None = None):
|
||||
"""
|
||||
Load a workspace profile.
|
||||
|
||||
@@ -825,8 +826,10 @@ class BECDockArea(DockAreaWidget):
|
||||
|
||||
Args:
|
||||
name (str | None): The name of the profile to load. If None, prompts the user.
|
||||
start_empty (bool): If True, load a profile without any widgets. Danger of overwriting the dynamic state of that profile.
|
||||
"""
|
||||
if name == "":
|
||||
return
|
||||
|
||||
if not name: # Gui fallback if the name is not provided
|
||||
name, ok = QInputDialog.getText(
|
||||
self, "Load Workspace", "Enter the name of the workspace profile to load:"
|
||||
@@ -858,10 +861,6 @@ class BECDockArea(DockAreaWidget):
|
||||
# Clear existing docks and remove all widgets
|
||||
self.delete_all()
|
||||
|
||||
if start_empty:
|
||||
self._finalize_profile_change(name, namespace)
|
||||
return
|
||||
|
||||
# Rebuild widgets and restore states
|
||||
for item in read_manifest(settings):
|
||||
obj_name = item["object_name"]
|
||||
@@ -1007,25 +1006,36 @@ class BECDockArea(DockAreaWidget):
|
||||
"""
|
||||
combo = self.toolbar.components.get_action("workspace_combo").widget
|
||||
active_profile = getattr(self, "_current_profile_name", None)
|
||||
empty_profile_active = bool(getattr(self, "_empty_profile_active", False))
|
||||
namespace = self.profile_namespace
|
||||
if hasattr(combo, "set_quick_profile_provider"):
|
||||
combo.set_quick_profile_provider(lambda ns=namespace: list_quick_profiles(namespace=ns))
|
||||
if hasattr(combo, "refresh_profiles"):
|
||||
combo.refresh_profiles(active_profile)
|
||||
if empty_profile_active:
|
||||
combo.refresh_profiles(active_profile, show_empty_profile=True)
|
||||
else:
|
||||
combo.refresh_profiles(active_profile)
|
||||
else:
|
||||
# Fallback for regular QComboBox
|
||||
combo.blockSignals(True)
|
||||
combo.clear()
|
||||
quick_profiles = list_quick_profiles(namespace=namespace)
|
||||
items = list(quick_profiles)
|
||||
items = [""] if empty_profile_active else []
|
||||
items.extend(quick_profiles)
|
||||
if active_profile and active_profile not in items:
|
||||
items.insert(0, active_profile)
|
||||
combo.addItems(items)
|
||||
if active_profile:
|
||||
if empty_profile_active:
|
||||
idx = combo.findText("")
|
||||
if idx >= 0:
|
||||
combo.setCurrentIndex(idx)
|
||||
elif active_profile:
|
||||
idx = combo.findText(active_profile)
|
||||
if idx >= 0:
|
||||
combo.setCurrentIndex(idx)
|
||||
if active_profile and active_profile not in quick_profiles:
|
||||
if empty_profile_active:
|
||||
combo.setToolTip("Unsaved empty workspace")
|
||||
elif active_profile and active_profile not in quick_profiles:
|
||||
combo.setToolTip("Active profile is not in quick select")
|
||||
else:
|
||||
combo.setToolTip("")
|
||||
@@ -1130,7 +1140,16 @@ class BECDockArea(DockAreaWidget):
|
||||
logger.info("ADS prepare_for_shutdown: skipping (already handled or destroyed)")
|
||||
return
|
||||
|
||||
name = self._active_profile_name_or_default()
|
||||
if getattr(self, "_empty_profile_active", False):
|
||||
logger.info("ADS prepare_for_shutdown: skipping autosave for unsaved empty workspace")
|
||||
self._exit_snapshot_written = True
|
||||
return
|
||||
|
||||
name = getattr(self, "_current_profile_name", None)
|
||||
if not name:
|
||||
logger.info("ADS prepare_for_shutdown: skipping autosave (no active profile)")
|
||||
self._exit_snapshot_written = True
|
||||
return
|
||||
|
||||
namespace = self.profile_namespace
|
||||
settings = open_user_settings(name, namespace=namespace)
|
||||
@@ -1138,6 +1157,33 @@ class BECDockArea(DockAreaWidget):
|
||||
set_last_profile(name, namespace=namespace, instance=self._last_profile_instance_id())
|
||||
self._exit_snapshot_written = True
|
||||
|
||||
def register_tour_steps(self, guided_tour, main_app):
|
||||
"""Register Dock Area components with the guided tour.
|
||||
|
||||
Args:
|
||||
guided_tour: The GuidedTour instance to register with.
|
||||
main_app: The main application instance (for accessing set_current).
|
||||
|
||||
Returns:
|
||||
ViewTourSteps | None: Model containing view title and step IDs.
|
||||
"""
|
||||
|
||||
step_ids = []
|
||||
|
||||
# Register Dock Area toolbar
|
||||
def get_dock_toolbar():
|
||||
main_app.set_current("dock_area")
|
||||
return (self.toolbar, None)
|
||||
|
||||
step_id = guided_tour.register_widget(
|
||||
widget=get_dock_toolbar,
|
||||
title="Dock Area Toolbar",
|
||||
text="Use this toolbar to add widgets, manage workspaces, save and load profiles, and control the layout of your workspace.",
|
||||
)
|
||||
step_ids.append(step_id)
|
||||
|
||||
return ViewTourSteps(view_title="Dock Area Workspace", step_ids=step_ids)
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Cleanup the dock area.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Utilities for managing AdvancedDockArea profiles stored in INI files.
|
||||
Utilities for managing BECDockArea profiles stored in INI files.
|
||||
|
||||
Policy:
|
||||
- All created/modified profiles are stored under the BEC settings root: <base_path>/profiles/{default,user}
|
||||
@@ -36,12 +36,12 @@ ProfileOrigin = Literal["module", "plugin", "settings", "unknown"]
|
||||
|
||||
def module_profiles_dir() -> str:
|
||||
"""
|
||||
Return the built-in AdvancedDockArea profiles directory bundled with the module.
|
||||
Return the built-in BECDockArea profiles directory bundled with the module.
|
||||
|
||||
Returns:
|
||||
str: Absolute path of the read-only module profiles directory.
|
||||
"""
|
||||
return os.path.join(MODULE_PATH, "containers", "advanced_dock_area", "profiles")
|
||||
return os.path.join(MODULE_PATH, "containers", "dock_area", "profiles")
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
@@ -115,12 +115,12 @@ def _settings_profiles_root() -> str:
|
||||
str: Absolute path to the profiles root. The directory is created if missing.
|
||||
"""
|
||||
client = BECClient()
|
||||
bec_widgets_settings = client._service_config.config.get("bec_widgets_settings")
|
||||
bec_widgets_settings = client._service_config.config.get("widgets_settings")
|
||||
bec_widgets_setting_path = (
|
||||
bec_widgets_settings.get("base_path") if bec_widgets_settings else None
|
||||
)
|
||||
default_path = os.path.join(bec_widgets_setting_path, "profiles")
|
||||
root = os.environ.get("BECWIDGETS_PROFILE_DIR", default_path)
|
||||
root = os.path.expanduser(os.environ.get("BECWIDGETS_PROFILE_DIR", default_path))
|
||||
os.makedirs(root, exist_ok=True)
|
||||
return root
|
||||
|
||||
@@ -138,7 +138,7 @@ def _profiles_dir(segment: str, namespace: str | None) -> str:
|
||||
"""
|
||||
base = os.path.join(_settings_profiles_root(), segment)
|
||||
ns = slugify.slugify(namespace, separator="_") if namespace else None
|
||||
path = os.path.join(base, ns) if ns else base
|
||||
path = os.path.expanduser(os.path.join(base, ns) if ns else base)
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
@@ -330,7 +330,7 @@ class WorkSpaceManager(BECWidget, QWidget):
|
||||
return
|
||||
|
||||
self.target_widget.save_profile_dialog()
|
||||
# AdvancedDockArea will emit profile_changed which will trigger table refresh,
|
||||
# BECDockArea will emit profile_changed which will trigger table refresh,
|
||||
# but ensure the UI stays in sync even if the signal is delayed.
|
||||
self.render_table()
|
||||
current = getattr(self.target_widget, "_current_profile_name", None)
|
||||
|
||||
@@ -24,12 +24,15 @@ class ProfileComboBox(QComboBox):
|
||||
def set_quick_profile_provider(self, provider: Callable[[], list[str]]) -> None:
|
||||
self._quick_provider = provider
|
||||
|
||||
def refresh_profiles(self, active_profile: str | None = None):
|
||||
def refresh_profiles(
|
||||
self, active_profile: str | None = None, show_empty_profile: bool = False
|
||||
) -> None:
|
||||
"""
|
||||
Refresh the profile list and ensure the active profile is visible.
|
||||
|
||||
Args:
|
||||
active_profile(str | None): The currently active profile name.
|
||||
show_empty_profile(bool): If True, show an explicit empty unsaved workspace entry.
|
||||
"""
|
||||
|
||||
current_text = active_profile or self.currentText()
|
||||
@@ -39,9 +42,22 @@ class ProfileComboBox(QComboBox):
|
||||
quick_profiles = self._quick_provider()
|
||||
quick_set = set(quick_profiles)
|
||||
|
||||
items = list(quick_profiles)
|
||||
items: list[str] = []
|
||||
if show_empty_profile:
|
||||
items.append("")
|
||||
|
||||
if active_profile and active_profile not in quick_set:
|
||||
items.insert(0, active_profile)
|
||||
items.append(active_profile)
|
||||
|
||||
for profile in quick_profiles:
|
||||
if profile not in items:
|
||||
items.append(profile)
|
||||
|
||||
if active_profile and active_profile not in quick_set:
|
||||
# keep active profile at the top when not in quick list
|
||||
items.remove(active_profile)
|
||||
insert_pos = 1 if show_empty_profile else 0
|
||||
items.insert(insert_pos, active_profile)
|
||||
|
||||
for profile in items:
|
||||
self.addItem(profile)
|
||||
@@ -52,6 +68,15 @@ class ProfileComboBox(QComboBox):
|
||||
self.setItemData(idx, None, Qt.ItemDataRole.ToolTipRole)
|
||||
self.setItemData(idx, None, Qt.ItemDataRole.ForegroundRole)
|
||||
|
||||
if profile == "":
|
||||
self.setItemData(idx, "Unsaved empty workspace", Qt.ItemDataRole.ToolTipRole)
|
||||
if active_profile is None:
|
||||
font = QFont(self.font())
|
||||
font.setItalic(True)
|
||||
self.setItemData(idx, font, Qt.ItemDataRole.FontRole)
|
||||
self.setCurrentIndex(idx)
|
||||
continue
|
||||
|
||||
if active_profile and profile == active_profile:
|
||||
tooltip = "Active workspace profile"
|
||||
if profile not in quick_set:
|
||||
@@ -69,16 +94,23 @@ class ProfileComboBox(QComboBox):
|
||||
self.setItemData(idx, "Not in quick select", Qt.ItemDataRole.ToolTipRole)
|
||||
|
||||
# Restore selection if possible
|
||||
index = self.findText(current_text)
|
||||
if index >= 0:
|
||||
self.setCurrentIndex(index)
|
||||
if show_empty_profile and active_profile is None:
|
||||
empty_idx = self.findText("")
|
||||
if empty_idx >= 0:
|
||||
self.setCurrentIndex(empty_idx)
|
||||
else:
|
||||
index = self.findText(current_text)
|
||||
if index >= 0:
|
||||
self.setCurrentIndex(index)
|
||||
|
||||
self.blockSignals(False)
|
||||
if active_profile and self.currentText() != active_profile:
|
||||
idx = self.findText(active_profile)
|
||||
if idx >= 0:
|
||||
self.setCurrentIndex(idx)
|
||||
if active_profile and active_profile not in quick_set:
|
||||
if show_empty_profile and self.currentText() == "":
|
||||
self.setToolTip("Unsaved empty workspace")
|
||||
elif active_profile and active_profile not in quick_set:
|
||||
self.setToolTip("Active profile is not in quick select")
|
||||
else:
|
||||
self.setToolTip("")
|
||||
@@ -86,7 +118,7 @@ class ProfileComboBox(QComboBox):
|
||||
|
||||
def workspace_bundle(components: ToolbarComponents, enable_tools: bool = True) -> ToolbarBundle:
|
||||
"""
|
||||
Creates a workspace toolbar bundle for AdvancedDockArea.
|
||||
Creates a workspace toolbar bundle for BECDockArea.
|
||||
|
||||
Args:
|
||||
components (ToolbarComponents): The components to be added to the bundle.
|
||||
@@ -139,7 +171,7 @@ def workspace_bundle(components: ToolbarComponents, enable_tools: bool = True) -
|
||||
|
||||
class WorkspaceConnection(BundleConnection):
|
||||
"""
|
||||
Connection class for workspace actions in AdvancedDockArea.
|
||||
Connection class for workspace actions in BECDockArea.
|
||||
"""
|
||||
|
||||
def __init__(self, components: ToolbarComponents, target_widget=None):
|
||||
|
||||
@@ -101,14 +101,12 @@ class Explorer(BECWidget, QWidget):
|
||||
palette = get_theme_palette()
|
||||
separator_color = palette.mid().color()
|
||||
|
||||
self.splitter.setStyleSheet(
|
||||
f"""
|
||||
self.splitter.setStyleSheet(f"""
|
||||
QSplitter::handle {{
|
||||
height: 0.1px;
|
||||
background-color: rgba({separator_color.red()}, {separator_color.green()}, {separator_color.blue()}, 60);
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
def _update_spacer(self) -> None:
|
||||
"""Update the spacer size based on section states"""
|
||||
|
||||
@@ -63,7 +63,7 @@ class ScriptTreeWidget(QWidget):
|
||||
layout.setSpacing(0)
|
||||
|
||||
# Create tree view
|
||||
self.tree = QTreeView()
|
||||
self.tree = QTreeView(parent=self)
|
||||
self.tree.setHeaderHidden(True)
|
||||
self.tree.setRootIsDecorated(True)
|
||||
|
||||
@@ -71,12 +71,12 @@ class ScriptTreeWidget(QWidget):
|
||||
self.tree.setMouseTracking(True)
|
||||
|
||||
# Create file system model
|
||||
self.model = QFileSystemModel()
|
||||
self.model = QFileSystemModel(parent=self)
|
||||
self.model.setNameFilters(["*.py"])
|
||||
self.model.setNameFilterDisables(False)
|
||||
|
||||
# Create proxy model to filter out underscore directories
|
||||
self.proxy_model = QSortFilterProxyModel()
|
||||
self.proxy_model = QSortFilterProxyModel(parent=self)
|
||||
self.proxy_model.setFilterRegularExpression(QRegularExpression("^[^_].*"))
|
||||
self.proxy_model.setSourceModel(self.model)
|
||||
self.tree.setModel(self.proxy_model)
|
||||
|
||||
@@ -1,27 +1,83 @@
|
||||
import sys
|
||||
|
||||
from qtpy import QtGui, QtWidgets
|
||||
from qtpy.QtCore import QPoint, Qt
|
||||
from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QProgressBar, QVBoxLayout, QWidget
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QProgressBar,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
|
||||
class WidgetTooltip(QWidget):
|
||||
"""Frameless, always-on-top window that behaves like a tooltip."""
|
||||
|
||||
def __init__(self, content: QWidget) -> None:
|
||||
super().__init__(None, Qt.ToolTip | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
|
||||
self.setAttribute(Qt.WA_ShowWithoutActivating)
|
||||
super().__init__(
|
||||
None,
|
||||
Qt.WindowType.ToolTip
|
||||
| Qt.WindowType.FramelessWindowHint
|
||||
| Qt.WindowType.WindowStaysOnTopHint,
|
||||
)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.setMouseTracking(True)
|
||||
self.content = content
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(6, 6, 6, 6)
|
||||
layout.addWidget(self.content)
|
||||
layout.setContentsMargins(14, 14, 14, 14)
|
||||
|
||||
self._card = QFrame(self)
|
||||
self._card.setObjectName("WidgetTooltipCard")
|
||||
card_layout = QVBoxLayout(self._card)
|
||||
card_layout.setContentsMargins(12, 10, 12, 10)
|
||||
card_layout.addWidget(self.content)
|
||||
|
||||
shadow = QtWidgets.QGraphicsDropShadowEffect(self._card)
|
||||
shadow.setBlurRadius(18)
|
||||
shadow.setOffset(0, 2)
|
||||
shadow.setColor(QtGui.QColor(0, 0, 0, 140))
|
||||
self._card.setGraphicsEffect(shadow)
|
||||
|
||||
layout.addWidget(self._card)
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
|
||||
def leaveEvent(self, _event) -> None:
|
||||
self.hide()
|
||||
|
||||
def apply_theme(self) -> None:
|
||||
palette = QApplication.palette()
|
||||
base = palette.color(QtGui.QPalette.ColorRole.Base)
|
||||
text = palette.color(QtGui.QPalette.ColorRole.Text)
|
||||
border = palette.color(QtGui.QPalette.ColorRole.Mid)
|
||||
background = QtGui.QColor(base)
|
||||
background.setAlpha(242)
|
||||
self._card.setStyleSheet(f"""
|
||||
QFrame#WidgetTooltipCard {{
|
||||
background: {background.name(QtGui.QColor.NameFormat.HexArgb)};
|
||||
border: 1px solid {border.name()};
|
||||
border-radius: 12px;
|
||||
}}
|
||||
QFrame#WidgetTooltipCard QLabel {{
|
||||
color: {text.name()};
|
||||
background: transparent;
|
||||
}}
|
||||
""")
|
||||
|
||||
def show_above(self, global_pos: QPoint, offset: int = 8) -> None:
|
||||
"""
|
||||
Show the tooltip above a global position, adjusting to stay within screen bounds.
|
||||
|
||||
Args:
|
||||
global_pos(QPoint): The global position to show above.
|
||||
offset(int, optional): The vertical offset from the global position. Defaults to 8 pixels.
|
||||
"""
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
screen = QApplication.screenAt(global_pos) or QApplication.primaryScreen()
|
||||
screen_geo = screen.availableGeometry()
|
||||
@@ -30,11 +86,43 @@ class WidgetTooltip(QWidget):
|
||||
x = global_pos.x() - geom.width() // 2
|
||||
y = global_pos.y() - geom.height() - offset
|
||||
|
||||
self._navigate_screen_coordinates(screen_geo, geom, x, y)
|
||||
|
||||
def show_near(self, global_pos: QPoint, offset: QPoint | None = None) -> None:
|
||||
"""
|
||||
Show the tooltip near a global position, adjusting to stay within screen bounds.
|
||||
By default, it will try to show below and to the right of the position,
|
||||
but if that would cause it to go off-screen, it will flip to the other side.
|
||||
|
||||
Args:
|
||||
global_pos(QPoint): The global position to show near.
|
||||
offset(QPoint, optional): The offset from the global position. Defaults to QPoint(12, 16).
|
||||
"""
|
||||
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
offset = offset or QPoint(12, 16)
|
||||
screen = QApplication.screenAt(global_pos) or QApplication.primaryScreen()
|
||||
screen_geo = screen.availableGeometry()
|
||||
geom = self.geometry()
|
||||
|
||||
x = global_pos.x() + offset.x()
|
||||
y = global_pos.y() + offset.y()
|
||||
|
||||
if x + geom.width() > screen_geo.right():
|
||||
x = global_pos.x() - geom.width() - abs(offset.x())
|
||||
if y + geom.height() > screen_geo.bottom():
|
||||
y = global_pos.y() - geom.height() - abs(offset.y())
|
||||
|
||||
self._navigate_screen_coordinates(screen_geo, geom, x, y)
|
||||
|
||||
def _navigate_screen_coordinates(self, screen_geo, geom, x, y):
|
||||
x = max(screen_geo.left(), min(x, screen_geo.right() - geom.width()))
|
||||
y = max(screen_geo.top(), min(y, screen_geo.bottom() - geom.height()))
|
||||
|
||||
self.move(x, y)
|
||||
self.show()
|
||||
self.raise_()
|
||||
|
||||
|
||||
class HoverWidget(QWidget):
|
||||
|
||||
+14
-28
@@ -134,15 +134,13 @@ class NotificationToast(QFrame):
|
||||
bg.setAlphaF(0.30)
|
||||
icon_bg = bg.name(QtGui.QColor.HexArgb)
|
||||
icon_btn.setFixedSize(40, 40)
|
||||
icon_btn.setStyleSheet(
|
||||
f"""
|
||||
icon_btn.setStyleSheet(f"""
|
||||
QToolButton {{
|
||||
background: {icon_bg};
|
||||
border: none;
|
||||
border-radius: 20px; /* perfect circle */
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
title_lbl = QtWidgets.QLabel(self._title)
|
||||
|
||||
@@ -327,15 +325,13 @@ class NotificationToast(QFrame):
|
||||
bg = QtGui.QColor(SEVERITY[value.value]["color"])
|
||||
bg.setAlphaF(0.30)
|
||||
icon_bg = bg.name(QtGui.QColor.HexArgb)
|
||||
self._icon_btn.setStyleSheet(
|
||||
f"""
|
||||
self._icon_btn.setStyleSheet(f"""
|
||||
QToolButton {{
|
||||
background: {icon_bg};
|
||||
border: none;
|
||||
border-radius: 20px;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
self.apply_theme(self._theme)
|
||||
# keep injected gradient in sync
|
||||
if getattr(self, "_hg_enabled", False):
|
||||
@@ -391,8 +387,7 @@ class NotificationToast(QFrame):
|
||||
card_bg.setAlphaF(0.88)
|
||||
btn_hover = self._accent_color.name()
|
||||
|
||||
self.setStyleSheet(
|
||||
f"""
|
||||
self.setStyleSheet(f"""
|
||||
#NotificationToast {{
|
||||
background: {card_bg.name(QtGui.QColor.HexArgb)};
|
||||
border-radius: 12px;
|
||||
@@ -406,18 +401,15 @@ class NotificationToast(QFrame):
|
||||
font-size: 14px;
|
||||
}}
|
||||
#NotificationToast QPushButton:hover {{ color: {btn_hover}; }}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
# traceback panel colours
|
||||
trace_bg = "#1e1e1e" if theme == "dark" else "#f0f0f0"
|
||||
self.trace_view.setStyleSheet(
|
||||
f"""
|
||||
self.trace_view.setStyleSheet(f"""
|
||||
background:{trace_bg};
|
||||
color:{palette['body']};
|
||||
border:none;
|
||||
border-radius:8px;
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
# icon glyph vs badge background: darker badge, lighter icon in light mode
|
||||
icon_fg = "#ffffff" if theme == "light" else self._accent_color.name()
|
||||
@@ -438,15 +430,13 @@ class NotificationToast(QFrame):
|
||||
else:
|
||||
badge_bg.setAlphaF(0.30)
|
||||
icon_bg = badge_bg.name(QtGui.QColor.HexArgb)
|
||||
self._icon_btn.setStyleSheet(
|
||||
f"""
|
||||
self._icon_btn.setStyleSheet(f"""
|
||||
QToolButton {{
|
||||
background: {icon_bg};
|
||||
border: none;
|
||||
border-radius: 20px;
|
||||
}}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
# stronger accent wash in light mode, slightly stronger in dark too
|
||||
self._accent_alpha = 110 if theme == "light" else 60
|
||||
@@ -593,8 +583,7 @@ class NotificationCentre(QScrollArea):
|
||||
self.setWidgetResizable(True)
|
||||
# transparent background so only the toast cards are visible
|
||||
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
|
||||
self.setStyleSheet(
|
||||
"""
|
||||
self.setStyleSheet("""
|
||||
#NotificationCentre { background: transparent; }
|
||||
#NotificationCentre QScrollBar:vertical {
|
||||
background: transparent;
|
||||
@@ -610,8 +599,7 @@ class NotificationCentre(QScrollArea):
|
||||
#NotificationCentre QScrollBar::sub-line:vertical { height: 0; }
|
||||
#NotificationCentre QScrollBar::add-page:vertical,
|
||||
#NotificationCentre QScrollBar::sub-page:vertical { background: transparent; }
|
||||
"""
|
||||
)
|
||||
""")
|
||||
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
|
||||
self.setFrameShape(QtWidgets.QFrame.NoFrame)
|
||||
self.setFixedWidth(fixed_width)
|
||||
@@ -958,8 +946,7 @@ class NotificationIndicator(QWidget):
|
||||
self._group.buttonToggled.connect(self._button_toggled)
|
||||
|
||||
# minimalistic look: no frames or backgrounds on the buttons
|
||||
self.setStyleSheet(
|
||||
"""
|
||||
self.setStyleSheet("""
|
||||
QToolButton {
|
||||
border: none;
|
||||
background: transparent;
|
||||
@@ -970,8 +957,7 @@ class NotificationIndicator(QWidget):
|
||||
background: rgba(255, 255, 255, 40);
|
||||
font-weight: 600;
|
||||
}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
# initial state: none checked (auto‑dismiss behaviour)
|
||||
for k in kinds:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from bec_lib import bec_logger
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from qtpy.QtCore import QEvent, QSize, Qt, QTimer
|
||||
from qtpy.QtGui import QAction, QActionGroup, QIcon
|
||||
@@ -21,7 +22,6 @@ from bec_widgets.utils import UILoader
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.toolbars.status_bar import StatusToolBar
|
||||
from bec_widgets.widgets.containers.main_window.addons.hover_widget import HoverWidget
|
||||
from bec_widgets.widgets.containers.main_window.addons.notification_center.notification_banner import (
|
||||
BECNotificationBroker,
|
||||
@@ -31,12 +31,17 @@ from bec_widgets.widgets.containers.main_window.addons.notification_center.notif
|
||||
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
|
||||
from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin
|
||||
from bec_widgets.widgets.progress.scan_progressbar.scan_progressbar import ScanProgressBar
|
||||
from bec_widgets.widgets.utility.widget_hierarchy_tree.widget_hierarchy_tree import (
|
||||
WidgetHierarchyDialog,
|
||||
)
|
||||
|
||||
MODULE_PATH = os.path.dirname(bec_widgets.__file__)
|
||||
|
||||
# Ensure the application does not use the native menu bar on macOS to be consistent with linux development.
|
||||
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar, True)
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class BECMainWindow(BECWidget, QMainWindow):
|
||||
RPC = True
|
||||
@@ -49,6 +54,7 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
|
||||
self.app = QApplication.instance()
|
||||
self.status_bar = self.statusBar()
|
||||
self._launcher_window = None
|
||||
self.setWindowTitle(window_title)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
||||
|
||||
@@ -57,6 +63,7 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
self.notification_broker = BECNotificationBroker(parent=self)
|
||||
self._nc_margin = 16
|
||||
self._position_notification_centre()
|
||||
self._widget_hierarchy_dialog: WidgetHierarchyDialog | None = None
|
||||
|
||||
# Init ui
|
||||
self._init_ui()
|
||||
@@ -115,11 +122,14 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
Prepare the BEC specific widgets in the status bar.
|
||||
"""
|
||||
|
||||
# Left: Beamline condition status toolbar (auto-fetches all conditions)
|
||||
self._status_toolbar = StatusToolBar(parent=self, names=None)
|
||||
self.status_bar.addWidget(self._status_toolbar)
|
||||
# Left: App‑ID label
|
||||
self._app_id_label = QLabel()
|
||||
self._app_id_label.setAlignment(
|
||||
Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
self.status_bar.addWidget(self._app_id_label)
|
||||
|
||||
# Add a separator after the status toolbar
|
||||
# Add a separator after the app ID label
|
||||
self._add_separator()
|
||||
|
||||
# Centre: Client‑info label (stretch=1 so it expands)
|
||||
@@ -186,14 +196,18 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
def _add_scan_progress_bar(self):
|
||||
|
||||
# Setting HoverWidget for the scan progress bar - minimal and full version
|
||||
self._scan_progress_bar_simple = ScanProgressBar(self, one_line_design=True)
|
||||
self._scan_progress_bar_simple = ScanProgressBar(
|
||||
self, one_line_design=True, rpc_exposed=False, rpc_passthrough_children=False
|
||||
)
|
||||
self._scan_progress_bar_simple.show_elapsed_time = False
|
||||
self._scan_progress_bar_simple.show_remaining_time = False
|
||||
self._scan_progress_bar_simple.show_source_label = False
|
||||
self._scan_progress_bar_simple.progressbar.label_template = ""
|
||||
self._scan_progress_bar_simple.progressbar.setFixedHeight(self.SCAN_PROGRESS_HEIGHT)
|
||||
self._scan_progress_bar_simple.progressbar.setFixedWidth(self.SCAN_PROGRESS_WIDTH)
|
||||
self._scan_progress_bar_full = ScanProgressBar(self)
|
||||
self._scan_progress_bar_full = ScanProgressBar(
|
||||
self, rpc_exposed=False, rpc_passthrough_children=False
|
||||
)
|
||||
self._scan_progress_hover = HoverWidget(
|
||||
self, simple=self._scan_progress_bar_simple, full=self._scan_progress_bar_full
|
||||
)
|
||||
@@ -251,7 +265,7 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
self.ui = loader.loader(ui_file)
|
||||
self.setCentralWidget(self.ui)
|
||||
|
||||
def _fetch_theme(self) -> str:
|
||||
def fetch_theme(self) -> str:
|
||||
return self.app.theme.theme
|
||||
|
||||
def _get_launcher_from_qapp(self):
|
||||
@@ -272,6 +286,16 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
Show the launcher if it exists.
|
||||
"""
|
||||
launcher = self._get_launcher_from_qapp()
|
||||
if launcher is None:
|
||||
from bec_widgets.applications.launch_window import LaunchWindow
|
||||
|
||||
cli_server = getattr(self.bec_dispatcher, "cli_server", None)
|
||||
if cli_server is None:
|
||||
logger.warning("Cannot open launcher: CLI server is not available.")
|
||||
return
|
||||
launcher = LaunchWindow(gui_id=f"{cli_server.gui_id}:launcher")
|
||||
launcher.setAttribute(Qt.WA_ShowWithoutActivating) # type: ignore[arg-type]
|
||||
self._launcher_window = launcher
|
||||
if launcher:
|
||||
launcher.show()
|
||||
launcher.activateWindow()
|
||||
@@ -309,6 +333,11 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
light_theme_action.triggered.connect(lambda: self.change_theme("light"))
|
||||
dark_theme_action.triggered.connect(lambda: self.change_theme("dark"))
|
||||
|
||||
theme_menu.addSeparator()
|
||||
widget_tree_action = QAction("Show Widget Hierarchy", self)
|
||||
widget_tree_action.triggered.connect(self._show_widget_hierarchy_dialog)
|
||||
theme_menu.addAction(widget_tree_action)
|
||||
|
||||
# Set the default theme
|
||||
if hasattr(self.app, "theme") and self.app.theme:
|
||||
theme_name = self.app.theme.theme.lower()
|
||||
@@ -338,27 +367,13 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
help_menu.addAction(bec_docs)
|
||||
help_menu.addAction(widgets_docs)
|
||||
help_menu.addAction(bug_report)
|
||||
help_menu.addSeparator()
|
||||
self._app_id_action = QAction(self)
|
||||
self._app_id_action.triggered.connect(self._copy_app_id_to_clipboard)
|
||||
|
||||
help_menu.addAction(self._app_id_action)
|
||||
|
||||
def _copy_app_id_to_clipboard(self):
|
||||
"""
|
||||
Copy the app ID to the clipboard.
|
||||
"""
|
||||
if self.bec_dispatcher.cli_server is not None:
|
||||
server_id = self.bec_dispatcher.cli_server.gui_id
|
||||
clipboard = QApplication.clipboard()
|
||||
clipboard.setText(server_id)
|
||||
|
||||
################################################################################
|
||||
# Status Bar Addons
|
||||
################################################################################
|
||||
def display_app_id(self):
|
||||
"""
|
||||
Display the app ID in the Help menu.
|
||||
Display the app ID in the status bar.
|
||||
"""
|
||||
if self.bec_dispatcher.cli_server is None:
|
||||
status_message = "Not connected"
|
||||
@@ -366,8 +381,7 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
# Get the server ID from the dispatcher
|
||||
server_id = self.bec_dispatcher.cli_server.gui_id
|
||||
status_message = f"App ID: {server_id}"
|
||||
if hasattr(self, "_app_id_action"):
|
||||
self._app_id_action.setText(status_message)
|
||||
self._app_id_label.setText(status_message)
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def display_client_message(self, msg: dict, meta: dict):
|
||||
@@ -407,7 +421,23 @@ class BECMainWindow(BECWidget, QMainWindow):
|
||||
return True
|
||||
return super().event(event)
|
||||
|
||||
def _show_widget_hierarchy_dialog(self):
|
||||
if self._widget_hierarchy_dialog is None:
|
||||
dialog = WidgetHierarchyDialog(root_widget=None, parent=self)
|
||||
dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
||||
dialog.destroyed.connect(lambda: setattr(self, "_widget_hierarchy_dialog", None))
|
||||
self._widget_hierarchy_dialog = dialog
|
||||
self._widget_hierarchy_dialog.refresh()
|
||||
self._widget_hierarchy_dialog.show()
|
||||
self._widget_hierarchy_dialog.raise_()
|
||||
self._widget_hierarchy_dialog.activateWindow()
|
||||
|
||||
def cleanup(self):
|
||||
# Widget hierarchy dialog cleanup
|
||||
if self._widget_hierarchy_dialog is not None:
|
||||
self._widget_hierarchy_dialog.close()
|
||||
self._widget_hierarchy_dialog = None
|
||||
|
||||
# Timer cleanup
|
||||
if hasattr(self, "_client_info_expire_timer") and self._client_info_expire_timer.isActive():
|
||||
self._client_info_expire_timer.stop()
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from .positioner_box_base import PositionerBoxBase
|
||||
|
||||
__ALL__ = ["PositionerBoxBase"]
|
||||
+6
-8
@@ -14,9 +14,9 @@ from qtpy.QtWidgets import QDoubleSpinBox
|
||||
from bec_widgets.utils import UILoader
|
||||
from bec_widgets.utils.colors import apply_theme, get_accent_colors
|
||||
from bec_widgets.utils.error_popups import SafeProperty, SafeSlot
|
||||
from bec_widgets.widgets.control.device_control.positioner_box._base import PositionerBoxBase
|
||||
from bec_widgets.widgets.control.device_control.positioner_box._base.positioner_box_base import (
|
||||
from bec_widgets.widgets.control.device_control.positioner_box.positioner_box_base import (
|
||||
DeviceUpdateUIComponents,
|
||||
PositionerBoxBase,
|
||||
)
|
||||
|
||||
logger = bec_logger.logger
|
||||
@@ -63,10 +63,10 @@ class PositionerBox(PositionerBoxBase):
|
||||
|
||||
self.ui = UILoader(self).loader(os.path.join(self.current_path, self.ui_file))
|
||||
|
||||
self.addWidget(self.ui)
|
||||
self.layout.setSpacing(0)
|
||||
self.layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.layout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
|
||||
self.main_layout.addWidget(self.ui)
|
||||
self.main_layout.setSpacing(0)
|
||||
self.main_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.main_layout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
|
||||
ui_min_size = self.ui.minimumSize()
|
||||
ui_min_hint = self.ui.minimumSizeHint()
|
||||
self.setMinimumSize(
|
||||
@@ -115,8 +115,6 @@ class PositionerBox(PositionerBoxBase):
|
||||
return
|
||||
old_device = self._device
|
||||
self._device = value
|
||||
if not self.label:
|
||||
self.label = value
|
||||
self.device_changed.emit(old_device, value)
|
||||
|
||||
@SafeProperty(bool)
|
||||
|
||||
+5
-7
@@ -15,9 +15,9 @@ from qtpy.QtWidgets import QDoubleSpinBox
|
||||
from bec_widgets.utils import UILoader
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
from bec_widgets.utils.error_popups import SafeProperty, SafeSlot
|
||||
from bec_widgets.widgets.control.device_control.positioner_box._base import PositionerBoxBase
|
||||
from bec_widgets.widgets.control.device_control.positioner_box._base.positioner_box_base import (
|
||||
from bec_widgets.widgets.control.device_control.positioner_box.positioner_box_base import (
|
||||
DeviceUpdateUIComponents,
|
||||
PositionerBoxBase,
|
||||
)
|
||||
|
||||
logger = bec_logger.logger
|
||||
@@ -96,9 +96,9 @@ class PositionerBox2D(PositionerBoxBase):
|
||||
|
||||
def connect_ui(self):
|
||||
"""Connect the UI components to signals, data, or routines"""
|
||||
self.addWidget(self.ui)
|
||||
self.layout.setSpacing(0)
|
||||
self.layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.main_layout.addWidget(self.ui)
|
||||
self.main_layout.setSpacing(0)
|
||||
self.main_layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
def _init_ui(val: QDoubleValidator, device_id: DeviceId):
|
||||
ui = self._device_ui_components_hv(device_id)
|
||||
@@ -200,7 +200,6 @@ class PositionerBox2D(PositionerBoxBase):
|
||||
return
|
||||
old_device = self._device_hor
|
||||
self._device_hor = value
|
||||
self.label = f"{self._device_hor}, {self._device_ver}"
|
||||
self.device_changed_hor.emit(old_device, value)
|
||||
self._init_device(self.device_hor, self.position_update_hor.emit, self.update_limits_hor)
|
||||
|
||||
@@ -220,7 +219,6 @@ class PositionerBox2D(PositionerBoxBase):
|
||||
return
|
||||
old_device = self._device_ver
|
||||
self._device_ver = value
|
||||
self.label = f"{self._device_hor}, {self._device_ver}"
|
||||
self.device_changed_ver.emit(old_device, value)
|
||||
self._init_device(self.device_ver, self.position_update_ver.emit, self.update_limits_ver)
|
||||
|
||||
|
||||
+12
-11
@@ -14,10 +14,10 @@ from qtpy.QtWidgets import (
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.compact_popup import CompactPopupWidget
|
||||
from bec_widgets.widgets.control.device_control.position_indicator.position_indicator import (
|
||||
PositionIndicator,
|
||||
)
|
||||
@@ -43,7 +43,7 @@ class DeviceUpdateUIComponents(TypedDict):
|
||||
units: QLabel
|
||||
|
||||
|
||||
class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
class PositionerBoxBase(BECWidget, QWidget):
|
||||
"""Contains some core logic for positioner box widgets"""
|
||||
|
||||
current_path = ""
|
||||
@@ -57,7 +57,10 @@ class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
parent: The parent widget.
|
||||
device (Positioner): The device to control.
|
||||
"""
|
||||
super().__init__(parent=parent, layout=QVBoxLayout, **kwargs)
|
||||
super().__init__(parent=parent, **kwargs)
|
||||
self.main_layout = QVBoxLayout(self)
|
||||
self.main_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.main_layout.setSpacing(0)
|
||||
self._dialog = None
|
||||
self.get_bec_shortcuts()
|
||||
|
||||
@@ -123,7 +126,7 @@ class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
queue="emergency",
|
||||
metadata={"RID": request_id, "response": False},
|
||||
)
|
||||
self.client.connector.send(MessageEndpoints.scan_queue_request(), msg)
|
||||
self.client.connector.send(MessageEndpoints.scan_queue_request(self.client.username), msg)
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def _on_device_readback(
|
||||
@@ -173,11 +176,9 @@ class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
if is_moving:
|
||||
spinner.start()
|
||||
spinner.setToolTip("Device is moving")
|
||||
self.set_global_state("warning")
|
||||
else:
|
||||
spinner.stop()
|
||||
spinner.setToolTip("Device is idle")
|
||||
self.set_global_state("success")
|
||||
else:
|
||||
spinner.setVisible(False)
|
||||
|
||||
@@ -196,9 +197,8 @@ class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
pos = (readback_val - limits[0]) / (limits[1] - limits[0])
|
||||
position_indicator.set_value(pos)
|
||||
|
||||
def _update_limits_ui(
|
||||
self, limits: tuple[float, float], position_indicator, setpoint_validator
|
||||
):
|
||||
@staticmethod
|
||||
def _update_limits_ui(limits: tuple[float, float], position_indicator, setpoint_validator):
|
||||
if limits is not None and limits[0] != limits[1]:
|
||||
position_indicator.setToolTip(f"Min: {limits[0]}, Max: {limits[1]}")
|
||||
setpoint_validator.setRange(limits[0], limits[1])
|
||||
@@ -223,8 +223,9 @@ class PositionerBoxBase(BECWidget, CompactPopupWidget):
|
||||
self.bec_dispatcher.disconnect_slot(slot, MessageEndpoints.device_readback(old_device))
|
||||
self.bec_dispatcher.connect_slot(slot, MessageEndpoints.device_readback(new_device))
|
||||
|
||||
def _toggle_enable_buttons(self, ui: DeviceUpdateUIComponents, enable: bool) -> None:
|
||||
"""Toogle enable/disable on available buttons
|
||||
@staticmethod
|
||||
def _toggle_enable_buttons(ui: DeviceUpdateUIComponents, enable: bool) -> None:
|
||||
"""Toggle enable/disable on available buttons
|
||||
|
||||
Args:
|
||||
enable (bool): Enable buttons
|
||||
+77
@@ -1,6 +1,8 @@
|
||||
import os
|
||||
|
||||
from bec_lib.device import Positioner
|
||||
from qtpy.QtCore import Qt
|
||||
from qtpy.QtWidgets import QSizePolicy
|
||||
|
||||
from bec_widgets.widgets.control.device_control.positioner_box import PositionerBox
|
||||
|
||||
@@ -22,7 +24,82 @@ class PositionerControlLine(PositionerBox):
|
||||
device (Positioner): The device to control.
|
||||
"""
|
||||
self.current_path = os.path.dirname(__file__)
|
||||
self._indicator_switch_width = 0
|
||||
self._horizontal_indicator_width = 0
|
||||
self._vertical_indicator_width = 15
|
||||
self._indicator_thickness = 10
|
||||
self._indicator_is_horizontal = False
|
||||
self._line_height = self.dimensions[0]
|
||||
super().__init__(parent=parent, device=device, *args, **kwargs)
|
||||
self._configure_line_layout()
|
||||
self._update_indicator_orientation()
|
||||
|
||||
def _configure_line_layout(self):
|
||||
device_box = self.ui.device_box
|
||||
indicator = self.ui.position_indicator
|
||||
|
||||
self.main_layout.setAlignment(Qt.AlignmentFlag(0))
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.ui.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
device_box.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
|
||||
self._line_height = max(
|
||||
self.dimensions[0],
|
||||
self.ui.minimumSizeHint().height(),
|
||||
self.ui.sizeHint().height(),
|
||||
device_box.minimumSizeHint().height(),
|
||||
device_box.sizeHint().height(),
|
||||
)
|
||||
device_box.setFixedHeight(self._line_height)
|
||||
device_box.setMinimumWidth(self.dimensions[1])
|
||||
device_box.setMaximumWidth(16777215)
|
||||
self.setFixedHeight(self._line_height)
|
||||
self.setMinimumWidth(self.dimensions[1])
|
||||
|
||||
self.ui.verticalLayout.setContentsMargins(0, 0, 0, 0)
|
||||
self.ui.verticalLayout.setSpacing(0)
|
||||
self.ui.readback.setMaximumWidth(16777215)
|
||||
self.ui.setpoint.setMaximumWidth(16777215)
|
||||
self.ui.step_size.setMaximumWidth(16777215)
|
||||
|
||||
indicator_hint = indicator.minimumSizeHint()
|
||||
step_hint = self.ui.step_size.sizeHint()
|
||||
self._indicator_thickness = max(indicator_hint.height(), 10)
|
||||
self._vertical_indicator_width = max(indicator.minimumWidth(), 15)
|
||||
self._horizontal_indicator_width = max(90, step_hint.width())
|
||||
base_width = max(device_box.minimumSizeHint().width(), self.dimensions[1])
|
||||
self._indicator_switch_width = (
|
||||
base_width - self._vertical_indicator_width + self._horizontal_indicator_width
|
||||
)
|
||||
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
self._update_indicator_orientation()
|
||||
|
||||
def _update_indicator_orientation(self):
|
||||
if not hasattr(self, "ui"):
|
||||
return
|
||||
|
||||
indicator = self.ui.position_indicator
|
||||
available_width = self.ui.device_box.width() or self.width() or self.dimensions[1]
|
||||
should_use_horizontal = available_width >= self._indicator_switch_width
|
||||
if should_use_horizontal == self._indicator_is_horizontal:
|
||||
return
|
||||
|
||||
self._indicator_is_horizontal = should_use_horizontal
|
||||
indicator.vertical = not should_use_horizontal
|
||||
|
||||
if should_use_horizontal:
|
||||
indicator.setMinimumSize(self._horizontal_indicator_width, self._indicator_thickness)
|
||||
indicator.setMaximumHeight(self._indicator_thickness)
|
||||
indicator.setMaximumWidth(16777215)
|
||||
indicator.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Fixed)
|
||||
else:
|
||||
indicator.setMinimumSize(self._vertical_indicator_width, self._indicator_thickness)
|
||||
indicator.setMaximumSize(self._vertical_indicator_width, 16777215)
|
||||
indicator.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Preferred)
|
||||
|
||||
indicator.updateGeometry()
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
|
||||
+31
-4
@@ -2,12 +2,18 @@
|
||||
<ui version="4.0">
|
||||
<class>Form</class>
|
||||
<widget class="QWidget" name="Form">
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>612</width>
|
||||
<height>91</height>
|
||||
<width>592</width>
|
||||
<height>76</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
@@ -26,8 +32,29 @@
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="device_box">
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="title">
|
||||
<string>Device Name</string>
|
||||
</property>
|
||||
@@ -227,12 +254,12 @@
|
||||
<customwidgets>
|
||||
<customwidget>
|
||||
<class>PositionIndicator</class>
|
||||
<extends>QWidget</extends>
|
||||
<extends></extends>
|
||||
<header>position_indicator</header>
|
||||
</customwidget>
|
||||
<customwidget>
|
||||
<class>SpinnerWidget</class>
|
||||
<extends>QWidget</extends>
|
||||
<extends></extends>
|
||||
<header>spinner_widget</header>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
|
||||
@@ -27,30 +27,13 @@ class PositionerGroupBox(QGroupBox):
|
||||
self.layout().setContentsMargins(0, 0, 0, 0)
|
||||
self.layout().setSpacing(0)
|
||||
self.widget = PositionerBox(self, dev_name)
|
||||
self.widget.compact_view = True
|
||||
self.widget.expand_popup = False
|
||||
self.layout().addWidget(self.widget)
|
||||
self.widget.position_update.connect(self._on_position_update)
|
||||
self.widget.expand.connect(self._on_expand)
|
||||
self.setTitle(self.device_name)
|
||||
self.widget.force_update_readback()
|
||||
|
||||
def _on_expand(self, expand):
|
||||
if expand:
|
||||
self.setTitle("")
|
||||
self.setFlat(True)
|
||||
else:
|
||||
self.setTitle(self.device_name)
|
||||
self.setFlat(False)
|
||||
|
||||
def _on_position_update(self, pos: float):
|
||||
self.position_update.emit(pos)
|
||||
precision = getattr(self.widget.dev[self.widget.device], "precision", 8)
|
||||
try:
|
||||
precision = int(precision)
|
||||
except (TypeError, ValueError):
|
||||
precision = int(8)
|
||||
self.widget.label = f"{pos:.{precision}f}"
|
||||
|
||||
def close(self):
|
||||
self.widget.close()
|
||||
|
||||
@@ -266,6 +266,7 @@ class DeviceSignalInputBase(BECWidget):
|
||||
|
||||
Args:
|
||||
device(str): Device to validate.
|
||||
raise_on_false(bool): Raise ValueError if device is not found.
|
||||
"""
|
||||
if device in self.dev:
|
||||
return True
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
from typing import Any, Callable, Generator, Iterable, TypeVar
|
||||
|
||||
from bec_lib.utils.json import ExtendedEncoder
|
||||
from bec_lib.utils.json_extended import ExtendedEncoder
|
||||
from qtpy.QtCore import QByteArray, QMimeData, QObject, Signal # type: ignore
|
||||
from qtpy.QtWidgets import QListWidgetItem
|
||||
|
||||
|
||||
+2
-4
@@ -51,8 +51,7 @@ class _DeviceEntryWidget(QFrame):
|
||||
self.setToolTip(self._rich_text())
|
||||
|
||||
def _rich_text(self):
|
||||
return dedent(
|
||||
f"""
|
||||
return dedent(f"""
|
||||
<b><u><h2> {self._device_spec.name}: </h2></u></b>
|
||||
<table>
|
||||
<tr><td> description: </td><td><i> {self._device_spec.description} </i></td></tr>
|
||||
@@ -60,8 +59,7 @@ class _DeviceEntryWidget(QFrame):
|
||||
<tr><td> enabled: </td><td><i> {self._device_spec.enabled} </i></td></tr>
|
||||
<tr><td> read only: </td><td><i> {self._device_spec.readOnly} </i></td></tr>
|
||||
</table>
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
def setup_title_layout(self, device_spec: HashableDevice):
|
||||
self._title_layout = QHBoxLayout()
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
|
||||
from .available_device_group import AvailableDeviceGroup
|
||||
|
||||
|
||||
class _DeviceListWiget(QListWidget):
|
||||
class _DeviceListWidget(QListWidget):
|
||||
|
||||
def _item_iter(self):
|
||||
return (self.item(i) for i in range(self.count()))
|
||||
@@ -44,7 +44,7 @@ class Ui_AvailableDeviceGroup(object):
|
||||
self.n_included.setObjectName("n_included")
|
||||
title_layout.addWidget(self.n_included)
|
||||
|
||||
self.device_list = _DeviceListWiget(AvailableDeviceGroup)
|
||||
self.device_list = _DeviceListWidget(AvailableDeviceGroup)
|
||||
self.device_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
|
||||
self.device_list.setObjectName("device_list")
|
||||
self.device_list.setFrameStyle(0)
|
||||
|
||||
+2
-2
@@ -34,13 +34,13 @@ class HashModel(str, Enum):
|
||||
class DeviceResourceBackend(Protocol):
|
||||
@property
|
||||
def tag_groups(self) -> dict[str, set[HashableDevice]]:
|
||||
"""A dictionary of all availble devices separated by tag groups. The same device may
|
||||
"""A dictionary of all available devices separated by tag groups. The same device may
|
||||
appear more than once (in different groups)."""
|
||||
...
|
||||
|
||||
@property
|
||||
def all_devices(self) -> set[HashableDevice]:
|
||||
"""A set of all availble devices. The same device may not appear more than once."""
|
||||
"""A set of all available devices. The same device may not appear more than once."""
|
||||
...
|
||||
|
||||
@property
|
||||
|
||||
@@ -5,9 +5,8 @@ in DeviceTableRow entries.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from copy import deepcopy
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal, Tuple
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterable, Tuple
|
||||
|
||||
from bec_lib.atlas_models import Device as DeviceModel
|
||||
from bec_lib.callback_handler import EventType
|
||||
@@ -19,6 +18,7 @@ from thefuzz import fuzz
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import get_accent_colors
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.fuzzy_search import is_match
|
||||
from bec_widgets.widgets.control.device_manager.components.device_table.device_table_row import (
|
||||
DeviceTableRow,
|
||||
)
|
||||
@@ -37,34 +37,6 @@ _DeviceCfgIter = Iterable[dict[str, Any]]
|
||||
# DeviceValidationResult: device_config, config_status, connection_status, error_message
|
||||
_ValidationResultIter = Iterable[Tuple[dict[str, Any], ConfigStatus, ConnectionStatus, str]]
|
||||
|
||||
FUZZY_SEARCH_THRESHOLD = 80
|
||||
|
||||
|
||||
def is_match(
|
||||
text: str, row_data: dict[str, Any], relevant_keys: list[str], enable_fuzzy: bool
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the text matches any of the relevant keys in the row data.
|
||||
|
||||
Args:
|
||||
text (str): The text to search for.
|
||||
row_data (dict[str, Any]): The row data to search in.
|
||||
relevant_keys (list[str]): The keys to consider for searching.
|
||||
enable_fuzzy (bool): Whether to use fuzzy matching.
|
||||
Returns:
|
||||
bool: True if a match is found, False otherwise.
|
||||
"""
|
||||
for key in relevant_keys:
|
||||
data = str(row_data.get(key, "") or "")
|
||||
if enable_fuzzy:
|
||||
match_ratio = fuzz.partial_ratio(text.lower(), data.lower())
|
||||
if match_ratio >= FUZZY_SEARCH_THRESHOLD:
|
||||
return True
|
||||
else:
|
||||
if text.lower() in data.lower():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class TableSortOnHold:
|
||||
"""Context manager for putting table sorting on hold. Works with nested calls."""
|
||||
|
||||
@@ -9,6 +9,7 @@ from qtpy.QtGui import QColor
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QComboBox,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
@@ -171,7 +172,13 @@ class ScanControl(BECWidget, QWidget):
|
||||
self.layout.addStretch()
|
||||
|
||||
def _add_metadata_form(self):
|
||||
self.layout.addWidget(self._metadata_form)
|
||||
# Wrap metadata form in a group box
|
||||
self._metadata_group = QGroupBox("Scan Metadata", self)
|
||||
self._metadata_group.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
|
||||
metadata_layout = QVBoxLayout(self._metadata_group)
|
||||
metadata_layout.addWidget(self._metadata_form)
|
||||
|
||||
self.layout.addWidget(self._metadata_group)
|
||||
self._metadata_form.update_with_new_scan(self.comboBox_scan_selection.currentText())
|
||||
self.scan_selected.connect(self._metadata_form.update_with_new_scan)
|
||||
self._metadata_form.form_data_updated.connect(self.update_scan_metadata)
|
||||
|
||||
@@ -347,14 +347,14 @@ class ScanGroupBox(QGroupBox):
|
||||
|
||||
def get_parameters(self, device_object: bool = True):
|
||||
"""
|
||||
Returns the parameters from the widgets in the scan control layout formated to run scan from BEC.
|
||||
Returns the parameters from the widgets in the scan control layout formatted to run scan from BEC.
|
||||
"""
|
||||
if self.box_type == "args":
|
||||
return self._get_arg_parameterts(device_object=device_object)
|
||||
return self._get_arg_parameters(device_object=device_object)
|
||||
elif self.box_type == "kwargs":
|
||||
return self._get_kwarg_parameters(device_object=device_object)
|
||||
|
||||
def _get_arg_parameterts(self, device_object: bool = True):
|
||||
def _get_arg_parameters(self, device_object: bool = True):
|
||||
args = []
|
||||
for i in range(1, self.layout.rowCount()):
|
||||
for j in range(self.layout.columnCount()):
|
||||
|
||||
@@ -2,22 +2,19 @@
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from qtpy.QtCore import Property, Signal, Slot
|
||||
from qtpy.QtWidgets import QComboBox, QVBoxLayout, QWidget
|
||||
from qtpy.QtWidgets import QComboBox
|
||||
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class DapComboBox(BECWidget, QWidget):
|
||||
class DapComboBox(BECWidget, QComboBox):
|
||||
"""
|
||||
The DAPComboBox widget is an extension to the QComboBox with all avaialble DAP model from BEC.
|
||||
Editable combobox listing the available DAP models.
|
||||
|
||||
Args:
|
||||
parent: Parent widget.
|
||||
client: BEC client object.
|
||||
gui_id: GUI ID.
|
||||
default: Default device name.
|
||||
The widget behaves as a plain QComboBox and keeps ``fit_model_combobox`` as an alias to itself
|
||||
for backwards compatibility with older call sites.
|
||||
"""
|
||||
|
||||
ICON_NAME = "data_exploration"
|
||||
@@ -45,19 +42,20 @@ class DapComboBox(BECWidget, QWidget):
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, client=client, gui_id=gui_id, **kwargs)
|
||||
self.layout = QVBoxLayout(self)
|
||||
self.fit_model_combobox = QComboBox(self)
|
||||
self.layout.addWidget(self.fit_model_combobox)
|
||||
self.layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._available_models = None
|
||||
self.fit_model_combobox = self # Just for backwards compatibility with older call sites, the widget itself is the combobox
|
||||
self._available_models: list[str] = []
|
||||
self._x_axis = None
|
||||
self._y_axis = None
|
||||
self.populate_fit_model_combobox()
|
||||
self.fit_model_combobox.currentTextChanged.connect(self._update_current_fit)
|
||||
# Set default fit model
|
||||
self.select_default_fit(default_fit)
|
||||
self._is_valid_input = False
|
||||
|
||||
def select_default_fit(self, default_fit: str | None):
|
||||
self.setEditable(True)
|
||||
|
||||
self.populate_fit_model_combobox()
|
||||
self.currentTextChanged.connect(self._on_text_changed)
|
||||
self.select_default_fit(default_fit)
|
||||
self.check_validity(self.currentText())
|
||||
|
||||
def select_default_fit(self, default_fit: str | None = "GaussianModel"):
|
||||
"""Set the default fit model.
|
||||
|
||||
Args:
|
||||
@@ -65,8 +63,8 @@ class DapComboBox(BECWidget, QWidget):
|
||||
"""
|
||||
if self._validate_dap_model(default_fit):
|
||||
self.select_fit_model(default_fit)
|
||||
else:
|
||||
self.select_fit_model("GaussianModel")
|
||||
elif self.available_models:
|
||||
self.select_fit_model(self.available_models[0])
|
||||
|
||||
@property
|
||||
def available_models(self):
|
||||
@@ -114,12 +112,40 @@ class DapComboBox(BECWidget, QWidget):
|
||||
self._y_axis = y_axis
|
||||
self.y_axis_updated.emit(y_axis)
|
||||
|
||||
def _update_current_fit(self, fit_name: str):
|
||||
"""Update the current fit."""
|
||||
@Slot(str)
|
||||
def _on_text_changed(self, fit_name: str):
|
||||
"""
|
||||
Validate and emit updates for the current text.
|
||||
|
||||
Args:
|
||||
fit_name(str): The current text in the combobox, representing the selected fit model.
|
||||
"""
|
||||
self.check_validity(fit_name)
|
||||
if not self._is_valid_input:
|
||||
return
|
||||
|
||||
self.fit_model_updated.emit(fit_name)
|
||||
if self.x_axis is not None and self.y_axis is not None:
|
||||
self.new_dap_config.emit(self._x_axis, self._y_axis, fit_name)
|
||||
|
||||
@Slot(str)
|
||||
def check_validity(self, fit_name: str):
|
||||
"""
|
||||
Highlight invalid manual entries similarly to DeviceComboBox.
|
||||
|
||||
Args:
|
||||
fit_name(str): The current text in the combobox, representing the selected fit model.
|
||||
"""
|
||||
if self._validate_dap_model(fit_name):
|
||||
self._is_valid_input = True
|
||||
self.setStyleSheet("border: 1px solid transparent;")
|
||||
else:
|
||||
self._is_valid_input = False
|
||||
if self.isEnabled():
|
||||
self.setStyleSheet("border: 1px solid red;")
|
||||
else:
|
||||
self.setStyleSheet("border: 1px solid transparent;")
|
||||
|
||||
@Slot(str)
|
||||
def select_x_axis(self, x_axis: str):
|
||||
"""Slot to update the x axis.
|
||||
@@ -128,7 +154,7 @@ class DapComboBox(BECWidget, QWidget):
|
||||
x_axis(str): X axis.
|
||||
"""
|
||||
self.x_axis = x_axis
|
||||
self._update_current_fit(self.fit_model_combobox.currentText())
|
||||
self._on_text_changed(self.currentText())
|
||||
|
||||
@Slot(str)
|
||||
def select_y_axis(self, y_axis: str):
|
||||
@@ -138,25 +164,26 @@ class DapComboBox(BECWidget, QWidget):
|
||||
y_axis(str): Y axis.
|
||||
"""
|
||||
self.y_axis = y_axis
|
||||
self._update_current_fit(self.fit_model_combobox.currentText())
|
||||
self._on_text_changed(self.currentText())
|
||||
|
||||
@Slot(str)
|
||||
def select_fit_model(self, fit_name: str | None):
|
||||
"""Slot to update the fit model.
|
||||
|
||||
Args:
|
||||
default_device(str): Default device name.
|
||||
fit_name(str): Fit model name.
|
||||
"""
|
||||
if not self._validate_dap_model(fit_name):
|
||||
raise ValueError(f"Fit {fit_name} is not valid.")
|
||||
self.fit_model_combobox.setCurrentText(fit_name)
|
||||
self.setCurrentText(fit_name)
|
||||
|
||||
def populate_fit_model_combobox(self):
|
||||
"""Populate the fit_model_combobox with the devices."""
|
||||
# pylint: disable=protected-access
|
||||
self.available_models = [model for model in self.client.dap._available_dap_plugins.keys()]
|
||||
self.fit_model_combobox.clear()
|
||||
self.fit_model_combobox.addItems(self.available_models)
|
||||
available_plugins = getattr(getattr(self.client, "dap", None), "_available_dap_plugins", {})
|
||||
self.available_models = [model for model in available_plugins.keys()]
|
||||
self.clear()
|
||||
self.addItems(self.available_models)
|
||||
|
||||
def _validate_dap_model(self, model: str | None) -> bool:
|
||||
"""Validate the DAP model.
|
||||
@@ -166,23 +193,23 @@ class DapComboBox(BECWidget, QWidget):
|
||||
"""
|
||||
if model is None:
|
||||
return False
|
||||
if model not in self.available_models:
|
||||
return False
|
||||
return True
|
||||
return model in self.available_models
|
||||
|
||||
@property
|
||||
def is_valid_input(self) -> bool:
|
||||
"""Whether the current text matches an available DAP model."""
|
||||
return self._is_valid_input
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import sys
|
||||
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
|
||||
app = QApplication([])
|
||||
app = QApplication(sys.argv)
|
||||
apply_theme("dark")
|
||||
widget = QWidget()
|
||||
widget.setFixedSize(200, 200)
|
||||
layout = QVBoxLayout()
|
||||
widget.setLayout(layout)
|
||||
layout.addWidget(DapComboBox())
|
||||
widget.show()
|
||||
app.exec_()
|
||||
dialog = DapComboBox()
|
||||
dialog.show()
|
||||
sys.exit(app.exec_())
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import os
|
||||
|
||||
import shiboken6
|
||||
from bec_lib.logger import bec_logger
|
||||
from qtpy.QtCore import Signal
|
||||
from qtpy.QtWidgets import QPushButton, QTreeWidgetItem, QVBoxLayout, QWidget
|
||||
from qtpy.QtWidgets import QPushButton, QSizePolicy, QTreeWidgetItem, QVBoxLayout, QWidget
|
||||
|
||||
from bec_widgets.utils import UILoader
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
@@ -34,7 +35,7 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialises the LMFitDialog widget.
|
||||
Initializes the LMFitDialog widget.
|
||||
|
||||
Args:
|
||||
parent (QWidget): The parent widget.
|
||||
@@ -68,6 +69,27 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
self._hide_curve_selection = False
|
||||
self._hide_summary = False
|
||||
self._hide_parameters = False
|
||||
self._configure_embedded_size_policy()
|
||||
|
||||
def _configure_embedded_size_policy(self):
|
||||
"""Allow the compact dialog to shrink more gracefully in embedded layouts."""
|
||||
if self._ui_file != "lmfit_dialog_compact.ui":
|
||||
return
|
||||
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
self.ui.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
|
||||
for group in (
|
||||
self.ui.group_curve_selection,
|
||||
self.ui.group_summary,
|
||||
self.ui.group_parameters,
|
||||
):
|
||||
group.setMinimumHeight(0)
|
||||
group.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
|
||||
for view in (self.ui.curve_list, self.ui.summary_tree, self.ui.param_tree):
|
||||
view.setMinimumHeight(0)
|
||||
view.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Ignored)
|
||||
|
||||
@property
|
||||
def enable_actions(self) -> bool:
|
||||
@@ -77,8 +99,14 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
@enable_actions.setter
|
||||
def enable_actions(self, enable: bool):
|
||||
self._enable_actions = enable
|
||||
for button in self.action_buttons.values():
|
||||
valid_buttons = {}
|
||||
for name, button in self.action_buttons.items():
|
||||
# just to be sure we have a valid c++ object
|
||||
if button is None or not shiboken6.isValid(button):
|
||||
continue
|
||||
button.setEnabled(enable)
|
||||
valid_buttons[name] = button
|
||||
self.action_buttons = valid_buttons
|
||||
|
||||
@SafeProperty(list)
|
||||
def active_action_list(self) -> list[str]:
|
||||
@@ -89,16 +117,6 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
def active_action_list(self, actions: list[str]):
|
||||
self._active_actions = actions
|
||||
|
||||
# This SafeSlot needed?
|
||||
@SafeSlot(bool)
|
||||
def set_actions_enabled(self, enable: bool) -> bool:
|
||||
"""SafeSlot to enable the move to buttons.
|
||||
|
||||
Args:
|
||||
enable (bool): Whether to enable the action buttons.
|
||||
"""
|
||||
self.enable_actions = enable
|
||||
|
||||
@SafeProperty(bool)
|
||||
def always_show_latest(self):
|
||||
"""SafeProperty to indicate if always the latest DAP update is displayed."""
|
||||
@@ -154,19 +172,21 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
self.ui.group_parameters.setVisible(not show)
|
||||
|
||||
@property
|
||||
def fit_curve_id(self) -> str:
|
||||
def fit_curve_id(self) -> str | None:
|
||||
"""SafeProperty for the currently displayed fit curve_id."""
|
||||
return self._fit_curve_id
|
||||
|
||||
@fit_curve_id.setter
|
||||
def fit_curve_id(self, curve_id: str):
|
||||
def fit_curve_id(self, curve_id: str | None):
|
||||
"""Setter for the currently displayed fit curve_id.
|
||||
|
||||
Args:
|
||||
fit_curve_id (str): The curve_id of the fit curve to be displayed.
|
||||
curve_id (str | None): The curve_id of the fit curve to be displayed,
|
||||
or None to clear the selection.
|
||||
"""
|
||||
self._fit_curve_id = curve_id
|
||||
self.selected_fit.emit(curve_id)
|
||||
if curve_id is not None:
|
||||
self.selected_fit.emit(curve_id)
|
||||
|
||||
@SafeSlot(str)
|
||||
def remove_dap_data(self, curve_id: str):
|
||||
@@ -176,6 +196,15 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
curve_id (str): The curve_id of the DAP data to be removed.
|
||||
"""
|
||||
self.summary_data.pop(curve_id, None)
|
||||
if self.fit_curve_id == curve_id:
|
||||
self.action_buttons = {}
|
||||
self.ui.summary_tree.clear()
|
||||
self.ui.param_tree.clear()
|
||||
remaining = list(self.summary_data.keys())
|
||||
if remaining:
|
||||
self.fit_curve_id = remaining[0]
|
||||
else:
|
||||
self._fit_curve_id = None
|
||||
self.refresh_curve_list()
|
||||
|
||||
@SafeSlot(str)
|
||||
@@ -251,6 +280,7 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
params (list): List of LMFit parameters for the fit curve.
|
||||
"""
|
||||
self._move_buttons = []
|
||||
self.action_buttons = {}
|
||||
self.ui.param_tree.clear()
|
||||
for param in params:
|
||||
param_name = param[0]
|
||||
@@ -269,18 +299,16 @@ class LMFitDialog(BECWidget, QWidget):
|
||||
if param_name in self.active_action_list: # pylint: disable=unsupported-membership-test
|
||||
# Create a push button to move the motor to a specific position
|
||||
widget = QWidget()
|
||||
button = QPushButton(f"Move to {param_name}")
|
||||
button = QPushButton("Move")
|
||||
button.clicked.connect(self._create_move_action(param_name, param[1]))
|
||||
if self.enable_actions is True:
|
||||
if self.enable_actions:
|
||||
button.setEnabled(True)
|
||||
else:
|
||||
button.setEnabled(False)
|
||||
button.setStyleSheet(
|
||||
f"""
|
||||
button.setStyleSheet(f"""
|
||||
QPushButton:enabled {{ background-color: {self._accent_colors.success.name()};color: white; }}
|
||||
QPushButton:disabled {{ background-color: grey;color: white; }}
|
||||
"""
|
||||
)
|
||||
""")
|
||||
self.action_buttons[param_name] = button
|
||||
layout = QVBoxLayout()
|
||||
layout.addWidget(self.action_buttons[param_name])
|
||||
|
||||
@@ -14,6 +14,18 @@
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QGridLayout" name="gridLayout">
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item row="0" column="0">
|
||||
<widget class="QSplitter" name="splitter_2">
|
||||
<property name="sizePolicy">
|
||||
@@ -22,15 +34,6 @@
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::VLine</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
@@ -41,6 +44,12 @@
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QGroupBox" name="group_curve_selection">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>120</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="title">
|
||||
<string>Select Curve</string>
|
||||
</property>
|
||||
@@ -58,18 +67,36 @@
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Vertical</enum>
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="QGroupBox" name="group_summary">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>180</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="title">
|
||||
<string>Fit Summary</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||
<item>
|
||||
<widget class="QTreeWidget" name="summary_tree">
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="indentation">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rootIsDecorated">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="uniformRowHeights">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<attribute name="headerDefaultSectionSize">
|
||||
<number>90</number>
|
||||
</attribute>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Property</string>
|
||||
@@ -85,12 +112,33 @@
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QGroupBox" name="group_parameters">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>240</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="title">
|
||||
<string>Parameter Details</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_3">
|
||||
<item>
|
||||
<widget class="QTreeWidget" name="param_tree">
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="indentation">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rootIsDecorated">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="columnCount">
|
||||
<number>4</number>
|
||||
</property>
|
||||
<attribute name="headerDefaultSectionSize">
|
||||
<number>80</number>
|
||||
</attribute>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Parameter</string>
|
||||
@@ -106,6 +154,11 @@
|
||||
<string>Std</string>
|
||||
</property>
|
||||
</column>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Action</string>
|
||||
</property>
|
||||
</column>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
|
||||
@@ -95,6 +95,12 @@
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="indentation">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rootIsDecorated">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="uniformRowHeights">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
@@ -147,6 +153,12 @@
|
||||
<width>0</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="indentation">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rootIsDecorated">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="columnCount">
|
||||
<number>4</number>
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import uuid4
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
import shiboken6
|
||||
from bec_lib.logger import bec_logger
|
||||
from qtpy.QtCore import Qt, Signal
|
||||
from qtpy.QtGui import QMouseEvent
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QStackedLayout,
|
||||
QTabWidget,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.widgets.utility.bec_term.protocol import BecTerminal
|
||||
from bec_widgets.widgets.utility.bec_term.util import get_current_bec_term_class
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
_BecTermClass = get_current_bec_term_class()
|
||||
|
||||
# Note on definitions:
|
||||
# Terminal: an instance of a terminal widget with a system shell
|
||||
# Console: one of possibly several widgets which may share ownership of one single terminal
|
||||
# Shell: a Console set to start the BEC IPython client in its terminal
|
||||
|
||||
|
||||
class ConsoleMode(str, enum.Enum):
|
||||
ACTIVE = "active"
|
||||
INACTIVE = "inactive"
|
||||
HIDDEN = "hidden"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TerminalOwnerInfo:
|
||||
"""Should be managed only by the BecConsoleRegistry. Consoles should ask the registry for
|
||||
necessary ownership info."""
|
||||
|
||||
owner_console_id: str | None = None
|
||||
registered_console_ids: set[str] = field(default_factory=set)
|
||||
instance: BecTerminal | None = None
|
||||
terminal_id: str = ""
|
||||
initialized: bool = False
|
||||
persist_session: bool = False
|
||||
fallback_holder: QWidget | None = None
|
||||
|
||||
|
||||
class BecConsoleRegistry:
|
||||
"""
|
||||
A registry for the BecConsole class to manage its instances.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Initialize the registry.
|
||||
"""
|
||||
self._consoles: WeakValueDictionary[str, BecConsole] = WeakValueDictionary()
|
||||
self._terminal_registry: dict[str, _TerminalOwnerInfo] = {}
|
||||
|
||||
@staticmethod
|
||||
def _is_valid_qobject(obj: object | None) -> bool:
|
||||
return obj is not None and shiboken6.isValid(obj)
|
||||
|
||||
def _connect_app_cleanup(self) -> None:
|
||||
app = QApplication.instance()
|
||||
if app is None:
|
||||
return
|
||||
app.aboutToQuit.connect(self.clear, Qt.ConnectionType.UniqueConnection)
|
||||
|
||||
@staticmethod
|
||||
def _new_terminal_info(console: BecConsole) -> _TerminalOwnerInfo:
|
||||
term = _BecTermClass()
|
||||
return _TerminalOwnerInfo(
|
||||
registered_console_ids={console.console_id},
|
||||
owner_console_id=console.console_id,
|
||||
instance=term,
|
||||
terminal_id=console.terminal_id,
|
||||
persist_session=console.persist_terminal_session,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _replace_terminal(info: _TerminalOwnerInfo, console: BecConsole) -> None:
|
||||
info.instance = _BecTermClass()
|
||||
info.initialized = False
|
||||
info.owner_console_id = console.console_id
|
||||
info.registered_console_ids.add(console.console_id)
|
||||
info.persist_session = info.persist_session or console.persist_terminal_session
|
||||
|
||||
def _delete_terminal_info(self, info: _TerminalOwnerInfo) -> None:
|
||||
if self._is_valid_qobject(info.instance):
|
||||
info.instance.deleteLater() # type: ignore[union-attr]
|
||||
info.instance = None
|
||||
if self._is_valid_qobject(info.fallback_holder):
|
||||
info.fallback_holder.deleteLater()
|
||||
info.fallback_holder = None
|
||||
|
||||
def _parking_parent(
|
||||
self,
|
||||
info: _TerminalOwnerInfo,
|
||||
console: BecConsole | None = None,
|
||||
*,
|
||||
avoid_console: bool = False,
|
||||
) -> QWidget | None:
|
||||
for console_id in info.registered_console_ids:
|
||||
candidate = self._consoles.get(console_id)
|
||||
if candidate is None or candidate is console:
|
||||
continue
|
||||
if self._is_valid_qobject(candidate):
|
||||
return candidate._term_holder
|
||||
|
||||
if console is None or not self._is_valid_qobject(console):
|
||||
return None
|
||||
|
||||
window = console.window()
|
||||
if window is not None and window is not console and self._is_valid_qobject(window):
|
||||
return window
|
||||
|
||||
if not avoid_console:
|
||||
return console._term_holder
|
||||
return None
|
||||
|
||||
def _fallback_holder(
|
||||
self,
|
||||
info: _TerminalOwnerInfo,
|
||||
console: BecConsole | None = None,
|
||||
*,
|
||||
avoid_console: bool = False,
|
||||
) -> QWidget:
|
||||
if not self._is_valid_qobject(info.fallback_holder):
|
||||
info.fallback_holder = QWidget(
|
||||
parent=self._parking_parent(info, console, avoid_console=avoid_console)
|
||||
)
|
||||
info.fallback_holder.setObjectName(f"_bec_console_terminal_holder_{info.terminal_id}")
|
||||
info.fallback_holder.hide()
|
||||
return info.fallback_holder
|
||||
|
||||
def _park_terminal(
|
||||
self,
|
||||
info: _TerminalOwnerInfo,
|
||||
console: BecConsole | None = None,
|
||||
*,
|
||||
avoid_console: bool = False,
|
||||
) -> None:
|
||||
if not self._is_valid_qobject(info.instance):
|
||||
return
|
||||
|
||||
parent = self._parking_parent(info, console, avoid_console=avoid_console)
|
||||
if parent is None and info.persist_session:
|
||||
parent = self._fallback_holder(info, console, avoid_console=avoid_console)
|
||||
|
||||
info.instance.hide() # type: ignore[union-attr]
|
||||
info.instance.setParent(parent) # type: ignore[union-attr]
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Delete every tracked terminal and holder."""
|
||||
for info in list(self._terminal_registry.values()):
|
||||
self._delete_terminal_info(info)
|
||||
self._terminal_registry.clear()
|
||||
self._consoles.clear()
|
||||
|
||||
def register(self, console: BecConsole):
|
||||
"""
|
||||
Register an instance of BecConsole. If there is already a terminal with the associated
|
||||
terminal_id, this does not automatically grant ownership.
|
||||
|
||||
Args:
|
||||
console (BecConsole): The instance to register.
|
||||
"""
|
||||
self._connect_app_cleanup()
|
||||
self._consoles[console.console_id] = console
|
||||
console_id, terminal_id = console.console_id, console.terminal_id
|
||||
term_info = self._terminal_registry.get(terminal_id)
|
||||
if term_info is None:
|
||||
self._terminal_registry[terminal_id] = self._new_terminal_info(console)
|
||||
return
|
||||
|
||||
term_info.persist_session = term_info.persist_session or console.persist_terminal_session
|
||||
had_registered_consoles = bool(term_info.registered_console_ids)
|
||||
term_info.registered_console_ids.add(console_id)
|
||||
if not self._is_valid_qobject(term_info.instance):
|
||||
self._replace_terminal(term_info, console)
|
||||
return
|
||||
if (
|
||||
term_info.owner_console_id is not None
|
||||
and term_info.owner_console_id not in self._consoles
|
||||
):
|
||||
term_info.owner_console_id = None
|
||||
if term_info.owner_console_id is None and not had_registered_consoles:
|
||||
term_info.owner_console_id = console_id
|
||||
logger.info(f"Registered new console {console_id} for terminal {terminal_id}")
|
||||
|
||||
def unregister(self, console: BecConsole):
|
||||
"""
|
||||
Unregister an instance of BecConsole.
|
||||
|
||||
Args:
|
||||
console (BecConsole): The instance to unregister.
|
||||
"""
|
||||
console_id, terminal_id = console.console_id, console.terminal_id
|
||||
if console_id in self._consoles:
|
||||
del self._consoles[console_id]
|
||||
if (term_info := self._terminal_registry.get(terminal_id)) is None:
|
||||
return
|
||||
detached = console._detach_terminal_widget(term_info.instance)
|
||||
if console_id in term_info.registered_console_ids:
|
||||
term_info.registered_console_ids.remove(console_id)
|
||||
if term_info.owner_console_id == console_id:
|
||||
term_info.owner_console_id = None
|
||||
if not term_info.registered_console_ids:
|
||||
if term_info.persist_session and self._is_valid_qobject(term_info.instance):
|
||||
self._park_terminal(term_info, console, avoid_console=True)
|
||||
logger.info(f"Unregistered console {console_id} for terminal {terminal_id}")
|
||||
return
|
||||
|
||||
self._delete_terminal_info(term_info)
|
||||
del self._terminal_registry[terminal_id]
|
||||
elif detached:
|
||||
self._park_terminal(term_info, console, avoid_console=True)
|
||||
|
||||
logger.info(f"Unregistered console {console_id} for terminal {terminal_id}")
|
||||
|
||||
def is_owner(self, console: BecConsole):
|
||||
"""Returns true if the given console is the owner of its terminal"""
|
||||
if console not in self._consoles.values():
|
||||
return False
|
||||
if (info := self._terminal_registry.get(console.terminal_id)) is None:
|
||||
logger.warning(f"Console {console.console_id} references an unknown terminal!")
|
||||
return False
|
||||
if not self._is_valid_qobject(info.instance):
|
||||
return False
|
||||
return info.owner_console_id == console.console_id
|
||||
|
||||
def take_ownership(self, console: BecConsole) -> BecTerminal | None:
|
||||
"""
|
||||
Transfer ownership of a terminal to the given console.
|
||||
|
||||
Args:
|
||||
console: the console which wishes to take ownership of its associated terminal.
|
||||
Returns:
|
||||
BecTerminal | None: The instance if ownership transfer was successful, None otherwise.
|
||||
"""
|
||||
console_id, terminal_id = console.console_id, console.terminal_id
|
||||
|
||||
if terminal_id not in self._terminal_registry:
|
||||
self.register(console)
|
||||
|
||||
instance_info = self._terminal_registry[terminal_id]
|
||||
if not self._is_valid_qobject(instance_info.instance):
|
||||
self._replace_terminal(instance_info, console)
|
||||
if (old_owner_console_ide := instance_info.owner_console_id) is not None:
|
||||
if (
|
||||
old_owner_console_ide != console_id
|
||||
and (old_owner := self._consoles.get(old_owner_console_ide)) is not None
|
||||
):
|
||||
old_owner.yield_ownership() # call this on the old owner to make sure it is updated
|
||||
instance_info.owner_console_id = console_id
|
||||
instance_info.registered_console_ids.add(console_id)
|
||||
logger.info(f"Transferred ownership of terminal {terminal_id} to {console_id}")
|
||||
return instance_info.instance
|
||||
|
||||
def try_get_term(self, console: BecConsole) -> BecTerminal | None:
|
||||
"""
|
||||
Return the terminal instance if the requesting console is the owner
|
||||
|
||||
Args:
|
||||
console: the requesting console.
|
||||
Returns:
|
||||
BecTerminal | None: The instance if the console is the owner, None otherwise.
|
||||
"""
|
||||
console_id, terminal_id = console.console_id, console.terminal_id
|
||||
logger.debug(f"checking term for {console_id}")
|
||||
if terminal_id not in self._terminal_registry:
|
||||
logger.warning(f"Terminal {terminal_id} not found in registry")
|
||||
return None
|
||||
|
||||
instance_info = self._terminal_registry[terminal_id]
|
||||
if not self._is_valid_qobject(instance_info.instance):
|
||||
if instance_info.owner_console_id == console_id:
|
||||
self._replace_terminal(instance_info, console)
|
||||
else:
|
||||
return None
|
||||
if instance_info.owner_console_id == console_id:
|
||||
return instance_info.instance
|
||||
|
||||
def yield_ownership(self, console: BecConsole):
|
||||
"""
|
||||
Yield ownership of an instance without destroying it. The instance remains in the
|
||||
registry with no owner, available for another widget to claim.
|
||||
|
||||
Args:
|
||||
console (BecConsole): The console which wishes to yield ownership of its associated terminal.
|
||||
"""
|
||||
console_id, terminal_id = console.console_id, console.terminal_id
|
||||
logger.debug(f"Console {console_id} attempted to yield ownership")
|
||||
if console_id not in self._consoles or terminal_id not in self._terminal_registry:
|
||||
return
|
||||
|
||||
term_info = self._terminal_registry[terminal_id]
|
||||
if term_info.owner_console_id != console_id:
|
||||
logger.debug(f"But it was not the owner, which was {term_info.owner_console_id}!")
|
||||
return
|
||||
term_info.owner_console_id = None
|
||||
console._detach_terminal_widget(term_info.instance)
|
||||
self._park_terminal(term_info, console)
|
||||
|
||||
def should_initialize(self, console: BecConsole) -> bool:
|
||||
"""Return true if the console should send its startup command to the terminal."""
|
||||
info = self._terminal_registry.get(console.terminal_id)
|
||||
if info is None:
|
||||
return False
|
||||
return (
|
||||
info.owner_console_id == console.console_id
|
||||
and not info.initialized
|
||||
and self._is_valid_qobject(info.instance)
|
||||
)
|
||||
|
||||
def mark_initialized(self, console: BecConsole) -> None:
|
||||
info = self._terminal_registry.get(console.terminal_id)
|
||||
if info is not None and info.owner_console_id == console.console_id:
|
||||
info.initialized = True
|
||||
|
||||
def owner_is_visible(self, term_id: str) -> bool:
|
||||
"""
|
||||
Check if the owner of an instance is currently visible.
|
||||
|
||||
Args:
|
||||
term_id (str): The terminal ID to check.
|
||||
Returns:
|
||||
bool: True if the owner is visible, False otherwise.
|
||||
"""
|
||||
instance_info = self._terminal_registry.get(term_id)
|
||||
if (
|
||||
instance_info is None
|
||||
or instance_info.owner_console_id is None
|
||||
or not self._is_valid_qobject(instance_info.instance)
|
||||
):
|
||||
return False
|
||||
|
||||
if (owner := self._consoles.get(instance_info.owner_console_id)) is None:
|
||||
return False
|
||||
return owner.isVisible()
|
||||
|
||||
|
||||
_bec_console_registry = BecConsoleRegistry()
|
||||
|
||||
|
||||
class _Overlay(QWidget):
|
||||
def __init__(self, console: BecConsole):
|
||||
super().__init__(parent=console)
|
||||
self._console = console
|
||||
|
||||
def mousePressEvent(self, event: QMouseEvent) -> None:
|
||||
if event.button() == Qt.MouseButton.LeftButton:
|
||||
self._console.take_terminal_ownership()
|
||||
event.accept()
|
||||
return
|
||||
return super().mousePressEvent(event)
|
||||
|
||||
|
||||
class BecConsole(BECWidget, QWidget):
|
||||
"""A console widget with access to a shared registry of terminals, such that instances can be moved around."""
|
||||
|
||||
_js_callback = Signal(bool)
|
||||
initialized = Signal()
|
||||
|
||||
PLUGIN = True
|
||||
ICON_NAME = "terminal"
|
||||
persist_terminal_session = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
config=None,
|
||||
client=None,
|
||||
gui_id=None,
|
||||
startup_cmd: str | None = None,
|
||||
terminal_id: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, client=client, gui_id=gui_id, config=config, **kwargs)
|
||||
self._mode = ConsoleMode.INACTIVE
|
||||
self._startup_cmd = startup_cmd
|
||||
self._is_initialized = False
|
||||
self.terminal_id = terminal_id or str(uuid4())
|
||||
self.console_id = self.gui_id
|
||||
self.term: BecTerminal | None = None # Will be set in _set_up_instance
|
||||
|
||||
self._set_up_instance()
|
||||
|
||||
def _set_up_instance(self):
|
||||
"""
|
||||
Set up the web instance and UI elements.
|
||||
"""
|
||||
self._stacked_layout = QStackedLayout()
|
||||
# self._stacked_layout.setStackingMode(QStackedLayout.StackingMode.StackAll)
|
||||
self._term_holder = QWidget()
|
||||
self._term_layout = QVBoxLayout()
|
||||
self._term_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._term_holder.setLayout(self._term_layout)
|
||||
|
||||
self.setLayout(self._stacked_layout)
|
||||
|
||||
# prepare overlay
|
||||
self._overlay = _Overlay(self)
|
||||
layout = QVBoxLayout(self._overlay)
|
||||
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
label = QLabel("Click to activate terminal", self._overlay)
|
||||
layout.addWidget(label)
|
||||
|
||||
self._stacked_layout.addWidget(self._term_holder)
|
||||
self._stacked_layout.addWidget(self._overlay)
|
||||
|
||||
# will create a new terminal instance if there isn't already one for this ID
|
||||
_bec_console_registry.register(self)
|
||||
self._infer_mode()
|
||||
self._ensure_startup_started()
|
||||
|
||||
def _infer_mode(self):
|
||||
self.term = _bec_console_registry.try_get_term(self)
|
||||
if self.term:
|
||||
self._set_mode(ConsoleMode.ACTIVE)
|
||||
elif self.isHidden():
|
||||
self._set_mode(ConsoleMode.HIDDEN)
|
||||
else:
|
||||
self._set_mode(ConsoleMode.INACTIVE)
|
||||
|
||||
def _set_mode(self, mode: ConsoleMode):
|
||||
"""
|
||||
Set the mode of the web console.
|
||||
|
||||
Args:
|
||||
mode (ConsoleMode): The mode to set.
|
||||
"""
|
||||
|
||||
match mode:
|
||||
case ConsoleMode.ACTIVE:
|
||||
if self.term:
|
||||
if self._term_layout.indexOf(self.term) == -1: # type: ignore[arg-type]
|
||||
self._term_layout.addWidget(self.term) # type: ignore # BecTerminal is QWidget
|
||||
self.term.show() # type: ignore[attr-defined]
|
||||
self._stacked_layout.setCurrentIndex(0)
|
||||
self._mode = mode
|
||||
else:
|
||||
self._stacked_layout.setCurrentIndex(1)
|
||||
self._mode = ConsoleMode.INACTIVE
|
||||
case ConsoleMode.INACTIVE:
|
||||
self._stacked_layout.setCurrentIndex(1)
|
||||
self._mode = mode
|
||||
case ConsoleMode.HIDDEN:
|
||||
self._stacked_layout.setCurrentIndex(1)
|
||||
self._mode = mode
|
||||
|
||||
@property
|
||||
def startup_cmd(self):
|
||||
"""
|
||||
Get the startup command for the web console.
|
||||
"""
|
||||
return self._startup_cmd
|
||||
|
||||
@startup_cmd.setter
|
||||
def startup_cmd(self, cmd: str | None):
|
||||
"""
|
||||
Set the startup command for the console.
|
||||
"""
|
||||
self._startup_cmd = cmd
|
||||
|
||||
def write(self, data: str, send_return: bool = True):
|
||||
"""
|
||||
Send data to the console
|
||||
|
||||
Args:
|
||||
data (str): The data to send.
|
||||
send_return (bool): Whether to send a return after the data.
|
||||
"""
|
||||
if self.term:
|
||||
self.term.write(data, send_return)
|
||||
|
||||
def _ensure_startup_started(self):
|
||||
if not self.startup_cmd or not _bec_console_registry.should_initialize(self):
|
||||
return
|
||||
self.write(self.startup_cmd, True)
|
||||
_bec_console_registry.mark_initialized(self)
|
||||
|
||||
def _detach_terminal_widget(self, term: BecTerminal | None) -> bool:
|
||||
if term is None or not BecConsoleRegistry._is_valid_qobject(term):
|
||||
if self.term is term:
|
||||
self.term = None
|
||||
return False
|
||||
|
||||
is_child = self.isAncestorOf(term) # type: ignore[arg-type]
|
||||
if self._term_layout.indexOf(term) != -1: # type: ignore[arg-type]
|
||||
self._term_layout.removeWidget(term) # type: ignore[arg-type]
|
||||
is_child = True
|
||||
if is_child:
|
||||
term.hide() # type: ignore[attr-defined]
|
||||
term.setParent(None) # type: ignore[attr-defined]
|
||||
if self.term is term:
|
||||
self.term = None
|
||||
return is_child
|
||||
|
||||
def take_terminal_ownership(self):
|
||||
"""
|
||||
Take ownership of a web instance from the registry. This will transfer the instance
|
||||
from its current owner (if any) to this widget.
|
||||
"""
|
||||
# Get the instance from registry
|
||||
self.term = _bec_console_registry.take_ownership(self)
|
||||
self._infer_mode()
|
||||
self._ensure_startup_started()
|
||||
if self._mode == ConsoleMode.ACTIVE:
|
||||
logger.debug(f"Widget {self.gui_id} took ownership of instance {self.terminal_id}")
|
||||
|
||||
def yield_ownership(self):
|
||||
"""
|
||||
Yield ownership of the instance. The instance remains in the registry with no owner,
|
||||
available for another widget to claim. This is automatically called when the
|
||||
widget becomes hidden.
|
||||
"""
|
||||
_bec_console_registry.yield_ownership(self)
|
||||
self._infer_mode()
|
||||
if self._mode != ConsoleMode.ACTIVE:
|
||||
logger.debug(f"Widget {self.gui_id} yielded ownership of instance {self.terminal_id}")
|
||||
|
||||
def hideEvent(self, event):
|
||||
"""Called when the widget is hidden. Automatically yields ownership."""
|
||||
self.yield_ownership()
|
||||
super().hideEvent(event)
|
||||
|
||||
def showEvent(self, event):
|
||||
"""Called when the widget is shown. Updates UI state based on ownership."""
|
||||
super().showEvent(event)
|
||||
if not _bec_console_registry.is_owner(self):
|
||||
if not _bec_console_registry.owner_is_visible(self.terminal_id):
|
||||
self.take_terminal_ownership()
|
||||
|
||||
def cleanup(self):
|
||||
"""Unregister this console on destruction."""
|
||||
_bec_console_registry.unregister(self)
|
||||
super().cleanup()
|
||||
|
||||
|
||||
class BECShell(BecConsole):
|
||||
"""
|
||||
A BecConsole pre-configured to run the BEC shell.
|
||||
We cannot simply expose the web console properties to Qt as we need to have a deterministic
|
||||
startup behavior for sharing the same shell instance across multiple widgets.
|
||||
"""
|
||||
|
||||
ICON_NAME = "hub"
|
||||
persist_terminal_session = True
|
||||
|
||||
def __init__(self, parent=None, config=None, client=None, gui_id=None, **kwargs):
|
||||
super().__init__(
|
||||
parent=parent,
|
||||
config=config,
|
||||
client=client,
|
||||
gui_id=gui_id,
|
||||
terminal_id="bec_shell",
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def startup_cmd(self):
|
||||
"""
|
||||
Get the startup command for the BEC shell.
|
||||
"""
|
||||
if self.bec_dispatcher.cli_server is None:
|
||||
return "bec --nogui"
|
||||
return f"bec --gui-id {self.bec_dispatcher.cli_server.gui_id}"
|
||||
|
||||
@startup_cmd.setter
|
||||
def startup_cmd(self, cmd: str | None): ...
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import sys
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
widget = QTabWidget()
|
||||
|
||||
# Create two consoles with different unique_ids
|
||||
bec_console_1a = BecConsole(startup_cmd="htop", gui_id="console_1_a", terminal_id="terminal_1")
|
||||
bec_console_1b = BecConsole(startup_cmd="htop", gui_id="console_1_b", terminal_id="terminal_1")
|
||||
bec_console_1 = QWidget()
|
||||
bec_console_1_layout = QHBoxLayout(bec_console_1)
|
||||
bec_console_1_layout.addWidget(bec_console_1a)
|
||||
bec_console_1_layout.addWidget(bec_console_1b)
|
||||
bec_console2 = BECShell()
|
||||
bec_console3 = BecConsole(gui_id="console_3", terminal_id="terminal_1")
|
||||
widget.addTab(bec_console_1, "Console 1")
|
||||
widget.addTab(bec_console2, "Console 2 - BEC Shell")
|
||||
widget.addTab(bec_console3, "Console 3 -- mirror of Console 1")
|
||||
widget.show()
|
||||
|
||||
widget.resize(800, 600)
|
||||
|
||||
sys.exit(app.exec_())
|
||||
@@ -0,0 +1 @@
|
||||
{'files': ['bec_console.py']}
|
||||
+9
-9
@@ -5,17 +5,17 @@ from qtpy.QtDesigner import QDesignerCustomWidgetInterface
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.utils.bec_designer import designer_material_icon
|
||||
from bec_widgets.widgets.editors.web_console.web_console import WebConsole
|
||||
from bec_widgets.widgets.editors.bec_console.bec_console import BecConsole
|
||||
|
||||
DOM_XML = """
|
||||
<ui language='c++'>
|
||||
<widget class='WebConsole' name='web_console'>
|
||||
<widget class='BecConsole' name='bec_console'>
|
||||
</widget>
|
||||
</ui>
|
||||
"""
|
||||
|
||||
|
||||
class WebConsolePlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
class BecConsolePlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._form_editor = None
|
||||
@@ -23,20 +23,20 @@ class WebConsolePlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
def createWidget(self, parent):
|
||||
if parent is None:
|
||||
return QWidget()
|
||||
t = WebConsole(parent)
|
||||
t = BecConsole(parent)
|
||||
return t
|
||||
|
||||
def domXml(self):
|
||||
return DOM_XML
|
||||
|
||||
def group(self):
|
||||
return "BEC Developer"
|
||||
return ""
|
||||
|
||||
def icon(self):
|
||||
return designer_material_icon(WebConsole.ICON_NAME)
|
||||
return designer_material_icon(BecConsole.ICON_NAME)
|
||||
|
||||
def includeFile(self):
|
||||
return "web_console"
|
||||
return "bec_console"
|
||||
|
||||
def initialize(self, form_editor):
|
||||
self._form_editor = form_editor
|
||||
@@ -48,10 +48,10 @@ class WebConsolePlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
return self._form_editor is not None
|
||||
|
||||
def name(self):
|
||||
return "WebConsole"
|
||||
return "BecConsole"
|
||||
|
||||
def toolTip(self):
|
||||
return ""
|
||||
return "A console widget with access to a shared registry of terminals, such that instances can be moved around."
|
||||
|
||||
def whatsThis(self):
|
||||
return self.toolTip()
|
||||
@@ -0,0 +1 @@
|
||||
{'files': ['bec_console.py']}
|
||||
+1
-1
@@ -5,7 +5,7 @@ from qtpy.QtDesigner import QDesignerCustomWidgetInterface
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.utils.bec_designer import designer_material_icon
|
||||
from bec_widgets.widgets.editors.web_console.web_console import BECShell
|
||||
from bec_widgets.widgets.editors.bec_console.bec_console import BECShell
|
||||
|
||||
DOM_XML = """
|
||||
<ui language='c++'>
|
||||
+2
-2
@@ -6,9 +6,9 @@ def main(): # pragma: no cover
|
||||
return
|
||||
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
|
||||
|
||||
from bec_widgets.widgets.editors.web_console.web_console_plugin import WebConsolePlugin
|
||||
from bec_widgets.widgets.editors.bec_console.bec_console_plugin import BecConsolePlugin
|
||||
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(WebConsolePlugin())
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(BecConsolePlugin())
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
+1
-1
@@ -6,7 +6,7 @@ def main(): # pragma: no cover
|
||||
return
|
||||
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
|
||||
|
||||
from bec_widgets.widgets.editors.web_console.bec_shell_plugin import BECShellPlugin
|
||||
from bec_widgets.widgets.editors.bec_console.bec_shell_plugin import BECShellPlugin
|
||||
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(BECShellPlugin())
|
||||
|
||||
@@ -47,15 +47,13 @@ class BECJupyterConsole(RichJupyterWidget): # pragma: no cover:
|
||||
)
|
||||
|
||||
def _init_bec_kernel(self):
|
||||
self.execute(
|
||||
"""
|
||||
self.execute("""
|
||||
from bec_ipython_client.main import BECIPythonClient
|
||||
bec = BECIPythonClient()
|
||||
bec.start()
|
||||
dev = bec.device_manager.devices if bec else None
|
||||
scans = bec.scans if bec else None
|
||||
"""
|
||||
)
|
||||
""")
|
||||
|
||||
def _cleanup_bec(self):
|
||||
if getattr(self, "ipyclient", None) is not None and self.inprocess is True:
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any, cast
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_lib.macro_update_handler import has_executable_code
|
||||
from qtpy.QtCore import QEvent, QTimer, Signal
|
||||
from qtpy.QtCore import Signal
|
||||
from qtpy.QtWidgets import QFileDialog, QMessageBox, QToolButton, QWidget
|
||||
|
||||
from bec_widgets.widgets.containers.dock_area.basic_dock_area import DockAreaWidget
|
||||
@@ -36,12 +36,12 @@ class MonacoDock(DockAreaWidget):
|
||||
**kwargs,
|
||||
)
|
||||
self.dock_manager.focusedDockWidgetChanged.connect(self._on_focus_event)
|
||||
self.dock_manager.installEventFilter(self)
|
||||
self._last_focused_editor: CDockWidget | None = None
|
||||
self.focused_editor.connect(self._on_last_focused_editor_changed)
|
||||
initial_editor = self.add_editor()
|
||||
if isinstance(initial_editor, CDockWidget):
|
||||
self.last_focused_editor = initial_editor
|
||||
self._install_manager_scan_and_fix_guards()
|
||||
|
||||
def _create_editor_widget(self) -> MonacoWidget:
|
||||
"""Create a configured Monaco editor widget."""
|
||||
@@ -73,7 +73,8 @@ class MonacoDock(DockAreaWidget):
|
||||
logger.info(f"Editor '{widget.current_file}' has unsaved changes: {widget.get_text()}")
|
||||
self.save_enabled.emit(widget.modified)
|
||||
|
||||
def _update_tab_title_for_modification(self, dock: CDockWidget, modified: bool):
|
||||
@staticmethod
|
||||
def _update_tab_title_for_modification(dock: CDockWidget, modified: bool):
|
||||
"""Update the tab title to show modification status with a dot indicator."""
|
||||
current_title = dock.windowTitle()
|
||||
|
||||
@@ -98,14 +99,12 @@ class MonacoDock(DockAreaWidget):
|
||||
return
|
||||
|
||||
active_sig = signatures[signature.get("activeSignature", 0)]
|
||||
active_param = signature.get("activeParameter", 0) # TODO: Add highlight for active_param
|
||||
|
||||
# Get signature label and documentation
|
||||
label = active_sig.get("label", "")
|
||||
doc_obj = active_sig.get("documentation", {})
|
||||
documentation = doc_obj.get("value", "") if isinstance(doc_obj, dict) else str(doc_obj)
|
||||
|
||||
# Format the markdown output
|
||||
# Format the Markdown output
|
||||
markdown = f"```python\n{label}\n```\n\n{documentation}"
|
||||
self.signature_help.emit(markdown)
|
||||
|
||||
@@ -156,9 +155,10 @@ class MonacoDock(DockAreaWidget):
|
||||
if self.last_focused_editor is dock:
|
||||
self.last_focused_editor = None
|
||||
# After topology changes, make sure single-tab areas get a plus button
|
||||
QTimer.singleShot(0, self._scan_and_fix_areas)
|
||||
self._scan_and_fix_areas()
|
||||
|
||||
def reset_widget(self, widget: MonacoWidget):
|
||||
@staticmethod
|
||||
def reset_widget(widget: MonacoWidget):
|
||||
"""
|
||||
Reset the given Monaco editor widget to its initial state.
|
||||
|
||||
@@ -193,23 +193,23 @@ class MonacoDock(DockAreaWidget):
|
||||
# pylint: disable=protected-access
|
||||
area._monaco_plus_btn = plus_btn
|
||||
|
||||
def _scan_and_fix_areas(self):
|
||||
def _install_manager_scan_and_fix_guards(self) -> None:
|
||||
"""
|
||||
Track ADS structural changes to trigger scan and fix of dock areas for plus button injection.
|
||||
"""
|
||||
self.dock_manager.dockAreaCreated.connect(self._scan_and_fix_areas)
|
||||
self.dock_manager.dockWidgetAdded.connect(self._scan_and_fix_areas)
|
||||
self.dock_manager.stateRestored.connect(self._scan_and_fix_areas)
|
||||
self.dock_manager.restoringState.connect(self._scan_and_fix_areas)
|
||||
self.dock_manager.focusedDockWidgetChanged.connect(self._scan_and_fix_areas)
|
||||
self._scan_and_fix_areas()
|
||||
|
||||
def _scan_and_fix_areas(self, *_arg):
|
||||
# Find all dock areas under this manager and ensure each single-tab area has a plus button
|
||||
areas = self.dock_manager.findChildren(CDockAreaWidget)
|
||||
for a in areas:
|
||||
self._ensure_area_plus(a)
|
||||
|
||||
def eventFilter(self, obj, event):
|
||||
# Track dock manager events
|
||||
if obj is self.dock_manager and event.type() in (
|
||||
QEvent.Type.ChildAdded,
|
||||
QEvent.Type.ChildRemoved,
|
||||
QEvent.Type.LayoutRequest,
|
||||
):
|
||||
QTimer.singleShot(0, self._scan_and_fix_areas)
|
||||
|
||||
return super().eventFilter(obj, event)
|
||||
|
||||
def add_editor(
|
||||
self, area: Any | None = None, title: str | None = None, tooltip: str | None = None
|
||||
) -> CDockWidget:
|
||||
@@ -258,7 +258,7 @@ class MonacoDock(DockAreaWidget):
|
||||
if area_widget is not None:
|
||||
self._ensure_area_plus(area_widget)
|
||||
|
||||
QTimer.singleShot(0, self._scan_and_fix_areas)
|
||||
self._scan_and_fix_areas()
|
||||
self.last_focused_editor = dock
|
||||
return dock
|
||||
|
||||
|
||||
@@ -362,8 +362,7 @@ if __name__ == "__main__": # pragma: no cover
|
||||
widget.set_language("python")
|
||||
widget.set_theme("vs-dark")
|
||||
widget.editor.set_minimap_enabled(False)
|
||||
widget.set_text(
|
||||
"""
|
||||
widget.set_text("""
|
||||
import numpy as np
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -380,8 +379,7 @@ if TYPE_CHECKING:
|
||||
# This is a comment
|
||||
def hello_world():
|
||||
print("Hello, world!")
|
||||
"""
|
||||
)
|
||||
""")
|
||||
widget.set_highlighted_lines(1, 3)
|
||||
widget.show()
|
||||
qapp.exec_()
|
||||
|
||||
@@ -53,6 +53,8 @@ class ScanMetadata(PydanticModelForm):
|
||||
|
||||
super().__init__(parent=parent, data_model=self._md_schema, client=client, **kwargs)
|
||||
|
||||
self._layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._form_grid_container.layout().setContentsMargins(0, 0, 0, 0)
|
||||
self._layout.addWidget(self._additional_md_box)
|
||||
self._additional_md_box_layout.addWidget(self._additional_metadata)
|
||||
|
||||
@@ -78,12 +80,27 @@ class ScanMetadata(PydanticModelForm):
|
||||
|
||||
def get_form_data(self):
|
||||
"""Get the entered metadata as a dict"""
|
||||
return self._additional_metadata.dump_dict() | self._dict_from_grid()
|
||||
form_data = self._additional_metadata.dump_dict() | self._dict_from_grid()
|
||||
|
||||
# If scan_name is empty, set it to the current scan
|
||||
if "scan_name" in form_data and not form_data["scan_name"]:
|
||||
form_data["scan_name"] = self._scan_name
|
||||
|
||||
return form_data
|
||||
|
||||
def populate(self):
|
||||
self._additional_metadata.update_disallowed_keys(list(self._md_schema.model_fields.keys()))
|
||||
super().populate()
|
||||
|
||||
# Set scan_name field to current scan if it exists and is empty
|
||||
if "scan_name" not in self.widget_dict:
|
||||
return
|
||||
scan_name_widget = self.widget_dict["scan_name"]
|
||||
if not hasattr(scan_name_widget, "getValue") or scan_name_widget.getValue():
|
||||
return
|
||||
if hasattr(scan_name_widget, "setValue"):
|
||||
scan_name_widget.setValue(self._scan_name)
|
||||
|
||||
def set_schema_from_scan(self, scan_name: str | None):
|
||||
self._scan_name = scan_name or ""
|
||||
self.set_schema(get_metadata_schema_for_scan(self._scan_name))
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{'files': ['web_console.py']}
|
||||
@@ -1,705 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import json
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from louie.saferef import safe_ref
|
||||
from pydantic import BaseModel
|
||||
from qtpy.QtCore import Qt, QTimer, QUrl, Signal, qInstallMessageHandler
|
||||
from qtpy.QtGui import QMouseEvent, QResizeEvent
|
||||
from qtpy.QtWebEngineWidgets import QWebEnginePage, QWebEngineView
|
||||
from qtpy.QtWidgets import QApplication, QLabel, QTabWidget, QVBoxLayout, QWidget
|
||||
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class ConsoleMode(str, enum.Enum):
|
||||
ACTIVE = "active"
|
||||
INACTIVE = "inactive"
|
||||
HIDDEN = "hidden"
|
||||
|
||||
|
||||
class PageOwnerInfo(BaseModel):
|
||||
owner_gui_id: str | None = None
|
||||
widget_ids: list[str] = []
|
||||
page: QWebEnginePage | None = None
|
||||
initialized: bool = False
|
||||
|
||||
model_config = {"arbitrary_types_allowed": True}
|
||||
|
||||
|
||||
class WebConsoleRegistry:
|
||||
"""
|
||||
A registry for the WebConsole class to manage its instances.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Initialize the registry.
|
||||
"""
|
||||
self._instances = {}
|
||||
self._server_process = None
|
||||
self._server_port = None
|
||||
self._token = secrets.token_hex(16)
|
||||
self._page_registry: dict[str, PageOwnerInfo] = {}
|
||||
|
||||
def register(self, instance: WebConsole):
|
||||
"""
|
||||
Register an instance of WebConsole.
|
||||
|
||||
Args:
|
||||
instance (WebConsole): The instance to register.
|
||||
"""
|
||||
self._instances[instance.gui_id] = safe_ref(instance)
|
||||
self.cleanup()
|
||||
|
||||
if instance._unique_id:
|
||||
self._register_page(instance)
|
||||
|
||||
if self._server_process is None:
|
||||
# Start the ttyd server if not already running
|
||||
self.start_ttyd()
|
||||
|
||||
def start_ttyd(self, use_zsh: bool | None = None):
|
||||
"""
|
||||
Start the ttyd server
|
||||
ttyd -q -W -t 'theme={"background": "black"}' zsh
|
||||
|
||||
Args:
|
||||
use_zsh (bool): Whether to use zsh or bash. If None, it will try to detect if zsh is available.
|
||||
"""
|
||||
|
||||
# First, check if ttyd is installed
|
||||
try:
|
||||
subprocess.run(["ttyd", "--version"], check=True, stdout=subprocess.PIPE)
|
||||
except FileNotFoundError:
|
||||
# pylint: disable=raise-missing-from
|
||||
raise RuntimeError("ttyd is not installed. Please install it first.")
|
||||
|
||||
if use_zsh is None:
|
||||
# Check if we can use zsh
|
||||
try:
|
||||
subprocess.run(["zsh", "--version"], check=True, stdout=subprocess.PIPE)
|
||||
use_zsh = True
|
||||
except FileNotFoundError:
|
||||
use_zsh = False
|
||||
|
||||
command = [
|
||||
"ttyd",
|
||||
"-p",
|
||||
"0",
|
||||
"-W",
|
||||
"-t",
|
||||
'theme={"background": "black"}',
|
||||
"-c",
|
||||
f"user:{self._token}",
|
||||
]
|
||||
if use_zsh:
|
||||
command.append("zsh")
|
||||
else:
|
||||
command.append("bash")
|
||||
|
||||
# Start the ttyd server
|
||||
self._server_process = subprocess.Popen(
|
||||
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
||||
)
|
||||
|
||||
self._wait_for_server_port()
|
||||
|
||||
self._server_process.stdout.close()
|
||||
self._server_process.stderr.close()
|
||||
|
||||
def _wait_for_server_port(self, timeout: float = 10):
|
||||
"""
|
||||
Wait for the ttyd server to start and get the port number.
|
||||
|
||||
Args:
|
||||
timeout (float): The timeout in seconds to wait for the server to start.
|
||||
"""
|
||||
start_time = time.time()
|
||||
while True:
|
||||
output = self._server_process.stderr.readline()
|
||||
if output == b"" and self._server_process.poll() is not None:
|
||||
break
|
||||
if not output:
|
||||
continue
|
||||
|
||||
output = output.decode("utf-8").strip()
|
||||
if "Listening on" in output:
|
||||
# Extract the port number from the output
|
||||
self._server_port = int(output.split(":")[-1])
|
||||
logger.info(f"ttyd server started on port {self._server_port}")
|
||||
break
|
||||
if time.time() - start_time > timeout:
|
||||
raise TimeoutError(
|
||||
"Timeout waiting for ttyd server to start. Please check if ttyd is installed and available in your PATH."
|
||||
)
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Clean up the registry by removing any instances that are no longer valid.
|
||||
"""
|
||||
for gui_id, weak_ref in list(self._instances.items()):
|
||||
if weak_ref() is None:
|
||||
del self._instances[gui_id]
|
||||
|
||||
if not self._instances and self._server_process:
|
||||
# If no instances are left, terminate the server process
|
||||
self._server_process.terminate()
|
||||
self._server_process = None
|
||||
self._server_port = None
|
||||
logger.info("ttyd server terminated")
|
||||
|
||||
def unregister(self, instance: WebConsole):
|
||||
"""
|
||||
Unregister an instance of WebConsole.
|
||||
|
||||
Args:
|
||||
instance (WebConsole): The instance to unregister.
|
||||
"""
|
||||
if instance.gui_id in self._instances:
|
||||
del self._instances[instance.gui_id]
|
||||
|
||||
if instance._unique_id:
|
||||
self._unregister_page(instance._unique_id, instance.gui_id)
|
||||
|
||||
self.cleanup()
|
||||
|
||||
def _register_page(self, instance: WebConsole):
|
||||
"""
|
||||
Register a page in the registry. Please note that this does not transfer ownership
|
||||
for already existing pages; it simply records which widget currently owns the page.
|
||||
Use transfer_page_ownership to change ownership.
|
||||
|
||||
Args:
|
||||
instance (WebConsole): The instance to register.
|
||||
"""
|
||||
|
||||
unique_id = instance._unique_id
|
||||
gui_id = instance.gui_id
|
||||
|
||||
if unique_id is None:
|
||||
return
|
||||
|
||||
if unique_id not in self._page_registry:
|
||||
page = BECWebEnginePage()
|
||||
page.authenticationRequired.connect(instance._authenticate)
|
||||
self._page_registry[unique_id] = PageOwnerInfo(
|
||||
owner_gui_id=gui_id, widget_ids=[gui_id], page=page
|
||||
)
|
||||
logger.info(f"Registered new page {unique_id} for {gui_id}")
|
||||
return
|
||||
|
||||
if gui_id not in self._page_registry[unique_id].widget_ids:
|
||||
self._page_registry[unique_id].widget_ids.append(gui_id)
|
||||
|
||||
def _unregister_page(self, unique_id: str, gui_id: str):
|
||||
"""
|
||||
Unregister a page from the registry.
|
||||
|
||||
Args:
|
||||
unique_id (str): The unique identifier for the page.
|
||||
gui_id (str): The GUI ID of the widget.
|
||||
"""
|
||||
if unique_id not in self._page_registry:
|
||||
return
|
||||
page_info = self._page_registry[unique_id]
|
||||
if gui_id in page_info.widget_ids:
|
||||
page_info.widget_ids.remove(gui_id)
|
||||
if page_info.owner_gui_id == gui_id:
|
||||
page_info.owner_gui_id = None
|
||||
if not page_info.widget_ids:
|
||||
if page_info.page:
|
||||
page_info.page.deleteLater()
|
||||
del self._page_registry[unique_id]
|
||||
|
||||
logger.info(f"Unregistered page {unique_id} for {gui_id}")
|
||||
|
||||
def get_page_info(self, unique_id: str) -> PageOwnerInfo | None:
|
||||
"""
|
||||
Get a page from the registry.
|
||||
|
||||
Args:
|
||||
unique_id (str): The unique identifier for the page.
|
||||
|
||||
Returns:
|
||||
PageOwnerInfo | None: The page info if found, None otherwise.
|
||||
"""
|
||||
if unique_id not in self._page_registry:
|
||||
return None
|
||||
return self._page_registry[unique_id]
|
||||
|
||||
def take_page_ownership(self, unique_id: str, new_owner_gui_id: str) -> QWebEnginePage | None:
|
||||
"""
|
||||
Transfer ownership of a page to a new owner.
|
||||
|
||||
Args:
|
||||
unique_id (str): The unique identifier for the page.
|
||||
new_owner_gui_id (str): The GUI ID of the new owner.
|
||||
|
||||
Returns:
|
||||
QWebEnginePage | None: The page if ownership transfer was successful, None otherwise.
|
||||
"""
|
||||
if unique_id not in self._page_registry:
|
||||
logger.warning(f"Page {unique_id} not found in registry")
|
||||
return None
|
||||
|
||||
page_info = self._page_registry[unique_id]
|
||||
old_owner_gui_id = page_info.owner_gui_id
|
||||
if old_owner_gui_id:
|
||||
old_owner_ref = self._instances.get(old_owner_gui_id)
|
||||
if old_owner_ref:
|
||||
old_owner_instance = old_owner_ref()
|
||||
if old_owner_instance:
|
||||
old_owner_instance.yield_ownership()
|
||||
page_info.owner_gui_id = new_owner_gui_id
|
||||
|
||||
logger.info(f"Transferred ownership of page {unique_id} to {new_owner_gui_id}")
|
||||
return page_info.page
|
||||
|
||||
def yield_ownership(self, gui_id: str) -> bool:
|
||||
"""
|
||||
Yield ownership of a page without destroying it. The page remains in the
|
||||
registry with no owner, available for another widget to claim.
|
||||
|
||||
Args:
|
||||
gui_id (str): The GUI ID of the widget yielding ownership.
|
||||
|
||||
Returns:
|
||||
bool: True if ownership was yielded, False otherwise.
|
||||
"""
|
||||
if gui_id not in self._instances:
|
||||
return False
|
||||
|
||||
instance = self._instances[gui_id]()
|
||||
if instance is None:
|
||||
return False
|
||||
|
||||
unique_id = instance._unique_id
|
||||
if unique_id is None:
|
||||
return False
|
||||
|
||||
if unique_id not in self._page_registry:
|
||||
return False
|
||||
|
||||
page_owner_info = self._page_registry[unique_id]
|
||||
if page_owner_info.owner_gui_id != gui_id:
|
||||
return False
|
||||
|
||||
page_owner_info.owner_gui_id = None
|
||||
return True
|
||||
|
||||
def owner_is_visible(self, unique_id: str) -> bool:
|
||||
"""
|
||||
Check if the owner of a page is currently visible.
|
||||
|
||||
Args:
|
||||
unique_id (str): The unique identifier for the page.
|
||||
Returns:
|
||||
bool: True if the owner is visible, False otherwise.
|
||||
"""
|
||||
page_info = self.get_page_info(unique_id)
|
||||
if page_info is None or page_info.owner_gui_id is None:
|
||||
return False
|
||||
|
||||
owner_ref = self._instances.get(page_info.owner_gui_id)
|
||||
if owner_ref is None:
|
||||
return False
|
||||
|
||||
owner_instance = owner_ref()
|
||||
if owner_instance is None:
|
||||
return False
|
||||
|
||||
return owner_instance.isVisible()
|
||||
|
||||
|
||||
_web_console_registry = WebConsoleRegistry()
|
||||
|
||||
|
||||
def suppress_qt_messages(type_, context, msg):
|
||||
if context.category in ["js", "default"]:
|
||||
return
|
||||
print(msg)
|
||||
|
||||
|
||||
qInstallMessageHandler(suppress_qt_messages)
|
||||
|
||||
|
||||
class BECWebEnginePage(QWebEnginePage):
|
||||
def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID):
|
||||
logger.info(f"[JS Console] {level.name} at line {lineNumber} in {sourceID}: {message}")
|
||||
|
||||
|
||||
class WebConsole(BECWidget, QWidget):
|
||||
"""
|
||||
A simple widget to display a website
|
||||
"""
|
||||
|
||||
_js_callback = Signal(bool)
|
||||
initialized = Signal()
|
||||
|
||||
PLUGIN = True
|
||||
ICON_NAME = "terminal"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
config=None,
|
||||
client=None,
|
||||
gui_id=None,
|
||||
startup_cmd: str | None = None,
|
||||
is_bec_shell: bool = False,
|
||||
unique_id: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(parent=parent, client=client, gui_id=gui_id, config=config, **kwargs)
|
||||
self._mode = ConsoleMode.INACTIVE
|
||||
self._is_bec_shell = is_bec_shell
|
||||
self._startup_cmd = startup_cmd
|
||||
self._is_initialized = False
|
||||
self._unique_id = unique_id
|
||||
self.page = None # Will be set in _set_up_page
|
||||
|
||||
self._startup_timer = QTimer()
|
||||
self._startup_timer.setInterval(500)
|
||||
self._startup_timer.timeout.connect(self._check_page_ready)
|
||||
self._startup_timer.start()
|
||||
self._js_callback.connect(self._on_js_callback)
|
||||
|
||||
self._set_up_page()
|
||||
|
||||
def _set_up_page(self):
|
||||
"""
|
||||
Set up the web page and UI elements.
|
||||
"""
|
||||
layout = QVBoxLayout()
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.browser = QWebEngineView(self)
|
||||
|
||||
layout.addWidget(self.browser)
|
||||
self.setLayout(layout)
|
||||
|
||||
# prepare overlay
|
||||
self.overlay = QWidget(self)
|
||||
layout = QVBoxLayout(self.overlay)
|
||||
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
label = QLabel("Click to activate terminal", self.overlay)
|
||||
layout.addWidget(label)
|
||||
self.overlay.hide()
|
||||
|
||||
_web_console_registry.register(self)
|
||||
self._token = _web_console_registry._token
|
||||
|
||||
# If no unique_id is provided, create a new page
|
||||
if not self._unique_id:
|
||||
self.page = BECWebEnginePage(self)
|
||||
self.page.authenticationRequired.connect(self._authenticate)
|
||||
self.page.setUrl(QUrl(f"http://localhost:{_web_console_registry._server_port}"))
|
||||
self.browser.setPage(self.page)
|
||||
self._set_mode(ConsoleMode.ACTIVE)
|
||||
return
|
||||
|
||||
# Try to get the page from the registry
|
||||
page_info = _web_console_registry.get_page_info(self._unique_id)
|
||||
if page_info and page_info.page:
|
||||
self.page = page_info.page
|
||||
if not page_info.owner_gui_id or page_info.owner_gui_id == self.gui_id:
|
||||
self.browser.setPage(self.page)
|
||||
# Only set URL if this is a newly created page (no URL set yet)
|
||||
if self.page.url().isEmpty():
|
||||
self.page.setUrl(QUrl(f"http://localhost:{_web_console_registry._server_port}"))
|
||||
else:
|
||||
# We have an existing page, so we don't need the startup timer
|
||||
self._startup_timer.stop()
|
||||
if page_info.owner_gui_id != self.gui_id:
|
||||
self._set_mode(ConsoleMode.INACTIVE)
|
||||
else:
|
||||
self._set_mode(ConsoleMode.ACTIVE)
|
||||
|
||||
def _set_mode(self, mode: ConsoleMode):
|
||||
"""
|
||||
Set the mode of the web console.
|
||||
|
||||
Args:
|
||||
mode (ConsoleMode): The mode to set.
|
||||
"""
|
||||
if not self._unique_id:
|
||||
# For non-unique_id consoles, always active
|
||||
mode = ConsoleMode.ACTIVE
|
||||
|
||||
self._mode = mode
|
||||
match mode:
|
||||
case ConsoleMode.ACTIVE:
|
||||
self.browser.setVisible(True)
|
||||
self.overlay.hide()
|
||||
case ConsoleMode.INACTIVE:
|
||||
self.browser.setVisible(False)
|
||||
self.overlay.show()
|
||||
case ConsoleMode.HIDDEN:
|
||||
self.browser.setVisible(False)
|
||||
self.overlay.hide()
|
||||
|
||||
def _check_page_ready(self):
|
||||
"""
|
||||
Check if the page is ready and stop the timer if it is.
|
||||
"""
|
||||
if not self.page or self.page.isLoading():
|
||||
return
|
||||
|
||||
self.page.runJavaScript("window.term !== undefined", self._js_callback.emit)
|
||||
|
||||
def _on_js_callback(self, ready: bool):
|
||||
"""
|
||||
Callback for when the JavaScript is ready.
|
||||
"""
|
||||
if not ready:
|
||||
return
|
||||
self._is_initialized = True
|
||||
self._startup_timer.stop()
|
||||
if self.startup_cmd:
|
||||
if self._unique_id:
|
||||
page_info = _web_console_registry.get_page_info(self._unique_id)
|
||||
if page_info is None:
|
||||
return
|
||||
if not page_info.initialized:
|
||||
page_info.initialized = True
|
||||
self.write(self.startup_cmd)
|
||||
else:
|
||||
self.write(self.startup_cmd)
|
||||
self.initialized.emit()
|
||||
|
||||
@property
|
||||
def startup_cmd(self):
|
||||
"""
|
||||
Get the startup command for the web console.
|
||||
"""
|
||||
if self._is_bec_shell:
|
||||
if self.bec_dispatcher.cli_server is None:
|
||||
return "bec --nogui"
|
||||
return f"bec --gui-id {self.bec_dispatcher.cli_server.gui_id}"
|
||||
return self._startup_cmd
|
||||
|
||||
@startup_cmd.setter
|
||||
def startup_cmd(self, cmd: str):
|
||||
"""
|
||||
Set the startup command for the web console.
|
||||
"""
|
||||
if not isinstance(cmd, str):
|
||||
raise ValueError("Startup command must be a string.")
|
||||
self._startup_cmd = cmd
|
||||
|
||||
def write(self, data: str, send_return: bool = True):
|
||||
"""
|
||||
Send data to the web page
|
||||
|
||||
Args:
|
||||
data (str): The data to send.
|
||||
send_return (bool): Whether to send a return after the data.
|
||||
"""
|
||||
cmd = f"window.term.paste({json.dumps(data)});"
|
||||
if self.page is None:
|
||||
logger.warning("Cannot write to web console: page is not initialized.")
|
||||
return
|
||||
self.page.runJavaScript(cmd)
|
||||
if send_return:
|
||||
self.send_return()
|
||||
|
||||
def take_page_ownership(self, unique_id: str | None = None):
|
||||
"""
|
||||
Take ownership of a web page from the registry. This will transfer the page
|
||||
from its current owner (if any) to this widget.
|
||||
|
||||
Args:
|
||||
unique_id (str): The unique identifier of the page to take ownership of.
|
||||
If None, uses this widget's unique_id.
|
||||
"""
|
||||
if unique_id is None:
|
||||
unique_id = self._unique_id
|
||||
|
||||
if not unique_id:
|
||||
logger.warning("Cannot take page ownership without a unique_id")
|
||||
return
|
||||
|
||||
# Get the page from registry
|
||||
page = _web_console_registry.take_page_ownership(unique_id, self.gui_id)
|
||||
|
||||
if not page:
|
||||
logger.warning(f"Page {unique_id} not found in registry")
|
||||
return
|
||||
|
||||
self.page = page
|
||||
self.browser.setPage(page)
|
||||
self._set_mode(ConsoleMode.ACTIVE)
|
||||
logger.info(f"Widget {self.gui_id} took ownership of page {unique_id}")
|
||||
|
||||
def _on_ownership_lost(self):
|
||||
"""
|
||||
Called when this widget loses ownership of its page.
|
||||
Displays the overlay and hides the browser.
|
||||
"""
|
||||
self._set_mode(ConsoleMode.INACTIVE)
|
||||
logger.info(f"Widget {self.gui_id} lost ownership of page {self._unique_id}")
|
||||
|
||||
def yield_ownership(self):
|
||||
"""
|
||||
Yield ownership of the page. The page remains in the registry with no owner,
|
||||
available for another widget to claim. This is automatically called when the
|
||||
widget becomes hidden.
|
||||
"""
|
||||
if not self._unique_id:
|
||||
return
|
||||
success = _web_console_registry.yield_ownership(self.gui_id)
|
||||
if success:
|
||||
self._on_ownership_lost()
|
||||
logger.info(f"Widget {self.gui_id} yielded ownership of page {self._unique_id}")
|
||||
|
||||
def has_ownership(self) -> bool:
|
||||
"""
|
||||
Check if this widget currently has ownership of a page.
|
||||
|
||||
Returns:
|
||||
bool: True if this widget owns a page, False otherwise.
|
||||
"""
|
||||
if not self._unique_id:
|
||||
return False
|
||||
page_info = _web_console_registry.get_page_info(self._unique_id)
|
||||
if page_info is None:
|
||||
return False
|
||||
return page_info.owner_gui_id == self.gui_id
|
||||
|
||||
def hideEvent(self, event):
|
||||
"""
|
||||
Called when the widget is hidden. Automatically yields ownership.
|
||||
"""
|
||||
if self.has_ownership():
|
||||
self.yield_ownership()
|
||||
self._set_mode(ConsoleMode.HIDDEN)
|
||||
super().hideEvent(event)
|
||||
|
||||
def showEvent(self, event):
|
||||
"""
|
||||
Called when the widget is shown. Updates UI state based on ownership.
|
||||
"""
|
||||
super().showEvent(event)
|
||||
if self._unique_id and not self.has_ownership():
|
||||
# Take ownership if the page does not have an owner or
|
||||
# the owner is not visible
|
||||
page_info = _web_console_registry.get_page_info(self._unique_id)
|
||||
if page_info is None:
|
||||
self._set_mode(ConsoleMode.INACTIVE)
|
||||
return
|
||||
if page_info.owner_gui_id is None or not _web_console_registry.owner_is_visible(
|
||||
self._unique_id
|
||||
):
|
||||
self.take_page_ownership(self._unique_id)
|
||||
return
|
||||
if page_info.owner_gui_id != self.gui_id:
|
||||
self._set_mode(ConsoleMode.INACTIVE)
|
||||
return
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None:
|
||||
super().resizeEvent(event)
|
||||
self.overlay.resize(event.size())
|
||||
|
||||
def mousePressEvent(self, event: QMouseEvent) -> None:
|
||||
if event.button() == Qt.MouseButton.LeftButton and not self.has_ownership():
|
||||
self.take_page_ownership(self._unique_id)
|
||||
event.accept()
|
||||
return
|
||||
return super().mousePressEvent(event)
|
||||
|
||||
def _authenticate(self, _, auth):
|
||||
"""
|
||||
Authenticate the request with the provided username and password.
|
||||
"""
|
||||
auth.setUser("user")
|
||||
auth.setPassword(self._token)
|
||||
|
||||
def send_return(self):
|
||||
"""
|
||||
Send return to the web page
|
||||
"""
|
||||
self.page.runJavaScript(
|
||||
"document.querySelector('textarea.xterm-helper-textarea').dispatchEvent(new KeyboardEvent('keypress', {charCode: 13}))"
|
||||
)
|
||||
|
||||
def send_ctrl_c(self):
|
||||
"""
|
||||
Send Ctrl+C to the web page
|
||||
"""
|
||||
self.page.runJavaScript(
|
||||
"document.querySelector('textarea.xterm-helper-textarea').dispatchEvent(new KeyboardEvent('keypress', {charCode: 3}))"
|
||||
)
|
||||
|
||||
def set_readonly(self, readonly: bool):
|
||||
"""
|
||||
Set the web console to read-only mode.
|
||||
"""
|
||||
if not isinstance(readonly, bool):
|
||||
raise ValueError("Readonly must be a boolean.")
|
||||
self.setEnabled(not readonly)
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Clean up the registry by removing any instances that are no longer valid.
|
||||
"""
|
||||
self._startup_timer.stop()
|
||||
_web_console_registry.unregister(self)
|
||||
super().cleanup()
|
||||
|
||||
|
||||
class BECShell(WebConsole):
|
||||
"""
|
||||
A WebConsole pre-configured to run the BEC shell.
|
||||
We cannot simply expose the web console properties to Qt as we need to have a deterministic
|
||||
startup behavior for sharing the same shell instance across multiple widgets.
|
||||
"""
|
||||
|
||||
ICON_NAME = "hub"
|
||||
|
||||
def __init__(self, parent=None, config=None, client=None, gui_id=None, **kwargs):
|
||||
super().__init__(
|
||||
parent=parent,
|
||||
config=config,
|
||||
client=client,
|
||||
gui_id=gui_id,
|
||||
is_bec_shell=True,
|
||||
unique_id="bec_shell",
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
import sys
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
widget = QTabWidget()
|
||||
|
||||
# Create two consoles with different unique_ids
|
||||
web_console1 = WebConsole(startup_cmd="bec --nogui", unique_id="console1")
|
||||
web_console2 = WebConsole(startup_cmd="htop")
|
||||
web_console3 = WebConsole(startup_cmd="bec --nogui", unique_id="console1")
|
||||
widget.addTab(web_console1, "Console 1")
|
||||
widget.addTab(web_console2, "Console 2")
|
||||
widget.addTab(web_console3, "Console 3 -- mirror of Console 1")
|
||||
widget.show()
|
||||
|
||||
# Demonstrate page sharing:
|
||||
# After initialization, web_console2 can take ownership of console1's page:
|
||||
# web_console2.take_page_ownership("console1")
|
||||
|
||||
widget.resize(800, 600)
|
||||
|
||||
def _close_cons1():
|
||||
web_console2.close()
|
||||
web_console2.deleteLater()
|
||||
|
||||
# QTimer.singleShot(3000, _close_cons1)
|
||||
|
||||
sys.exit(app.exec_())
|
||||
@@ -1 +0,0 @@
|
||||
{'files': ['web_console.py']}
|
||||
@@ -35,8 +35,8 @@ logger = bec_logger.logger
|
||||
class HeatmapDeviceSignal(BaseModel):
|
||||
"""The configuration of a signal in the scatter waveform widget."""
|
||||
|
||||
name: str
|
||||
entry: str
|
||||
device: str
|
||||
signal: str
|
||||
|
||||
model_config: dict = {"validate_assignment": True}
|
||||
|
||||
@@ -65,13 +65,13 @@ class HeatmapConfig(ConnectionConfig):
|
||||
lock_aspect_ratio: bool = Field(
|
||||
False, description="Whether to lock the aspect ratio of the image."
|
||||
)
|
||||
x_device: HeatmapDeviceSignal | None = Field(
|
||||
device_x: HeatmapDeviceSignal | None = Field(
|
||||
None, description="The x device signal of the heatmap."
|
||||
)
|
||||
y_device: HeatmapDeviceSignal | None = Field(
|
||||
device_y: HeatmapDeviceSignal | None = Field(
|
||||
None, description="The y device signal of the heatmap."
|
||||
)
|
||||
z_device: HeatmapDeviceSignal | None = Field(
|
||||
device_z: HeatmapDeviceSignal | None = Field(
|
||||
None, description="The z device signal of the heatmap."
|
||||
)
|
||||
|
||||
@@ -204,18 +204,18 @@ class Heatmap(ImageBase):
|
||||
"rois",
|
||||
"plot",
|
||||
# Device properties
|
||||
"x_device_name",
|
||||
"x_device_name.setter",
|
||||
"x_device_entry",
|
||||
"x_device_entry.setter",
|
||||
"y_device_name",
|
||||
"y_device_name.setter",
|
||||
"y_device_entry",
|
||||
"y_device_entry.setter",
|
||||
"z_device_name",
|
||||
"z_device_name.setter",
|
||||
"z_device_entry",
|
||||
"z_device_entry.setter",
|
||||
"device_x",
|
||||
"device_x.setter",
|
||||
"signal_x",
|
||||
"signal_x.setter",
|
||||
"device_y",
|
||||
"device_y.setter",
|
||||
"signal_y",
|
||||
"signal_y.setter",
|
||||
"device_z",
|
||||
"device_z.setter",
|
||||
"signal_z",
|
||||
"signal_z.setter",
|
||||
]
|
||||
|
||||
PLUGIN = True
|
||||
@@ -238,9 +238,9 @@ class Heatmap(ImageBase):
|
||||
interpolation="linear",
|
||||
oversampling_factor=1.0,
|
||||
lock_aspect_ratio=False,
|
||||
x_device=None,
|
||||
y_device=None,
|
||||
z_device=None,
|
||||
device_x=None,
|
||||
device_y=None,
|
||||
device_z=None,
|
||||
)
|
||||
super().__init__(parent=parent, config=config, theme_update=True, **kwargs)
|
||||
self._image_config = config
|
||||
@@ -314,12 +314,12 @@ class Heatmap(ImageBase):
|
||||
@SafeSlot(popup_error=True)
|
||||
def plot(
|
||||
self,
|
||||
x_name: str,
|
||||
y_name: str,
|
||||
z_name: str,
|
||||
x_entry: None | str = None,
|
||||
y_entry: None | str = None,
|
||||
z_entry: None | str = None,
|
||||
device_x: str,
|
||||
device_y: str,
|
||||
device_z: str,
|
||||
signal_x: None | str = None,
|
||||
signal_y: None | str = None,
|
||||
signal_z: None | str = None,
|
||||
color_map: str | None = "plasma",
|
||||
validate_bec: bool = True,
|
||||
interpolation: Literal["linear", "nearest"] | None = None,
|
||||
@@ -333,12 +333,12 @@ class Heatmap(ImageBase):
|
||||
Plot the heatmap with the given x, y, and z data.
|
||||
|
||||
Args:
|
||||
x_name (str): The name of the x-axis signal.
|
||||
y_name (str): The name of the y-axis signal.
|
||||
z_name (str): The name of the z-axis signal.
|
||||
x_entry (str | None): The entry for the x-axis signal.
|
||||
y_entry (str | None): The entry for the y-axis signal.
|
||||
z_entry (str | None): The entry for the z-axis signal.
|
||||
device_x (str): The name of the x-axis device signal.
|
||||
device_y (str): The name of the y-axis device signal.
|
||||
device_z (str): The name of the z-axis device signal.
|
||||
signal_x (str | None): The entry for the x-axis device signal.
|
||||
signal_y (str | None): The entry for the y-axis device signal.
|
||||
signal_z (str | None): The entry for the z-axis device signal.
|
||||
color_map (str | None): The color map to use for the heatmap.
|
||||
validate_bec (bool): Whether to validate the entries against BEC signals.
|
||||
interpolation (Literal["linear", "nearest"] | None): The interpolation method to use.
|
||||
@@ -349,13 +349,13 @@ class Heatmap(ImageBase):
|
||||
reload (bool): Whether to reload the heatmap with new data.
|
||||
"""
|
||||
if validate_bec:
|
||||
x_entry = self.entry_validator.validate_signal(x_name, x_entry)
|
||||
y_entry = self.entry_validator.validate_signal(y_name, y_entry)
|
||||
z_entry = self.entry_validator.validate_signal(z_name, z_entry)
|
||||
signal_x = self.entry_validator.validate_signal(device_x, signal_x)
|
||||
signal_y = self.entry_validator.validate_signal(device_y, signal_y)
|
||||
signal_z = self.entry_validator.validate_signal(device_z, signal_z)
|
||||
|
||||
if x_entry is None or y_entry is None or z_entry is None:
|
||||
if signal_x is None or signal_y is None or signal_z is None:
|
||||
raise ValueError("x, y, and z entries must be provided.")
|
||||
if x_name is None or y_name is None or z_name is None:
|
||||
if device_x is None or device_y is None or device_z is None:
|
||||
raise ValueError("x, y, and z names must be provided.")
|
||||
|
||||
if interpolation is None:
|
||||
@@ -374,24 +374,24 @@ class Heatmap(ImageBase):
|
||||
show_config_label = self._image_config.show_config_label
|
||||
|
||||
def _device_key(device: HeatmapDeviceSignal | None) -> tuple[str | None, str | None]:
|
||||
return (device.name if device else None, device.entry if device else None)
|
||||
return (device.device if device else None, device.signal if device else None)
|
||||
|
||||
prev_cfg = getattr(self, "_image_config", None)
|
||||
config_changed = False
|
||||
if prev_cfg and prev_cfg.x_device and prev_cfg.y_device and prev_cfg.z_device:
|
||||
if prev_cfg and prev_cfg.device_x and prev_cfg.device_y and prev_cfg.device_z:
|
||||
config_changed = any(
|
||||
(
|
||||
_device_key(prev_cfg.x_device) != (x_name, x_entry),
|
||||
_device_key(prev_cfg.y_device) != (y_name, y_entry),
|
||||
_device_key(prev_cfg.z_device) != (z_name, z_entry),
|
||||
_device_key(prev_cfg.device_x) != (device_x, signal_x),
|
||||
_device_key(prev_cfg.device_y) != (device_y, signal_y),
|
||||
_device_key(prev_cfg.device_z) != (device_z, signal_z),
|
||||
)
|
||||
)
|
||||
|
||||
self._image_config = HeatmapConfig(
|
||||
parent_id=self.gui_id,
|
||||
x_device=HeatmapDeviceSignal(name=x_name, entry=x_entry),
|
||||
y_device=HeatmapDeviceSignal(name=y_name, entry=y_entry),
|
||||
z_device=HeatmapDeviceSignal(name=z_name, entry=z_entry),
|
||||
device_x=HeatmapDeviceSignal(device=device_x, signal=signal_x),
|
||||
device_y=HeatmapDeviceSignal(device=device_y, signal=signal_y),
|
||||
device_z=HeatmapDeviceSignal(device=device_z, signal=signal_z),
|
||||
color_map=color_map,
|
||||
color_bar=None,
|
||||
interpolation=interpolation,
|
||||
@@ -428,26 +428,26 @@ class Heatmap(ImageBase):
|
||||
return
|
||||
|
||||
# Safely get device names (might be None if not yet configured)
|
||||
x_device = self._image_config.x_device
|
||||
y_device = self._image_config.y_device
|
||||
z_device = self._image_config.z_device
|
||||
device_x = self._image_config.device_x
|
||||
device_y = self._image_config.device_y
|
||||
device_z = self._image_config.device_z
|
||||
|
||||
x_name = x_device.name if x_device else None
|
||||
y_name = y_device.name if y_device else None
|
||||
z_name = z_device.name if z_device else None
|
||||
device_x_name = device_x.device if device_x else None
|
||||
device_y_name = device_y.device if device_y else None
|
||||
device_z_name = device_z.device if device_z else None
|
||||
|
||||
if x_name is not None:
|
||||
self.x_label = x_name # type: ignore
|
||||
x_dev = self.dev.get(x_name)
|
||||
if device_x_name is not None:
|
||||
self.x_label = device_x_name # type: ignore
|
||||
x_dev = self.dev.get(device_x_name)
|
||||
if x_dev and hasattr(x_dev, "egu"):
|
||||
self.x_label_units = x_dev.egu()
|
||||
if y_name is not None:
|
||||
self.y_label = y_name # type: ignore
|
||||
y_dev = self.dev.get(y_name)
|
||||
if device_y_name is not None:
|
||||
self.y_label = device_y_name # type: ignore
|
||||
y_dev = self.dev.get(device_y_name)
|
||||
if y_dev and hasattr(y_dev, "egu"):
|
||||
self.y_label_units = y_dev.egu()
|
||||
if z_name is not None:
|
||||
self.title = z_name
|
||||
if device_z_name is not None:
|
||||
self.title = device_z_name
|
||||
|
||||
def _init_toolbar_heatmap(self):
|
||||
"""
|
||||
@@ -572,23 +572,23 @@ class Heatmap(ImageBase):
|
||||
if self._image_config is None:
|
||||
return
|
||||
try:
|
||||
x_name = self._image_config.x_device.name
|
||||
x_entry = self._image_config.x_device.entry
|
||||
y_name = self._image_config.y_device.name
|
||||
y_entry = self._image_config.y_device.entry
|
||||
z_name = self._image_config.z_device.name
|
||||
z_entry = self._image_config.z_device.entry
|
||||
device_x = self._image_config.device_x.device
|
||||
signal_x = self._image_config.device_x.signal
|
||||
device_y = self._image_config.device_y.device
|
||||
signal_y = self._image_config.device_y.signal
|
||||
device_z = self._image_config.device_z.device
|
||||
signal_z = self._image_config.device_z.signal
|
||||
except AttributeError:
|
||||
return
|
||||
|
||||
if access_key == "val":
|
||||
x_data = data.get(x_name, {}).get(x_entry, {}).get(access_key, None)
|
||||
y_data = data.get(y_name, {}).get(y_entry, {}).get(access_key, None)
|
||||
z_data = data.get(z_name, {}).get(z_entry, {}).get(access_key, None)
|
||||
x_data = data.get(device_x, {}).get(signal_x, {}).get(access_key, None)
|
||||
y_data = data.get(device_y, {}).get(signal_y, {}).get(access_key, None)
|
||||
z_data = data.get(device_z, {}).get(signal_z, {}).get(access_key, None)
|
||||
else:
|
||||
x_data = data.get(x_name, {}).get(x_entry, {}).read().get("value", None)
|
||||
y_data = data.get(y_name, {}).get(y_entry, {}).read().get("value", None)
|
||||
z_data = data.get(z_name, {}).get(z_entry, {}).read().get("value", None)
|
||||
x_data = data.get(device_x, {}).get(signal_x, {}).read().get("value", None)
|
||||
y_data = data.get(device_y, {}).get(signal_y, {}).read().get("value", None)
|
||||
z_data = data.get(device_z, {}).get(signal_z, {}).read().get("value", None)
|
||||
|
||||
if not isinstance(x_data, list):
|
||||
x_data = x_data.tolist() if isinstance(x_data, np.ndarray) else None
|
||||
@@ -839,7 +839,6 @@ class Heatmap(ImageBase):
|
||||
x_data (np.ndarray): The x data.
|
||||
y_data (np.ndarray): The y data.
|
||||
z_data (np.ndarray): The z data.
|
||||
msg (messages.ScanStatusMessage): The scan status message.
|
||||
|
||||
Returns:
|
||||
tuple[np.ndarray, QTransform]: The image data and the QTransform.
|
||||
@@ -854,7 +853,7 @@ class Heatmap(ImageBase):
|
||||
if len(z_data) < 4:
|
||||
# LinearNDInterpolator requires at least 4 points to interpolate
|
||||
return None, None
|
||||
return self.get_step_scan_image(x_data, y_data, z_data, msg)
|
||||
return self.get_step_scan_image(x_data, y_data, z_data)
|
||||
|
||||
def _is_grid_scan_supported(self, msg: messages.ScanStatusMessage) -> bool:
|
||||
"""Check if the scan can use optimized grid_scan rendering.
|
||||
@@ -871,11 +870,11 @@ class Heatmap(ImageBase):
|
||||
if msg.scan_name != "grid_scan" or self._image_config.enforce_interpolation:
|
||||
return False
|
||||
|
||||
device_x = self._image_config.x_device.entry
|
||||
device_y = self._image_config.y_device.entry
|
||||
signal_x = self._image_config.device_x.signal
|
||||
signal_y = self._image_config.device_y.signal
|
||||
return (
|
||||
device_x in msg.request_inputs["arg_bundle"]
|
||||
and device_y in msg.request_inputs["arg_bundle"]
|
||||
signal_x in msg.request_inputs["arg_bundle"]
|
||||
and signal_y in msg.request_inputs["arg_bundle"]
|
||||
)
|
||||
|
||||
def get_grid_scan_image(
|
||||
@@ -893,9 +892,9 @@ class Heatmap(ImageBase):
|
||||
|
||||
args = self.arg_bundle_to_dict(4, msg.request_inputs["arg_bundle"])
|
||||
|
||||
x_entry = self._image_config.x_device.entry
|
||||
y_entry = self._image_config.y_device.entry
|
||||
shape = (args[x_entry][-1], args[y_entry][-1])
|
||||
signal_x = self._image_config.device_x.signal
|
||||
signal_y = self._image_config.device_y.signal
|
||||
shape = (args[signal_x][-1], args[signal_y][-1])
|
||||
|
||||
data = self.main_image.raw_data
|
||||
|
||||
@@ -925,8 +924,8 @@ class Heatmap(ImageBase):
|
||||
return origin + np.linspace(start, stop, npts)
|
||||
return np.linspace(start, stop, npts)
|
||||
|
||||
x_levels = _axis_levels(x_entry, shape[0])
|
||||
y_levels = _axis_levels(y_entry, shape[1])
|
||||
x_levels = _axis_levels(signal_x, shape[0])
|
||||
y_levels = _axis_levels(signal_y, shape[1])
|
||||
|
||||
pixel_size_x = (
|
||||
float(x_levels[-1] - x_levels[0]) / max(shape[0] - 1, 1) if shape[0] > 1 else 1.0
|
||||
@@ -949,7 +948,7 @@ class Heatmap(ImageBase):
|
||||
if snaked and (slow_i % 2 == 1):
|
||||
fast_i = args[fast_entry][-1] - 1 - fast_i
|
||||
|
||||
if x_entry == fast_entry:
|
||||
if signal_x == fast_entry:
|
||||
x_i, y_i = fast_i, slow_i
|
||||
else:
|
||||
x_i, y_i = slow_i, fast_i
|
||||
@@ -959,11 +958,7 @@ class Heatmap(ImageBase):
|
||||
return data, transform
|
||||
|
||||
def get_step_scan_image(
|
||||
self,
|
||||
x_data: list[float],
|
||||
y_data: list[float],
|
||||
z_data: list[float],
|
||||
msg: messages.ScanStatusMessage,
|
||||
self, x_data: list[float], y_data: list[float], z_data: list[float]
|
||||
) -> tuple[np.ndarray, QTransform]:
|
||||
"""
|
||||
Get the image data for an arbitrary step scan.
|
||||
@@ -972,7 +967,6 @@ class Heatmap(ImageBase):
|
||||
x_data (list[float]): The x data.
|
||||
y_data (list[float]): The y data.
|
||||
z_data (list[float]): The z data.
|
||||
msg (messages.ScanStatusMessage): The scan status message.
|
||||
|
||||
Returns:
|
||||
tuple[np.ndarray, QTransform]: The image data and the QTransform.
|
||||
@@ -1033,7 +1027,7 @@ class Heatmap(ImageBase):
|
||||
to avoid recalculating the grid for the same scan.
|
||||
|
||||
Args:
|
||||
_scan_id (str): The scan ID. Needed for caching but not used in the function.
|
||||
positions: positions of the data points.
|
||||
|
||||
Returns:
|
||||
tuple[np.ndarray, np.ndarray, QTransform]: The grid x and y coordinates and the QTransform.
|
||||
@@ -1108,11 +1102,13 @@ class Heatmap(ImageBase):
|
||||
|
||||
return max(1, width_pixels), max(1, height_pixels)
|
||||
|
||||
def arg_bundle_to_dict(self, bundle_size: int, args: list) -> dict:
|
||||
@staticmethod
|
||||
def arg_bundle_to_dict(bundle_size: int, args: list) -> dict:
|
||||
"""
|
||||
Convert the argument bundle to a dictionary.
|
||||
|
||||
Args:
|
||||
bundle_size (int): The size of each argument bundle.
|
||||
args (list): The argument bundle.
|
||||
|
||||
Returns:
|
||||
@@ -1160,14 +1156,14 @@ class Heatmap(ImageBase):
|
||||
################################################################################
|
||||
|
||||
@SafeProperty(str)
|
||||
def x_device_name(self) -> str:
|
||||
def device_x(self) -> str:
|
||||
"""Device name for the X axis."""
|
||||
if self._image_config.x_device is None:
|
||||
if self._image_config.device_x is None:
|
||||
return ""
|
||||
return self._image_config.x_device.name or ""
|
||||
return self._image_config.device_x.device or ""
|
||||
|
||||
@x_device_name.setter
|
||||
def x_device_name(self, device_name: str) -> None:
|
||||
@device_x.setter
|
||||
def device_x(self, device_name: str) -> None:
|
||||
"""
|
||||
Set the X device name.
|
||||
|
||||
@@ -1179,27 +1175,27 @@ class Heatmap(ImageBase):
|
||||
# Get current entry or validate
|
||||
if device_name:
|
||||
try:
|
||||
entry = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.x_device = HeatmapDeviceSignal(name=device_name, entry=entry)
|
||||
self.property_changed.emit("x_device_name", device_name)
|
||||
signal = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.device_x = HeatmapDeviceSignal(device=device_name, signal=signal)
|
||||
self.property_changed.emit("device_x", device_name)
|
||||
self.update_labels() # Update axis labels
|
||||
self._try_auto_plot()
|
||||
except Exception:
|
||||
pass # Silently fail if device is not available yet
|
||||
else:
|
||||
self._image_config.x_device = None
|
||||
self.property_changed.emit("x_device_name", "")
|
||||
self._image_config.device_x = None
|
||||
self.property_changed.emit("device_x", "")
|
||||
self.update_labels() # Clear axis labels
|
||||
|
||||
@SafeProperty(str)
|
||||
def x_device_entry(self) -> str:
|
||||
def signal_x(self) -> str:
|
||||
"""Signal entry for the X axis device."""
|
||||
if self._image_config.x_device is None:
|
||||
if self._image_config.device_x is None:
|
||||
return ""
|
||||
return self._image_config.x_device.entry or ""
|
||||
return self._image_config.device_x.signal or ""
|
||||
|
||||
@x_device_entry.setter
|
||||
def x_device_entry(self, entry: str) -> None:
|
||||
@signal_x.setter
|
||||
def signal_x(self, entry: str) -> None:
|
||||
"""
|
||||
Set the X device entry.
|
||||
|
||||
@@ -1209,32 +1205,32 @@ class Heatmap(ImageBase):
|
||||
if not entry:
|
||||
return
|
||||
|
||||
if self._image_config.x_device is None:
|
||||
logger.warning("Cannot set x_device_entry without x_device_name set first.")
|
||||
if self._image_config.device_x is None:
|
||||
logger.warning("Cannot set signal_x without device_x set first.")
|
||||
return
|
||||
|
||||
device_name = self._image_config.x_device.name
|
||||
device_name = self._image_config.device_x.device
|
||||
try:
|
||||
# Validate the entry for this device
|
||||
validated_entry = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.x_device = HeatmapDeviceSignal(
|
||||
name=device_name, entry=validated_entry
|
||||
validated_signal = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.device_x = HeatmapDeviceSignal(
|
||||
device=device_name, signal=validated_signal
|
||||
)
|
||||
self.property_changed.emit("x_device_entry", validated_entry)
|
||||
self.property_changed.emit("signal_x", validated_signal)
|
||||
self.update_labels() # Update axis labels
|
||||
self._try_auto_plot()
|
||||
except Exception:
|
||||
pass # Silently fail if validation fails
|
||||
|
||||
@SafeProperty(str)
|
||||
def y_device_name(self) -> str:
|
||||
def device_y(self) -> str:
|
||||
"""Device name for the Y axis."""
|
||||
if self._image_config.y_device is None:
|
||||
if self._image_config.device_y is None:
|
||||
return ""
|
||||
return self._image_config.y_device.name or ""
|
||||
return self._image_config.device_y.device or ""
|
||||
|
||||
@y_device_name.setter
|
||||
def y_device_name(self, device_name: str) -> None:
|
||||
@device_y.setter
|
||||
def device_y(self, device_name: str) -> None:
|
||||
"""
|
||||
Set the Y device name.
|
||||
|
||||
@@ -1246,27 +1242,27 @@ class Heatmap(ImageBase):
|
||||
# Get current entry or validate
|
||||
if device_name:
|
||||
try:
|
||||
entry = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.y_device = HeatmapDeviceSignal(name=device_name, entry=entry)
|
||||
self.property_changed.emit("y_device_name", device_name)
|
||||
signal = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.device_y = HeatmapDeviceSignal(device=device_name, signal=signal)
|
||||
self.property_changed.emit("device_y", device_name)
|
||||
self.update_labels() # Update axis labels
|
||||
self._try_auto_plot()
|
||||
except Exception:
|
||||
pass # Silently fail if device is not available yet
|
||||
else:
|
||||
self._image_config.y_device = None
|
||||
self.property_changed.emit("y_device_name", "")
|
||||
self._image_config.device_y = None
|
||||
self.property_changed.emit("device_y", "")
|
||||
self.update_labels() # Clear axis labels
|
||||
|
||||
@SafeProperty(str)
|
||||
def y_device_entry(self) -> str:
|
||||
def signal_y(self) -> str:
|
||||
"""Signal entry for the Y axis device."""
|
||||
if self._image_config.y_device is None:
|
||||
if self._image_config.device_y is None:
|
||||
return ""
|
||||
return self._image_config.y_device.entry or ""
|
||||
return self._image_config.device_y.signal or ""
|
||||
|
||||
@y_device_entry.setter
|
||||
def y_device_entry(self, entry: str) -> None:
|
||||
@signal_y.setter
|
||||
def signal_y(self, entry: str) -> None:
|
||||
"""
|
||||
Set the Y device entry.
|
||||
|
||||
@@ -1276,18 +1272,18 @@ class Heatmap(ImageBase):
|
||||
if not entry:
|
||||
return
|
||||
|
||||
if self._image_config.y_device is None:
|
||||
logger.warning("Cannot set y_device_entry without y_device_name set first.")
|
||||
if self._image_config.device_y is None:
|
||||
logger.warning("Cannot set signal_y without device_y set first.")
|
||||
return
|
||||
|
||||
device_name = self._image_config.y_device.name
|
||||
device_name = self._image_config.device_y.device
|
||||
try:
|
||||
# Validate the entry for this device
|
||||
validated_entry = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.y_device = HeatmapDeviceSignal(
|
||||
name=device_name, entry=validated_entry
|
||||
validated_signal = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.device_y = HeatmapDeviceSignal(
|
||||
device=device_name, signal=validated_signal
|
||||
)
|
||||
self.property_changed.emit("y_device_entry", validated_entry)
|
||||
self.property_changed.emit("signal_y", validated_signal)
|
||||
self.update_labels() # Update axis labels
|
||||
self._try_auto_plot()
|
||||
except Exception as e:
|
||||
@@ -1295,14 +1291,14 @@ class Heatmap(ImageBase):
|
||||
pass # Silently fail if validation fails
|
||||
|
||||
@SafeProperty(str)
|
||||
def z_device_name(self) -> str:
|
||||
def device_z(self) -> str:
|
||||
"""Device name for the Z (color) axis."""
|
||||
if self._image_config.z_device is None:
|
||||
if self._image_config.device_z is None:
|
||||
return ""
|
||||
return self._image_config.z_device.name or ""
|
||||
return self._image_config.device_z.device or ""
|
||||
|
||||
@z_device_name.setter
|
||||
def z_device_name(self, device_name: str) -> None:
|
||||
@device_z.setter
|
||||
def device_z(self, device_name: str) -> None:
|
||||
"""
|
||||
Set the Z device name.
|
||||
|
||||
@@ -1314,28 +1310,28 @@ class Heatmap(ImageBase):
|
||||
# Get current entry or validate
|
||||
if device_name:
|
||||
try:
|
||||
entry = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.z_device = HeatmapDeviceSignal(name=device_name, entry=entry)
|
||||
self.property_changed.emit("z_device_name", device_name)
|
||||
signal = self.entry_validator.validate_signal(device_name, None)
|
||||
self._image_config.device_z = HeatmapDeviceSignal(device=device_name, signal=signal)
|
||||
self.property_changed.emit("device_z", device_name)
|
||||
self.update_labels() # Update axis labels (title)
|
||||
self._try_auto_plot()
|
||||
except Exception as e:
|
||||
logger.debug(f"Z device name validation failed: {e}")
|
||||
pass # Silently fail if device is not available yet
|
||||
else:
|
||||
self._image_config.z_device = None
|
||||
self.property_changed.emit("z_device_name", "")
|
||||
self._image_config.device_z = None
|
||||
self.property_changed.emit("device_z", "")
|
||||
self.update_labels() # Clear axis labels
|
||||
|
||||
@SafeProperty(str)
|
||||
def z_device_entry(self) -> str:
|
||||
def signal_z(self) -> str:
|
||||
"""Signal entry for the Z (color) axis device."""
|
||||
if self._image_config.z_device is None:
|
||||
if self._image_config.device_z is None:
|
||||
return ""
|
||||
return self._image_config.z_device.entry or ""
|
||||
return self._image_config.device_z.signal or ""
|
||||
|
||||
@z_device_entry.setter
|
||||
def z_device_entry(self, entry: str) -> None:
|
||||
@signal_z.setter
|
||||
def signal_z(self, entry: str) -> None:
|
||||
"""
|
||||
Set the Z device entry.
|
||||
|
||||
@@ -1345,18 +1341,18 @@ class Heatmap(ImageBase):
|
||||
if not entry:
|
||||
return
|
||||
|
||||
if self._image_config.z_device is None:
|
||||
logger.warning("Cannot set z_device_entry without z_device_name set first.")
|
||||
if self._image_config.device_z is None:
|
||||
logger.warning("Cannot set signal_z without device_z set first.")
|
||||
return
|
||||
|
||||
device_name = self._image_config.z_device.name
|
||||
device_name = self._image_config.device_z.device
|
||||
try:
|
||||
# Validate the entry for this device
|
||||
validated_entry = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.z_device = HeatmapDeviceSignal(
|
||||
name=device_name, entry=validated_entry
|
||||
validated_signal = self.entry_validator.validate_signal(device_name, entry)
|
||||
self._image_config.device_z = HeatmapDeviceSignal(
|
||||
device=device_name, signal=validated_signal
|
||||
)
|
||||
self.property_changed.emit("z_device_entry", validated_entry)
|
||||
self.property_changed.emit("signal_z", validated_signal)
|
||||
self.update_labels() # Update axis labels (title)
|
||||
self._try_auto_plot()
|
||||
except Exception as e:
|
||||
@@ -1368,25 +1364,25 @@ class Heatmap(ImageBase):
|
||||
Attempt to automatically call plot() if all three devices are set.
|
||||
Similar to waveform's approach but requires all three devices.
|
||||
"""
|
||||
has_x = self._image_config.x_device is not None
|
||||
has_y = self._image_config.y_device is not None
|
||||
has_z = self._image_config.z_device is not None
|
||||
has_x = self._image_config.device_x is not None
|
||||
has_y = self._image_config.device_y is not None
|
||||
has_z = self._image_config.device_z is not None
|
||||
|
||||
if has_x and has_y and has_z:
|
||||
x_name = self._image_config.x_device.name
|
||||
x_entry = self._image_config.x_device.entry
|
||||
y_name = self._image_config.y_device.name
|
||||
y_entry = self._image_config.y_device.entry
|
||||
z_name = self._image_config.z_device.name
|
||||
z_entry = self._image_config.z_device.entry
|
||||
device_x = self._image_config.device_x.device
|
||||
signal_x = self._image_config.device_x.signal
|
||||
device_y = self._image_config.device_y.device
|
||||
signal_y = self._image_config.device_y.signal
|
||||
device_z = self._image_config.device_z.device
|
||||
signal_z = self._image_config.device_z.signal
|
||||
try:
|
||||
self.plot(
|
||||
x_name=x_name,
|
||||
y_name=y_name,
|
||||
z_name=z_name,
|
||||
x_entry=x_entry,
|
||||
y_entry=y_entry,
|
||||
z_entry=z_entry,
|
||||
device_x=device_x,
|
||||
device_y=device_y,
|
||||
device_z=device_z,
|
||||
signal_x=signal_x,
|
||||
signal_y=signal_y,
|
||||
signal_z=signal_z,
|
||||
validate_bec=False, # Don't validate - entries already validated
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -1533,6 +1529,6 @@ if __name__ == "__main__": # pragma: no cover
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
heatmap = Heatmap()
|
||||
heatmap.plot(x_name="samx", y_name="samy", z_name="bpm4i", oversampling_factor=5.0)
|
||||
heatmap.plot(device_x="samx", device_y="samy", device_z="bpm4i", oversampling_factor=5.0)
|
||||
heatmap.show()
|
||||
sys.exit(app.exec_())
|
||||
|
||||
@@ -48,7 +48,7 @@ class HeatmapSettings(SettingWidget):
|
||||
if popup is False:
|
||||
self.ui.button_apply.clicked.connect(self.accept_changes)
|
||||
|
||||
self.ui.x_name.setFocus()
|
||||
self.ui.device_x.setFocus()
|
||||
|
||||
@SafeSlot()
|
||||
def fetch_all_properties(self):
|
||||
@@ -62,44 +62,44 @@ class HeatmapSettings(SettingWidget):
|
||||
color_map = getattr(self.target_widget, "color_map", None)
|
||||
|
||||
# Default values for device properties
|
||||
x_name, x_entry = None, None
|
||||
y_name, y_entry = None, None
|
||||
z_name, z_entry = None, None
|
||||
device_x, signal_x = None, None
|
||||
device_y, signal_y = None, None
|
||||
device_z, signal_z = None, None
|
||||
|
||||
# Safely access device properties
|
||||
if hasattr(self.target_widget, "_image_config") and self.target_widget._image_config:
|
||||
config = self.target_widget._image_config
|
||||
|
||||
if hasattr(config, "x_device") and config.x_device:
|
||||
x_name = getattr(config.x_device, "name", None)
|
||||
x_entry = getattr(config.x_device, "entry", None)
|
||||
if hasattr(config, "device_x") and config.device_x:
|
||||
device_x = getattr(config.device_x, "device", None)
|
||||
signal_x = getattr(config.device_x, "signal", None)
|
||||
|
||||
if hasattr(config, "y_device") and config.y_device:
|
||||
y_name = getattr(config.y_device, "name", None)
|
||||
y_entry = getattr(config.y_device, "entry", None)
|
||||
if hasattr(config, "device_y") and config.device_y:
|
||||
device_y = getattr(config.device_y, "device", None)
|
||||
signal_y = getattr(config.device_y, "signal", None)
|
||||
|
||||
if hasattr(config, "z_device") and config.z_device:
|
||||
z_name = getattr(config.z_device, "name", None)
|
||||
z_entry = getattr(config.z_device, "entry", None)
|
||||
if hasattr(config, "device_z") and config.device_z:
|
||||
device_z = getattr(config.device_z, "device", None)
|
||||
signal_z = getattr(config.device_z, "signal", None)
|
||||
|
||||
# Apply the properties to the settings widget
|
||||
if hasattr(self.ui, "color_map"):
|
||||
self.ui.color_map.colormap = color_map
|
||||
|
||||
if hasattr(self.ui, "x_name"):
|
||||
self.ui.x_name.set_device(x_name)
|
||||
if hasattr(self.ui, "x_entry") and x_entry is not None:
|
||||
self.ui.x_entry.set_to_obj_name(x_entry)
|
||||
if hasattr(self.ui, "device_x"):
|
||||
self.ui.device_x.set_device(device_x)
|
||||
if hasattr(self.ui, "signal_x") and signal_x is not None:
|
||||
self.ui.signal_x.set_to_obj_name(signal_x)
|
||||
|
||||
if hasattr(self.ui, "y_name"):
|
||||
self.ui.y_name.set_device(y_name)
|
||||
if hasattr(self.ui, "y_entry") and y_entry is not None:
|
||||
self.ui.y_entry.set_to_obj_name(y_entry)
|
||||
if hasattr(self.ui, "device_y"):
|
||||
self.ui.device_y.set_device(device_y)
|
||||
if hasattr(self.ui, "signal_y") and signal_y is not None:
|
||||
self.ui.signal_y.set_to_obj_name(signal_y)
|
||||
|
||||
if hasattr(self.ui, "z_name"):
|
||||
self.ui.z_name.set_device(z_name)
|
||||
if hasattr(self.ui, "z_entry") and z_entry is not None:
|
||||
self.ui.z_entry.set_to_obj_name(z_entry)
|
||||
if hasattr(self.ui, "device_z"):
|
||||
self.ui.device_z.set_device(device_z)
|
||||
if hasattr(self.ui, "signal_z") and signal_z is not None:
|
||||
self.ui.signal_z.set_to_obj_name(signal_z)
|
||||
|
||||
if hasattr(self.ui, "interpolation"):
|
||||
self.ui.interpolation.setCurrentText(
|
||||
@@ -119,12 +119,12 @@ class HeatmapSettings(SettingWidget):
|
||||
"""
|
||||
Apply all properties from the settings widget to the target widget.
|
||||
"""
|
||||
x_name = self.ui.x_name.currentText()
|
||||
x_entry = self.ui.x_entry.get_signal_name()
|
||||
y_name = self.ui.y_name.currentText()
|
||||
y_entry = self.ui.y_entry.get_signal_name()
|
||||
z_name = self.ui.z_name.currentText()
|
||||
z_entry = self.ui.z_entry.get_signal_name()
|
||||
device_x = self.ui.device_x.currentText()
|
||||
signal_x = self.ui.signal_x.get_signal_name()
|
||||
device_y = self.ui.device_y.currentText()
|
||||
signal_y = self.ui.signal_y.get_signal_name()
|
||||
device_z = self.ui.device_z.currentText()
|
||||
signal_z = self.ui.signal_z.get_signal_name()
|
||||
validate_bec = self.ui.validate_bec.checked
|
||||
color_map = self.ui.color_map.colormap
|
||||
interpolation = self.ui.interpolation.currentText()
|
||||
@@ -132,12 +132,12 @@ class HeatmapSettings(SettingWidget):
|
||||
enforce_interpolation = self.ui.enforce_interpolation.isChecked()
|
||||
|
||||
self.target_widget.plot(
|
||||
x_name=x_name,
|
||||
y_name=y_name,
|
||||
z_name=z_name,
|
||||
x_entry=x_entry,
|
||||
y_entry=y_entry,
|
||||
z_entry=z_entry,
|
||||
device_x=device_x,
|
||||
device_y=device_y,
|
||||
device_z=device_z,
|
||||
signal_x=signal_x,
|
||||
signal_y=signal_y,
|
||||
signal_z=signal_z,
|
||||
color_map=color_map,
|
||||
validate_bec=validate_bec,
|
||||
interpolation=interpolation,
|
||||
@@ -147,17 +147,17 @@ class HeatmapSettings(SettingWidget):
|
||||
)
|
||||
|
||||
def cleanup(self):
|
||||
self.ui.x_name.close()
|
||||
self.ui.x_name.deleteLater()
|
||||
self.ui.x_entry.close()
|
||||
self.ui.x_entry.deleteLater()
|
||||
self.ui.y_name.close()
|
||||
self.ui.y_name.deleteLater()
|
||||
self.ui.y_entry.close()
|
||||
self.ui.y_entry.deleteLater()
|
||||
self.ui.z_name.close()
|
||||
self.ui.z_name.deleteLater()
|
||||
self.ui.z_entry.close()
|
||||
self.ui.z_entry.deleteLater()
|
||||
self.ui.device_x.close()
|
||||
self.ui.device_x.deleteLater()
|
||||
self.ui.signal_x.close()
|
||||
self.ui.signal_x.deleteLater()
|
||||
self.ui.device_y.close()
|
||||
self.ui.device_y.deleteLater()
|
||||
self.ui.signal_y.close()
|
||||
self.ui.signal_y.deleteLater()
|
||||
self.ui.device_z.close()
|
||||
self.ui.device_z.deleteLater()
|
||||
self.ui.signal_z.close()
|
||||
self.ui.signal_z.deleteLater()
|
||||
self.ui.interpolation.close()
|
||||
self.ui.interpolation.deleteLater()
|
||||
|
||||
@@ -196,7 +196,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="x_name">
|
||||
<widget class="DeviceComboBox" name="device_x">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -206,7 +206,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="x_entry">
|
||||
<widget class="SignalComboBox" name="signal_x">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -236,7 +236,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="y_name">
|
||||
<widget class="DeviceComboBox" name="device_y">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -246,7 +246,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="y_entry">
|
||||
<widget class="SignalComboBox" name="signal_y">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -276,7 +276,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="z_name">
|
||||
<widget class="DeviceComboBox" name="device_z">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -286,7 +286,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="z_entry">
|
||||
<widget class="SignalComboBox" name="signal_z">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -322,21 +322,21 @@
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<tabstops>
|
||||
<tabstop>x_name</tabstop>
|
||||
<tabstop>y_name</tabstop>
|
||||
<tabstop>z_name</tabstop>
|
||||
<tabstop>x_entry</tabstop>
|
||||
<tabstop>y_entry</tabstop>
|
||||
<tabstop>z_entry</tabstop>
|
||||
<tabstop>device_x</tabstop>
|
||||
<tabstop>device_y</tabstop>
|
||||
<tabstop>device_z</tabstop>
|
||||
<tabstop>signal_x</tabstop>
|
||||
<tabstop>signal_y</tabstop>
|
||||
<tabstop>signal_z</tabstop>
|
||||
<tabstop>interpolation</tabstop>
|
||||
<tabstop>oversampling_factor</tabstop>
|
||||
</tabstops>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>x_name</sender>
|
||||
<sender>device_x</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>x_entry</receiver>
|
||||
<receiver>signal_x</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -350,9 +350,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>x_name</sender>
|
||||
<sender>device_x</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>x_entry</receiver>
|
||||
<receiver>signal_x</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -366,9 +366,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>y_name</sender>
|
||||
<sender>device_y</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>y_entry</receiver>
|
||||
<receiver>signal_y</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -382,9 +382,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>y_name</sender>
|
||||
<sender>device_y</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>y_entry</receiver>
|
||||
<receiver>signal_y</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -398,9 +398,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>z_name</sender>
|
||||
<sender>device_z</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>z_entry</receiver>
|
||||
<receiver>signal_z</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -414,9 +414,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>z_name</sender>
|
||||
<sender>device_z</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>z_entry</receiver>
|
||||
<receiver>signal_z</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="x_name">
|
||||
<widget class="DeviceComboBox" name="device_x">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -79,7 +79,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="x_entry">
|
||||
<widget class="SignalComboBox" name="signal_x">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -109,7 +109,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="y_name">
|
||||
<widget class="DeviceComboBox" name="device_y">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -119,7 +119,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="y_entry">
|
||||
<widget class="SignalComboBox" name="signal_y">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -142,7 +142,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="DeviceComboBox" name="z_name">
|
||||
<widget class="DeviceComboBox" name="device_z">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -152,7 +152,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="SignalComboBox" name="z_entry">
|
||||
<widget class="SignalComboBox" name="signal_z">
|
||||
<property name="editable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
@@ -264,20 +264,20 @@
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<tabstops>
|
||||
<tabstop>x_name</tabstop>
|
||||
<tabstop>y_name</tabstop>
|
||||
<tabstop>z_name</tabstop>
|
||||
<tabstop>device_x</tabstop>
|
||||
<tabstop>device_y</tabstop>
|
||||
<tabstop>device_z</tabstop>
|
||||
<tabstop>button_apply</tabstop>
|
||||
<tabstop>x_entry</tabstop>
|
||||
<tabstop>y_entry</tabstop>
|
||||
<tabstop>z_entry</tabstop>
|
||||
<tabstop>signal_x</tabstop>
|
||||
<tabstop>signal_y</tabstop>
|
||||
<tabstop>signal_z</tabstop>
|
||||
</tabstops>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>x_name</sender>
|
||||
<sender>device_x</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>x_entry</receiver>
|
||||
<receiver>signal_x</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -291,9 +291,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>x_name</sender>
|
||||
<sender>device_x</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>x_entry</receiver>
|
||||
<receiver>signal_x</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -307,9 +307,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>y_name</sender>
|
||||
<sender>device_y</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>y_entry</receiver>
|
||||
<receiver>signal_y</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -323,9 +323,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>y_name</sender>
|
||||
<sender>device_y</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>y_entry</receiver>
|
||||
<receiver>signal_y</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -339,9 +339,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>z_name</sender>
|
||||
<sender>device_z</sender>
|
||||
<signal>device_reset()</signal>
|
||||
<receiver>z_entry</receiver>
|
||||
<receiver>signal_z</receiver>
|
||||
<slot>reset_selection()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
@@ -355,9 +355,9 @@
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>z_name</sender>
|
||||
<sender>device_z</sender>
|
||||
<signal>currentTextChanged(QString)</signal>
|
||||
<receiver>z_entry</receiver>
|
||||
<receiver>signal_z</receiver>
|
||||
<slot>set_device(QString)</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
|
||||
@@ -42,8 +42,8 @@ class ImageConfig(ConnectionConfig):
|
||||
|
||||
|
||||
class ImageLayerConfig(BaseModel):
|
||||
device_name: str = Field("", description="The device name to monitor.")
|
||||
device_entry: str = Field("", description="The signal/entry name to monitor on the device.")
|
||||
device: str = Field("", description="The device name to monitor.")
|
||||
signal: str = Field("", description="The signal/entry name to monitor on the device.")
|
||||
monitor_type: Literal["1d", "2d"] | None = Field(None, description="The type of monitor.")
|
||||
source: Literal["device_monitor_1d", "device_monitor_2d"] | None = Field(
|
||||
None, description="The source of the image data."
|
||||
@@ -80,10 +80,10 @@ class Image(ImageBase):
|
||||
"autorange.setter",
|
||||
"autorange_mode",
|
||||
"autorange_mode.setter",
|
||||
"device_name",
|
||||
"device_name.setter",
|
||||
"device_entry",
|
||||
"device_entry.setter",
|
||||
"device",
|
||||
"device.setter",
|
||||
"signal",
|
||||
"signal.setter",
|
||||
"enable_colorbar",
|
||||
"enable_simple_colorbar",
|
||||
"enable_simple_colorbar.setter",
|
||||
@@ -206,19 +206,19 @@ class Image(ImageBase):
|
||||
signal_text = device_selection.signal_combo_box.currentText()
|
||||
|
||||
if not device:
|
||||
self.device_name = ""
|
||||
self.device = ""
|
||||
return
|
||||
if not device_selection.device_combo_box.is_valid_input:
|
||||
return
|
||||
|
||||
if not device_selection.signal_combo_box.is_valid_input:
|
||||
if self._config.device_entry:
|
||||
self.device_entry = ""
|
||||
if device != self._config.device_name:
|
||||
self.device_name = device
|
||||
if self._config.signal:
|
||||
self.signal = ""
|
||||
if device != self._config.device:
|
||||
self.device = device
|
||||
return
|
||||
|
||||
if device == self._config.device_name and signal_text == self._config.device_entry:
|
||||
if device == self._config.device and signal_text == self._config.signal:
|
||||
return
|
||||
|
||||
# Get the signal config stored in the combobox
|
||||
@@ -235,8 +235,8 @@ class Image(ImageBase):
|
||||
|
||||
# Store signal config and set properties which will trigger the connection
|
||||
self._signal_configs["main"] = signal_config
|
||||
self.device_name = device
|
||||
self.device_entry = signal_text
|
||||
self.device = device
|
||||
self.signal = signal_text
|
||||
finally:
|
||||
self._device_selection_updating = False
|
||||
|
||||
@@ -244,55 +244,63 @@ class Image(ImageBase):
|
||||
# Data Acquisition
|
||||
|
||||
@SafeProperty(str, auto_emit=True)
|
||||
def device_name(self) -> str:
|
||||
def device(self) -> str:
|
||||
"""
|
||||
The name of the device to monitor for image data.
|
||||
"""
|
||||
return self._config.device_name
|
||||
return self._config.device
|
||||
|
||||
@device_name.setter
|
||||
def device_name(self, value: str):
|
||||
@device.setter
|
||||
def device(self, value: str):
|
||||
"""
|
||||
Set the device name for the image. This should be used together with device_entry.
|
||||
When both device_name and device_entry are set, the widget connects to that device signal.
|
||||
Set the device name for the image. This should be used together with signal.
|
||||
When both device and signal are set, the widget connects to that device signal.
|
||||
|
||||
Args:
|
||||
value(str): The name of the device to monitor.
|
||||
"""
|
||||
if not value:
|
||||
# Clear the monitor if empty device name
|
||||
if self._config.device_name:
|
||||
if self._config.device:
|
||||
self._disconnect_current_monitor()
|
||||
self._config.device_name = ""
|
||||
self._config.device_entry = ""
|
||||
self._config.device = ""
|
||||
self._config.signal = ""
|
||||
self._signal_configs.pop("main", None)
|
||||
self._set_connection_status("disconnected")
|
||||
return
|
||||
|
||||
old_device = self._config.device_name
|
||||
self._config.device_name = value
|
||||
old_device = self._config.device
|
||||
old_signal = self._config.signal
|
||||
old_config = self.subscriptions["main"]
|
||||
if old_device and old_signal and old_device != value:
|
||||
self._disconnect_monitor_subscription(
|
||||
device=old_device,
|
||||
signal=old_signal,
|
||||
source=old_config.source,
|
||||
async_update=self.async_update,
|
||||
async_signal_name=old_config.async_signal_name,
|
||||
)
|
||||
self._config.device = value
|
||||
|
||||
# If we have a device_entry, reconnect with the new device
|
||||
if self._config.device_entry:
|
||||
# If we have a signal, reconnect with the new device
|
||||
if self._config.signal:
|
||||
# Try to get fresh signal config for the new device
|
||||
try:
|
||||
device_obj = self.dev[value]
|
||||
# Try to get signal config for the current entry
|
||||
if self._config.device_entry in device_obj._info.get("signals", {}):
|
||||
self._signal_configs["main"] = device_obj._info["signals"][
|
||||
self._config.device_entry
|
||||
]
|
||||
if self._config.signal in device_obj._info.get("signals", {}):
|
||||
self._signal_configs["main"] = device_obj._info["signals"][self._config.signal]
|
||||
self._setup_connection()
|
||||
else:
|
||||
# Signal doesn't exist on new device
|
||||
logger.warning(
|
||||
f"Signal '{self._config.device_entry}' doesn't exist on device '{value}'"
|
||||
f"Signal '{self._config.signal}' doesn't exist on device '{value}'"
|
||||
)
|
||||
self._disconnect_current_monitor()
|
||||
self._config.device_entry = ""
|
||||
self._config.signal = ""
|
||||
self._signal_configs.pop("main", None)
|
||||
self._set_connection_status(
|
||||
"error", f"Signal '{self._config.device_entry}' doesn't exist"
|
||||
"error", f"Signal '{self._config.signal}' doesn't exist"
|
||||
)
|
||||
except (KeyError, AttributeError):
|
||||
# Device doesn't exist
|
||||
@@ -304,40 +312,50 @@ class Image(ImageBase):
|
||||
# Toolbar sync happens via SafeProperty auto_emit property_changed handling.
|
||||
|
||||
@SafeProperty(str, auto_emit=True)
|
||||
def device_entry(self) -> str:
|
||||
def signal(self) -> str:
|
||||
"""
|
||||
The signal/entry name to monitor on the device.
|
||||
"""
|
||||
return self._config.device_entry
|
||||
return self._config.signal
|
||||
|
||||
@device_entry.setter
|
||||
def device_entry(self, value: str):
|
||||
@signal.setter
|
||||
def signal(self, value: str):
|
||||
"""
|
||||
Set the device entry (signal) for the image. This should be used together with device_name.
|
||||
Set the device signal for the image. This should be used together with device.
|
||||
When set, it will connect to updates from that device signal.
|
||||
|
||||
Args:
|
||||
value(str): The signal name to monitor.
|
||||
"""
|
||||
if not value:
|
||||
if self._config.device_entry:
|
||||
if self._config.signal:
|
||||
self._disconnect_current_monitor()
|
||||
self._config.device_entry = ""
|
||||
self._config.signal = ""
|
||||
self._signal_configs.pop("main", None)
|
||||
self._set_connection_status("disconnected")
|
||||
return
|
||||
|
||||
self._config.device_entry = value
|
||||
old_signal = self._config.signal
|
||||
old_config = self.subscriptions["main"]
|
||||
if self._config.device and old_signal and old_signal != value:
|
||||
self._disconnect_monitor_subscription(
|
||||
device=self._config.device,
|
||||
signal=old_signal,
|
||||
source=old_config.source,
|
||||
async_update=self.async_update,
|
||||
async_signal_name=old_config.async_signal_name,
|
||||
)
|
||||
self._config.signal = value
|
||||
|
||||
# If we have a device_name, try to connect
|
||||
if self._config.device_name:
|
||||
# If we have a device, try to connect
|
||||
if self._config.device:
|
||||
try:
|
||||
device_obj = self.dev[self._config.device_name]
|
||||
device_obj = self.dev[self._config.device]
|
||||
signal_config = device_obj._info["signals"].get(value)
|
||||
if not isinstance(signal_config, dict) or not signal_config.get("signal_class"):
|
||||
logger.warning(
|
||||
f"Could not find valid configuration for signal '{value}' "
|
||||
f"on device '{self._config.device_name}'."
|
||||
f"on device '{self._config.device}'."
|
||||
)
|
||||
self._signal_configs.pop("main", None)
|
||||
self._set_connection_status("error", f"Signal '{value}' not found")
|
||||
@@ -347,14 +365,14 @@ class Image(ImageBase):
|
||||
self._setup_connection()
|
||||
except (KeyError, AttributeError):
|
||||
logger.warning(
|
||||
f"Could not find signal '{value}' on device '{self._config.device_name}'."
|
||||
f"Could not find signal '{value}' on device '{self._config.device}'."
|
||||
)
|
||||
# Remove signal config if it can't be fetched
|
||||
self._signal_configs.pop("main", None)
|
||||
self._set_connection_status("error", f"Signal '{value}' not found")
|
||||
|
||||
else:
|
||||
logger.debug(f"device_entry setter: No device set yet for signal '{value}'")
|
||||
logger.debug(f"signal setter: No device set yet for signal '{value}'")
|
||||
|
||||
@property
|
||||
def main_image(self) -> ImageItem:
|
||||
@@ -363,17 +381,17 @@ class Image(ImageBase):
|
||||
|
||||
def _setup_connection(self):
|
||||
"""
|
||||
Internal method to setup connection based on current device_name, device_entry, and signal_config.
|
||||
Internal method to setup connection based on current device, signal, and signal_config.
|
||||
"""
|
||||
if not self._config.device_name or not self._config.device_entry:
|
||||
logger.warning("Cannot setup connection without both device_name and device_entry")
|
||||
if not self._config.device or not self._config.signal:
|
||||
logger.warning("Cannot setup connection without both device and signal")
|
||||
self._set_connection_status("disconnected")
|
||||
return
|
||||
|
||||
signal_config = self._signal_configs.get("main")
|
||||
if not signal_config:
|
||||
logger.warning(
|
||||
f"Cannot setup connection for {self._config.device_name}.{self._config.device_entry} without signal_config"
|
||||
f"Cannot setup connection for {self._config.device}.{self._config.signal} without signal_config"
|
||||
)
|
||||
self._set_connection_status("error", "Missing signal config")
|
||||
return
|
||||
@@ -387,7 +405,7 @@ class Image(ImageBase):
|
||||
|
||||
if signal_class not in supported_classes:
|
||||
logger.warning(
|
||||
f"Signal '{self._config.device_name}.{self._config.device_entry}' has unsupported signal class '{signal_class}'. "
|
||||
f"Signal '{self._config.device}.{self._config.signal}' has unsupported signal class '{signal_class}'. "
|
||||
f"Supported classes: {supported_classes}"
|
||||
)
|
||||
self._set_connection_status("error", f"Unsupported signal class '{signal_class}'")
|
||||
@@ -399,7 +417,7 @@ class Image(ImageBase):
|
||||
|
||||
if ndim is None:
|
||||
logger.warning(
|
||||
f"Signal '{self._config.device_name}.{self._config.device_entry}' does not have a valid 'ndim' in its signal_info."
|
||||
f"Signal '{self._config.device}.{self._config.signal}' does not have a valid 'ndim' in its signal_info."
|
||||
)
|
||||
self._set_connection_status("error", "Missing ndim in signal_info")
|
||||
return
|
||||
@@ -414,14 +432,12 @@ class Image(ImageBase):
|
||||
if signal_class == "PreviewSignal":
|
||||
self.bec_dispatcher.connect_slot(
|
||||
self.on_image_update_1d,
|
||||
MessageEndpoints.device_preview(
|
||||
self._config.device_name, self._config.device_entry
|
||||
),
|
||||
MessageEndpoints.device_preview(self._config.device, self._config.signal),
|
||||
)
|
||||
elif signal_class in self.SUPPORTED_SIGNALS:
|
||||
self.async_update = True
|
||||
config.async_signal_name = signal_config.get(
|
||||
"obj_name", f"{self._config.device_name}_{self._config.device_entry}"
|
||||
"obj_name", f"{self._config.device}_{self._config.signal}"
|
||||
)
|
||||
self._setup_async_image(self.scan_id)
|
||||
elif ndim == 2:
|
||||
@@ -430,90 +446,97 @@ class Image(ImageBase):
|
||||
if signal_class == "PreviewSignal":
|
||||
self.bec_dispatcher.connect_slot(
|
||||
self.on_image_update_2d,
|
||||
MessageEndpoints.device_preview(
|
||||
self._config.device_name, self._config.device_entry
|
||||
),
|
||||
MessageEndpoints.device_preview(self._config.device, self._config.signal),
|
||||
)
|
||||
elif signal_class in self.SUPPORTED_SIGNALS:
|
||||
self.async_update = True
|
||||
config.async_signal_name = signal_config.get(
|
||||
"obj_name", f"{self._config.device_name}_{self._config.device_entry}"
|
||||
"obj_name", f"{self._config.device}_{self._config.signal}"
|
||||
)
|
||||
self._setup_async_image(self.scan_id)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Unsupported ndim '{ndim}' for monitor '{self._config.device_name}.{self._config.device_entry}'."
|
||||
f"Unsupported ndim '{ndim}' for monitor '{self._config.device}.{self._config.signal}'."
|
||||
)
|
||||
self._set_connection_status("error", f"Unsupported ndim '{ndim}'")
|
||||
return
|
||||
|
||||
self._set_connection_status("connected")
|
||||
logger.info(
|
||||
f"Connected to {self._config.device_name}.{self._config.device_entry} with type {config.monitor_type}"
|
||||
f"Connected to {self._config.device}.{self._config.signal} with type {config.monitor_type}"
|
||||
)
|
||||
self._autorange_on_next_update = True
|
||||
|
||||
def _disconnect_current_monitor(self):
|
||||
"""
|
||||
Internal method to disconnect the current monitor subscriptions.
|
||||
"""
|
||||
if not self._config.device_name or not self._config.device_entry:
|
||||
def _disconnect_monitor_subscription(
|
||||
self,
|
||||
*,
|
||||
device: str,
|
||||
signal: str,
|
||||
source: Literal["device_monitor_1d", "device_monitor_2d"] | None,
|
||||
async_update: bool,
|
||||
async_signal_name: str | None,
|
||||
) -> None:
|
||||
if not device or not signal:
|
||||
return
|
||||
|
||||
config = self.subscriptions["main"]
|
||||
|
||||
if self.async_update:
|
||||
async_signal_name = config.async_signal_name or self._config.device_entry
|
||||
if async_update:
|
||||
async_signal_name = async_signal_name or signal
|
||||
ids_to_check = [self.scan_id, self.old_scan_id]
|
||||
|
||||
if config.source == "device_monitor_1d":
|
||||
if source == "device_monitor_1d":
|
||||
for scan_id in ids_to_check:
|
||||
if scan_id is None:
|
||||
continue
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_1d,
|
||||
MessageEndpoints.device_async_signal(
|
||||
scan_id, self._config.device_name, async_signal_name
|
||||
),
|
||||
MessageEndpoints.device_async_signal(scan_id, device, async_signal_name),
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting 1d update ScanID:{scan_id}, Device Name:{self._config.device_name},Device Entry:{async_signal_name}"
|
||||
f"Disconnecting 1d update ScanID:{scan_id}, Device Name:{device},Device Entry:{async_signal_name}"
|
||||
)
|
||||
elif config.source == "device_monitor_2d":
|
||||
elif source == "device_monitor_2d":
|
||||
for scan_id in ids_to_check:
|
||||
if scan_id is None:
|
||||
continue
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_2d,
|
||||
MessageEndpoints.device_async_signal(
|
||||
scan_id, self._config.device_name, async_signal_name
|
||||
),
|
||||
MessageEndpoints.device_async_signal(scan_id, device, async_signal_name),
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting 2d update ScanID:{scan_id}, Device Name:{self._config.device_name},Device Entry:{async_signal_name}"
|
||||
f"Disconnecting 2d update ScanID:{scan_id}, Device Name:{device},Device Entry:{async_signal_name}"
|
||||
)
|
||||
return
|
||||
|
||||
else:
|
||||
if config.source == "device_monitor_1d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_1d,
|
||||
MessageEndpoints.device_preview(
|
||||
self._config.device_name, self._config.device_entry
|
||||
),
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting preview 1d update Device Name:{self._config.device_name}, Device Entry:{self._config.device_entry}"
|
||||
)
|
||||
elif config.source == "device_monitor_2d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_2d,
|
||||
MessageEndpoints.device_preview(
|
||||
self._config.device_name, self._config.device_entry
|
||||
),
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting preview 2d update Device Name:{self._config.device_name}, Device Entry:{self._config.device_entry}"
|
||||
)
|
||||
if source == "device_monitor_1d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_1d, MessageEndpoints.device_preview(device, signal)
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting preview 1d update Device Name:{device}, Device Entry:{signal}"
|
||||
)
|
||||
elif source == "device_monitor_2d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_2d, MessageEndpoints.device_preview(device, signal)
|
||||
)
|
||||
logger.info(
|
||||
f"Disconnecting preview 2d update Device Name:{device}, Device Entry:{signal}"
|
||||
)
|
||||
|
||||
def _disconnect_current_monitor(self):
|
||||
"""
|
||||
Internal method to disconnect the current monitor subscriptions.
|
||||
"""
|
||||
if not self._config.device or not self._config.signal:
|
||||
return
|
||||
|
||||
config = self.subscriptions["main"]
|
||||
self._disconnect_monitor_subscription(
|
||||
device=self._config.device,
|
||||
signal=self._config.signal,
|
||||
source=config.source,
|
||||
async_update=self.async_update,
|
||||
async_signal_name=config.async_signal_name,
|
||||
)
|
||||
|
||||
# Reset async state
|
||||
self.async_update = False
|
||||
@@ -526,8 +549,8 @@ class Image(ImageBase):
|
||||
@SafeSlot(popup_error=True)
|
||||
def image(
|
||||
self,
|
||||
device_name: str | None = None,
|
||||
device_entry: str | None = None,
|
||||
device: str | None = None,
|
||||
signal: str | None = None,
|
||||
color_map: str | None = None,
|
||||
color_bar: Literal["simple", "full"] | None = None,
|
||||
vrange: tuple[int, int] | None = None,
|
||||
@@ -536,8 +559,8 @@ class Image(ImageBase):
|
||||
Set the image source and update the image.
|
||||
|
||||
Args:
|
||||
device_name(str|None): The name of the device to monitor. If None or empty string, the current monitor will be disconnected.
|
||||
device_entry(str|None): The signal/entry name to monitor on the device.
|
||||
device(str|None): The name of the device to monitor. If None or empty string, the current monitor will be disconnected.
|
||||
signal(str|None): The signal/entry name to monitor on the device.
|
||||
color_map(str): The color map to use for the image.
|
||||
color_bar(str): The type of color bar to use. Options are "simple" or "full".
|
||||
vrange(tuple): The range of values to use for the color map.
|
||||
@@ -546,27 +569,27 @@ class Image(ImageBase):
|
||||
ImageItem: The image object, or None if connection failed.
|
||||
"""
|
||||
# Disconnect existing monitor if any
|
||||
if self._config.device_name and self._config.device_entry:
|
||||
if self._config.device and self._config.signal:
|
||||
self._disconnect_current_monitor()
|
||||
|
||||
if not device_name or not device_entry:
|
||||
if device_name or device_entry:
|
||||
logger.warning("Both device_name and device_entry must be specified")
|
||||
if not device or not signal:
|
||||
if device or signal:
|
||||
logger.warning("Both device and signal must be specified")
|
||||
else:
|
||||
logger.info("Disconnecting image monitor")
|
||||
self.device_name = ""
|
||||
self.device = ""
|
||||
return None
|
||||
|
||||
# Validate device
|
||||
self.entry_validator.validate_monitor(device_name)
|
||||
self.entry_validator.validate_monitor(device)
|
||||
|
||||
# Clear old entry first to avoid reconnect attempts on the new device
|
||||
if self._config.device_entry:
|
||||
self.device_entry = ""
|
||||
if self._config.signal:
|
||||
self.signal = ""
|
||||
|
||||
# Set properties to trigger connection
|
||||
self.device_name = device_name
|
||||
self.device_entry = device_entry
|
||||
self.device = device
|
||||
self.signal = signal
|
||||
|
||||
# Apply visual settings
|
||||
if color_map is not None:
|
||||
@@ -581,7 +604,7 @@ class Image(ImageBase):
|
||||
def _sync_device_selection(self):
|
||||
"""
|
||||
Synchronize the device and signal comboboxes with the current monitor state.
|
||||
This ensures the toolbar reflects the device_name and device_entry properties.
|
||||
This ensures the toolbar reflects the device and signal properties.
|
||||
"""
|
||||
try:
|
||||
device_selection_action = self.toolbar.components.get_action("device_selection")
|
||||
@@ -593,8 +616,8 @@ class Image(ImageBase):
|
||||
return
|
||||
|
||||
device_selection: DeviceSelection = device_selection_action.widget
|
||||
target_device = self._config.device_name or ""
|
||||
target_entry = self._config.device_entry or ""
|
||||
target_device = self._config.device or ""
|
||||
target_entry = self._config.signal or ""
|
||||
|
||||
# Check if already synced
|
||||
if (
|
||||
@@ -605,15 +628,15 @@ class Image(ImageBase):
|
||||
|
||||
device_selection.set_device_and_signal(target_device, target_entry)
|
||||
|
||||
def _sync_device_entry_from_toolbar(self) -> None:
|
||||
def _sync_signal_from_toolbar(self) -> None:
|
||||
"""
|
||||
Pull the signal selection from the toolbar if it differs from the current device_entry.
|
||||
This keeps CLI-driven device_name updates in sync with the signal combobox state.
|
||||
Pull the signal selection from the toolbar if it differs from the current signal.
|
||||
This keeps CLI-driven device updates in sync with the signal combobox state.
|
||||
"""
|
||||
if self._device_selection_updating:
|
||||
return
|
||||
|
||||
if not self._config.device_name:
|
||||
if not self._config.device:
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -625,17 +648,17 @@ class Image(ImageBase):
|
||||
return
|
||||
|
||||
device_selection: DeviceSelection = device_selection_action.widget
|
||||
if device_selection.device_combo_box.currentText() != self._config.device_name:
|
||||
if device_selection.device_combo_box.currentText() != self._config.device:
|
||||
return
|
||||
|
||||
signal_text = device_selection.signal_combo_box.currentText()
|
||||
if not signal_text or signal_text == self._config.device_entry:
|
||||
if not signal_text or signal_text == self._config.signal:
|
||||
return
|
||||
|
||||
signal_config = device_selection.signal_combo_box.get_signal_config()
|
||||
if not signal_config:
|
||||
try:
|
||||
device_obj = self.dev[self._config.device_name]
|
||||
device_obj = self.dev[self._config.device]
|
||||
signal_config = device_obj._info["signals"].get(signal_text, {})
|
||||
except (KeyError, AttributeError):
|
||||
signal_config = None
|
||||
@@ -646,7 +669,7 @@ class Image(ImageBase):
|
||||
self._signal_configs["main"] = signal_config
|
||||
self._device_selection_updating = True
|
||||
try:
|
||||
self.device_entry = signal_text
|
||||
self.signal = signal_text
|
||||
finally:
|
||||
self._device_selection_updating = False
|
||||
|
||||
@@ -795,17 +818,17 @@ class Image(ImageBase):
|
||||
|
||||
def _get_async_signal_name(self) -> tuple[str, str] | None:
|
||||
"""
|
||||
Returns device name and async signal name used for endpoints/messages.
|
||||
Returns device and async signal names used for endpoints/messages.
|
||||
|
||||
Returns:
|
||||
tuple[str, str] | None: (device_name, async_signal_name) or None if not available.
|
||||
tuple[str, str] | None: (device, async_signal_name) or None if not available.
|
||||
"""
|
||||
if not self._config.device_name or not self._config.device_entry:
|
||||
if not self._config.device or not self._config.signal:
|
||||
return None
|
||||
|
||||
config = self.subscriptions["main"]
|
||||
async_signal = config.async_signal_name or self._config.device_entry
|
||||
return self._config.device_name, async_signal
|
||||
async_signal = config.async_signal_name or self._config.signal
|
||||
return self._config.device, async_signal
|
||||
|
||||
def _setup_async_image(self, scan_id: str | None):
|
||||
"""
|
||||
@@ -823,7 +846,7 @@ class Image(ImageBase):
|
||||
logger.info("Async image setup skipped because monitor information is incomplete.")
|
||||
return
|
||||
|
||||
device_name, async_signal = async_names
|
||||
device, async_signal = async_names
|
||||
if config.monitor_type == "1d":
|
||||
slot = self.on_image_update_1d
|
||||
elif config.monitor_type == "2d":
|
||||
@@ -839,7 +862,7 @@ class Image(ImageBase):
|
||||
if prev_scan_id is None:
|
||||
continue
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
slot, MessageEndpoints.device_async_signal(prev_scan_id, device_name, async_signal)
|
||||
slot, MessageEndpoints.device_async_signal(prev_scan_id, device, async_signal)
|
||||
)
|
||||
|
||||
if scan_id is None:
|
||||
@@ -848,67 +871,41 @@ class Image(ImageBase):
|
||||
|
||||
self.bec_dispatcher.connect_slot(
|
||||
slot,
|
||||
MessageEndpoints.device_async_signal(scan_id, device_name, async_signal),
|
||||
MessageEndpoints.device_async_signal(scan_id, device, async_signal),
|
||||
from_start=True,
|
||||
cb_info={"scan_id": scan_id},
|
||||
)
|
||||
logger.info(f"Setup async image for {device_name}.{async_signal} and scan {scan_id}.")
|
||||
logger.info(f"Setup async image for {device}.{async_signal} and scan {scan_id}.")
|
||||
|
||||
def disconnect_monitor(self, device_name: str | None = None, device_entry: str | None = None):
|
||||
def disconnect_monitor(self, device: str | None = None, signal: str | None = None):
|
||||
"""
|
||||
Disconnect the monitor from the image update signals, both 1D and 2D.
|
||||
|
||||
Args:
|
||||
device_name(str|None): The name of the device to disconnect. Defaults to current device.
|
||||
device_entry(str|None): The signal/entry name to disconnect. Defaults to current entry.
|
||||
device(str|None): The name of the device to disconnect. Defaults to current device.
|
||||
signal(str|None): The signal/entry name to disconnect. Defaults to current signal.
|
||||
"""
|
||||
config = self.subscriptions["main"]
|
||||
target_device = device_name or self._config.device_name
|
||||
target_entry = device_entry or self._config.device_entry
|
||||
target_device = device or self._config.device
|
||||
target_entry = signal or self._config.signal
|
||||
|
||||
if not target_device or not target_entry:
|
||||
logger.warning("Cannot disconnect monitor without both device_name and device_entry")
|
||||
logger.warning("Cannot disconnect monitor without both device and signal")
|
||||
return
|
||||
|
||||
if self.async_update:
|
||||
async_signal_name = config.async_signal_name or target_entry
|
||||
ids_to_check = [self.scan_id, self.old_scan_id]
|
||||
if config.source == "device_monitor_1d":
|
||||
for scan_id in ids_to_check:
|
||||
if scan_id is None:
|
||||
continue
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_1d,
|
||||
MessageEndpoints.device_async_signal(
|
||||
scan_id, target_device, async_signal_name
|
||||
),
|
||||
)
|
||||
elif config.source == "device_monitor_2d":
|
||||
for scan_id in ids_to_check:
|
||||
if scan_id is None:
|
||||
continue
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_2d,
|
||||
MessageEndpoints.device_async_signal(
|
||||
scan_id, target_device, async_signal_name
|
||||
),
|
||||
)
|
||||
else:
|
||||
if config.source == "device_monitor_1d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_1d,
|
||||
MessageEndpoints.device_preview(target_device, target_entry),
|
||||
)
|
||||
elif config.source == "device_monitor_2d":
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update_2d,
|
||||
MessageEndpoints.device_preview(target_device, target_entry),
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Cannot disconnect monitor {target_device}.{target_entry} with source {self.subscriptions['main'].source}"
|
||||
)
|
||||
return
|
||||
if config.source not in {"device_monitor_1d", "device_monitor_2d"}:
|
||||
logger.warning(
|
||||
f"Cannot disconnect monitor {target_device}.{target_entry} with source {self.subscriptions['main'].source}"
|
||||
)
|
||||
return
|
||||
|
||||
self._disconnect_monitor_subscription(
|
||||
device=target_device,
|
||||
signal=target_entry,
|
||||
source=config.source,
|
||||
async_update=self.async_update,
|
||||
async_signal_name=config.async_signal_name,
|
||||
)
|
||||
|
||||
self.subscriptions["main"].async_signal_name = None
|
||||
self.async_update = False
|
||||
@@ -1045,10 +1042,10 @@ class Image(ImageBase):
|
||||
if layer_name not in self.subscriptions:
|
||||
return
|
||||
# For the main layer, disconnect current monitor
|
||||
if layer_name == "main" and self._config.device_name and self._config.device_entry:
|
||||
if layer_name == "main" and self._config.device and self._config.signal:
|
||||
self._disconnect_current_monitor()
|
||||
self._config.device_name = ""
|
||||
self._config.device_entry = ""
|
||||
self._config.device = ""
|
||||
self._config.signal = ""
|
||||
self._signal_configs.pop("main", None)
|
||||
|
||||
def cleanup(self):
|
||||
@@ -1058,7 +1055,7 @@ class Image(ImageBase):
|
||||
self.layer_removed.disconnect(self._on_layer_removed)
|
||||
|
||||
# Disconnect current monitor
|
||||
if self._config.device_name and self._config.device_entry:
|
||||
if self._config.device and self._config.signal:
|
||||
self._disconnect_current_monitor()
|
||||
|
||||
self.subscriptions.clear()
|
||||
|
||||
@@ -64,32 +64,32 @@ class DeviceSelection(QWidget):
|
||||
layout.addWidget(self.device_combo_box, stretch=1)
|
||||
layout.addWidget(self.signal_combo_box, stretch=1)
|
||||
|
||||
def set_device_and_signal(self, device_name: str | None, device_entry: str | None) -> None:
|
||||
def set_device_and_signal(self, device: str | None, signal: str | None) -> None:
|
||||
"""Set the displayed device and signal without emitting selection signals."""
|
||||
device_name = device_name or ""
|
||||
device_entry = device_entry or ""
|
||||
device = device or ""
|
||||
signal = signal or ""
|
||||
|
||||
self.device_combo_box.blockSignals(True)
|
||||
self.signal_combo_box.blockSignals(True)
|
||||
|
||||
try:
|
||||
if device_name:
|
||||
if device:
|
||||
# Set device in device_combo_box
|
||||
index = self.device_combo_box.findText(device_name)
|
||||
index = self.device_combo_box.findText(device)
|
||||
if index >= 0:
|
||||
self.device_combo_box.setCurrentIndex(index)
|
||||
else:
|
||||
# Device not found in list, but still set it
|
||||
self.device_combo_box.setCurrentText(device_name)
|
||||
self.device_combo_box.setCurrentText(device)
|
||||
|
||||
# Only update signal combobox device filter if it's actually changing
|
||||
# This prevents redundant repopulation which can cause duplicates !!!!
|
||||
current_device = getattr(self.signal_combo_box, "_device", None)
|
||||
if current_device != device_name:
|
||||
self.signal_combo_box.set_device(device_name)
|
||||
if current_device != device:
|
||||
self.signal_combo_box.set_device(device)
|
||||
|
||||
# Sync signal combobox selection
|
||||
if device_entry:
|
||||
if signal:
|
||||
# Try to find the signal by component_name (which is what's displayed)
|
||||
found = False
|
||||
for i in range(self.signal_combo_box.count()):
|
||||
@@ -99,14 +99,14 @@ class DeviceSelection(QWidget):
|
||||
# Check if this matches our signal
|
||||
if config_data:
|
||||
component_name = config_data.get("component_name", "")
|
||||
if text == component_name or text == device_entry:
|
||||
if text == component_name or text == signal:
|
||||
self.signal_combo_box.setCurrentIndex(i)
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
# Fallback: try to match the device_entry directly
|
||||
index = self.signal_combo_box.findText(device_entry)
|
||||
# Fallback: try to match the signal directly
|
||||
index = self.signal_combo_box.findText(signal)
|
||||
if index >= 0:
|
||||
self.signal_combo_box.setCurrentIndex(index)
|
||||
else:
|
||||
@@ -187,8 +187,8 @@ class DeviceSelectionConnection(BundleConnection):
|
||||
self.components = components
|
||||
self.target_widget = target_widget
|
||||
self._connected = False
|
||||
self.register_property_sync("device_name", self._sync_from_device_name)
|
||||
self.register_property_sync("device_entry", self._sync_from_device_entry)
|
||||
self.register_property_sync("device", self._sync_from_device)
|
||||
self.register_property_sync("signal", self._sync_from_signal)
|
||||
self.register_property_sync("connection_status", self._sync_connection_status)
|
||||
self.register_property_sync("connection_error", self._sync_connection_status)
|
||||
|
||||
@@ -222,26 +222,22 @@ class DeviceSelectionConnection(BundleConnection):
|
||||
self._connected = False
|
||||
widget.cleanup()
|
||||
|
||||
def _sync_from_device_name(self, _):
|
||||
def _sync_from_device(self, _):
|
||||
try:
|
||||
widget = self._widget()
|
||||
except Exception:
|
||||
return
|
||||
|
||||
widget.set_device_and_signal(
|
||||
self.target_widget.device_name, self.target_widget.device_entry
|
||||
)
|
||||
self.target_widget._sync_device_entry_from_toolbar()
|
||||
widget.set_device_and_signal(self.target_widget.device, self.target_widget.signal)
|
||||
self.target_widget._sync_signal_from_toolbar()
|
||||
|
||||
def _sync_from_device_entry(self, _):
|
||||
def _sync_from_signal(self, _):
|
||||
try:
|
||||
widget = self._widget()
|
||||
except Exception:
|
||||
return
|
||||
|
||||
widget.set_device_and_signal(
|
||||
self.target_widget.device_name, self.target_widget.device_entry
|
||||
)
|
||||
widget.set_device_and_signal(self.target_widget.device, self.target_widget.signal)
|
||||
|
||||
def _sync_connection_status(self, _):
|
||||
try:
|
||||
|
||||
@@ -48,14 +48,14 @@ class FilledRectItem(pg.GraphicsObject):
|
||||
|
||||
|
||||
class MotorConfig(BaseModel):
|
||||
name: str | None = Field(None, description="Motor name.")
|
||||
device: str | None = Field(None, description="Motor name.")
|
||||
limits: list[float] | None = Field(None, description="Motor limits.")
|
||||
|
||||
|
||||
# noinspection PyDataclass
|
||||
class MotorMapConfig(ConnectionConfig):
|
||||
x_motor: MotorConfig = Field(default_factory=MotorConfig, description="Motor X name.")
|
||||
y_motor: MotorConfig = Field(default_factory=MotorConfig, description="Motor Y name.")
|
||||
device_x: MotorConfig = Field(default_factory=MotorConfig, description="Motor X name.")
|
||||
device_y: MotorConfig = Field(default_factory=MotorConfig, description="Motor Y name.")
|
||||
color: str | tuple | None = Field(
|
||||
(255, 255, 255, 255), description="The color of the last point of current position."
|
||||
)
|
||||
@@ -109,10 +109,10 @@ class MotorMap(PlotBase):
|
||||
"map",
|
||||
"reset_history",
|
||||
"get_data",
|
||||
"x_motor",
|
||||
"x_motor.setter",
|
||||
"y_motor",
|
||||
"y_motor.setter",
|
||||
"device_x",
|
||||
"device_x.setter",
|
||||
"device_y",
|
||||
"device_y.setter",
|
||||
]
|
||||
|
||||
update_signal = Signal()
|
||||
@@ -208,7 +208,7 @@ class MotorMap(PlotBase):
|
||||
return
|
||||
|
||||
if motor_x != "" and motor_y != "":
|
||||
if motor_x != self.config.x_motor.name or motor_y != self.config.y_motor.name:
|
||||
if motor_x != self.config.device_x.device or motor_y != self.config.device_y.device:
|
||||
self.map(motor_x, motor_y)
|
||||
|
||||
def _add_motor_map_settings(self):
|
||||
@@ -259,32 +259,32 @@ class MotorMap(PlotBase):
|
||||
################################################################################
|
||||
|
||||
@SafeProperty(str)
|
||||
def x_motor(self) -> str:
|
||||
def device_x(self) -> str:
|
||||
"""Name of the motor shown on the X axis."""
|
||||
return self.config.x_motor.name or ""
|
||||
return self.config.device_x.device or ""
|
||||
|
||||
@x_motor.setter
|
||||
def x_motor(self, motor_name: str) -> None:
|
||||
@device_x.setter
|
||||
def device_x(self, motor_name: str) -> None:
|
||||
motor_name = motor_name or ""
|
||||
if motor_name == (self.config.x_motor.name or ""):
|
||||
if motor_name == (self.config.device_x.device or ""):
|
||||
return
|
||||
if motor_name and self.y_motor:
|
||||
self.map(motor_name, self.y_motor, suppress_errors=True)
|
||||
if motor_name and self.device_y:
|
||||
self.map(motor_name, self.device_y, suppress_errors=True)
|
||||
return
|
||||
self._set_motor_name(axis="x", motor_name=motor_name)
|
||||
|
||||
@SafeProperty(str)
|
||||
def y_motor(self) -> str:
|
||||
def device_y(self) -> str:
|
||||
"""Name of the motor shown on the Y axis."""
|
||||
return self.config.y_motor.name or ""
|
||||
return self.config.device_y.device or ""
|
||||
|
||||
@y_motor.setter
|
||||
def y_motor(self, motor_name: str) -> None:
|
||||
@device_y.setter
|
||||
def device_y(self, motor_name: str) -> None:
|
||||
motor_name = motor_name or ""
|
||||
if motor_name == (self.config.y_motor.name or ""):
|
||||
if motor_name == (self.config.device_y.device or ""):
|
||||
return
|
||||
if motor_name and self.x_motor:
|
||||
self.map(self.x_motor, motor_name, suppress_errors=True)
|
||||
if motor_name and self.device_x:
|
||||
self.map(self.device_x, motor_name, suppress_errors=True)
|
||||
return
|
||||
self._set_motor_name(axis="y", motor_name=motor_name)
|
||||
|
||||
@@ -452,13 +452,13 @@ class MotorMap(PlotBase):
|
||||
Update stored motor name for given axis and optionally refresh the toolbar selection.
|
||||
"""
|
||||
motor_name = motor_name or ""
|
||||
motor_config = self.config.x_motor if axis == "x" else self.config.y_motor
|
||||
motor_config = self.config.device_x if axis == "x" else self.config.device_y
|
||||
|
||||
if motor_config.name == motor_name:
|
||||
if motor_config.device == motor_name:
|
||||
return
|
||||
|
||||
motor_config.name = motor_name
|
||||
self.property_changed.emit(f"{axis}_motor", motor_name)
|
||||
motor_config.device = motor_name
|
||||
self.property_changed.emit(f"device_{axis}", motor_name)
|
||||
|
||||
if sync_toolbar:
|
||||
self._sync_motor_map_selection_toolbar()
|
||||
@@ -468,14 +468,14 @@ class MotorMap(PlotBase):
|
||||
################################################################################
|
||||
@SafeSlot()
|
||||
def map(
|
||||
self, x_name: str, y_name: str, validate_bec: bool = True, suppress_errors=False
|
||||
self, device_x: str, device_y: str, validate_bec: bool = True, suppress_errors=False
|
||||
) -> None:
|
||||
"""
|
||||
Set the x and y motor names.
|
||||
|
||||
Args:
|
||||
x_name(str): The name of the x motor.
|
||||
y_name(str): The name of the y motor.
|
||||
device_x(str): The name of the x motor.
|
||||
device_y(str): The name of the y motor.
|
||||
validate_bec(bool, optional): If True, validate the signal with BEC. Defaults to True.
|
||||
suppress_errors(bool, optional): If True, suppress errors during validation. Defaults to False. Used for properties setting. If the validation fails, the changes are not applied.
|
||||
"""
|
||||
@@ -484,22 +484,22 @@ class MotorMap(PlotBase):
|
||||
if validate_bec:
|
||||
if suppress_errors:
|
||||
try:
|
||||
self.entry_validator.validate_signal(x_name, None)
|
||||
self.entry_validator.validate_signal(y_name, None)
|
||||
self.entry_validator.validate_signal(device_x, None)
|
||||
self.entry_validator.validate_signal(device_y, None)
|
||||
except Exception:
|
||||
return
|
||||
else:
|
||||
self.entry_validator.validate_signal(x_name, None)
|
||||
self.entry_validator.validate_signal(y_name, None)
|
||||
self.entry_validator.validate_signal(device_x, None)
|
||||
self.entry_validator.validate_signal(device_y, None)
|
||||
|
||||
self._set_motor_name(axis="x", motor_name=x_name, sync_toolbar=False)
|
||||
self._set_motor_name(axis="y", motor_name=y_name, sync_toolbar=False)
|
||||
self._set_motor_name(axis="x", motor_name=device_x, sync_toolbar=False)
|
||||
self._set_motor_name(axis="y", motor_name=device_y, sync_toolbar=False)
|
||||
|
||||
motor_x_limit = self._get_motor_limit(self.config.x_motor.name)
|
||||
motor_y_limit = self._get_motor_limit(self.config.y_motor.name)
|
||||
motor_x_limit = self._get_motor_limit(self.config.device_x.device)
|
||||
motor_y_limit = self._get_motor_limit(self.config.device_y.device)
|
||||
|
||||
self.config.x_motor.limits = motor_x_limit
|
||||
self.config.y_motor.limits = motor_y_limit
|
||||
self.config.device_x.limits = motor_x_limit
|
||||
self.config.device_y.limits = motor_y_limit
|
||||
|
||||
# reconnect the signals
|
||||
self._connect_motor_to_slots()
|
||||
@@ -574,19 +574,19 @@ class MotorMap(PlotBase):
|
||||
msg(dict): Message from the device readback.
|
||||
metadata(dict): Metadata of the message.
|
||||
"""
|
||||
x_motor = self.config.x_motor.name
|
||||
y_motor = self.config.y_motor.name
|
||||
device_x = self.config.device_x.device
|
||||
device_y = self.config.device_y.device
|
||||
|
||||
if x_motor is None or y_motor is None:
|
||||
if device_x is None or device_y is None:
|
||||
return
|
||||
|
||||
if x_motor in msg["signals"]:
|
||||
x = msg["signals"][x_motor]["value"]
|
||||
if device_x in msg["signals"]:
|
||||
x = msg["signals"][device_x]["value"]
|
||||
self._buffer["x"].append(x)
|
||||
self._buffer["y"].append(self._buffer["y"][-1])
|
||||
|
||||
elif y_motor in msg["signals"]:
|
||||
y = msg["signals"][y_motor]["value"]
|
||||
elif device_y in msg["signals"]:
|
||||
y = msg["signals"][device_y]["value"]
|
||||
self._buffer["y"].append(y)
|
||||
self._buffer["x"].append(self._buffer["x"][-1])
|
||||
|
||||
@@ -597,12 +597,12 @@ class MotorMap(PlotBase):
|
||||
self._disconnect_current_motors()
|
||||
|
||||
endpoints_readback = [
|
||||
MessageEndpoints.device_readback(self.config.x_motor.name),
|
||||
MessageEndpoints.device_readback(self.config.y_motor.name),
|
||||
MessageEndpoints.device_readback(self.config.device_x.device),
|
||||
MessageEndpoints.device_readback(self.config.device_y.device),
|
||||
]
|
||||
endpoints_limits = [
|
||||
MessageEndpoints.device_limits(self.config.x_motor.name),
|
||||
MessageEndpoints.device_limits(self.config.y_motor.name),
|
||||
MessageEndpoints.device_limits(self.config.device_x.device),
|
||||
MessageEndpoints.device_limits(self.config.device_y.device),
|
||||
]
|
||||
|
||||
self.bec_dispatcher.connect_slot(self.on_device_readback, endpoints_readback)
|
||||
@@ -610,14 +610,14 @@ class MotorMap(PlotBase):
|
||||
|
||||
def _disconnect_current_motors(self):
|
||||
"""Disconnect the current motors from the slots."""
|
||||
if self.config.x_motor.name is not None and self.config.y_motor.name is not None:
|
||||
if self.config.device_x.device is not None and self.config.device_y.device is not None:
|
||||
endpoints_readback = [
|
||||
MessageEndpoints.device_readback(self.config.x_motor.name),
|
||||
MessageEndpoints.device_readback(self.config.y_motor.name),
|
||||
MessageEndpoints.device_readback(self.config.device_x.device),
|
||||
MessageEndpoints.device_readback(self.config.device_y.device),
|
||||
]
|
||||
endpoints_limits = [
|
||||
MessageEndpoints.device_limits(self.config.x_motor.name),
|
||||
MessageEndpoints.device_limits(self.config.y_motor.name),
|
||||
MessageEndpoints.device_limits(self.config.device_x.device),
|
||||
MessageEndpoints.device_limits(self.config.device_y.device),
|
||||
]
|
||||
self.bec_dispatcher.disconnect_slot(self.on_device_readback, endpoints_readback)
|
||||
self.bec_dispatcher.disconnect_slot(self.on_device_limits, endpoints_limits)
|
||||
@@ -634,8 +634,8 @@ class MotorMap(PlotBase):
|
||||
msg(dict): Message from the device limits.
|
||||
metadata(dict): Metadata of the message.
|
||||
"""
|
||||
self.config.x_motor.limits = self._get_motor_limit(self.config.x_motor.name)
|
||||
self.config.y_motor.limits = self._get_motor_limit(self.config.y_motor.name)
|
||||
self.config.device_x.limits = self._get_motor_limit(self.config.device_x.device)
|
||||
self.config.device_y.limits = self._get_motor_limit(self.config.device_y.device)
|
||||
self._swap_limit_map()
|
||||
|
||||
def _get_motor_limit(self, motor: str) -> list | None:
|
||||
@@ -663,8 +663,8 @@ class MotorMap(PlotBase):
|
||||
Make the motor map.
|
||||
"""
|
||||
|
||||
motor_x_limit = self.config.x_motor.limits
|
||||
motor_y_limit = self.config.y_motor.limits
|
||||
motor_x_limit = self.config.device_x.limits
|
||||
motor_y_limit = self.config.device_y.limits
|
||||
|
||||
self._limit_map = self._make_limit_map(motor_x_limit, motor_y_limit)
|
||||
self.plot_item.addItem(self._limit_map)
|
||||
@@ -678,10 +678,10 @@ class MotorMap(PlotBase):
|
||||
|
||||
# Add the crosshair for initial motor coordinates
|
||||
initial_position_x = self._get_motor_init_position(
|
||||
self.config.x_motor.name, self.config.precision
|
||||
self.config.device_x.device, self.config.precision
|
||||
)
|
||||
initial_position_y = self._get_motor_init_position(
|
||||
self.config.y_motor.name, self.config.precision
|
||||
self.config.device_y.device, self.config.precision
|
||||
)
|
||||
|
||||
self._buffer["x"] = [initial_position_x]
|
||||
@@ -693,8 +693,8 @@ class MotorMap(PlotBase):
|
||||
self._add_coordinates_crosshair(initial_position_x, initial_position_y)
|
||||
|
||||
# Set default labels for the plot
|
||||
self.set_x_label_suffix(f"[{self.config.x_motor.name}-{self.config.x_motor.name}]")
|
||||
self.set_y_label_suffix(f"[{self.config.y_motor.name}-{self.config.y_motor.name}]")
|
||||
self.set_x_label_suffix(f"[{self.config.device_x.device}-{self.config.device_x.device}]")
|
||||
self.set_y_label_suffix(f"[{self.config.device_y.device}-{self.config.device_y.device}]")
|
||||
|
||||
self.update_signal.emit()
|
||||
|
||||
@@ -794,8 +794,8 @@ class MotorMap(PlotBase):
|
||||
def _swap_limit_map(self):
|
||||
"""Swap the limit map."""
|
||||
self.plot_item.removeItem(self._limit_map)
|
||||
x_limits = self.config.x_motor.limits
|
||||
y_limits = self.config.y_motor.limits
|
||||
x_limits = self.config.device_x.limits
|
||||
y_limits = self.config.device_y.limits
|
||||
if x_limits is not None and y_limits is not None:
|
||||
self._limit_map = self._make_limit_map(x_limits, y_limits)
|
||||
self._limit_map.setZValue(-1)
|
||||
@@ -828,8 +828,8 @@ class MotorMap(PlotBase):
|
||||
if motor_selection_action is None:
|
||||
return
|
||||
motor_selection: MotorSelection = motor_selection_action.widget
|
||||
target_x = self.config.x_motor.name or ""
|
||||
target_y = self.config.y_motor.name or ""
|
||||
target_x = self.config.device_x.device or ""
|
||||
target_y = self.config.device_y.device or ""
|
||||
|
||||
if (
|
||||
motor_selection.motor_x.currentText() == target_x
|
||||
@@ -864,10 +864,10 @@ class DemoApp(QMainWindow): # pragma: no cover
|
||||
self.setCentralWidget(self.main_widget)
|
||||
|
||||
self.motor_map_popup = MotorMap(popups=True)
|
||||
self.motor_map_popup.map(x_name="samx", y_name="samy", validate_bec=True)
|
||||
self.motor_map_popup.map(device_x="samx", device_y="samy", validate_bec=True)
|
||||
|
||||
self.motor_map_side = MotorMap(popups=False)
|
||||
self.motor_map_side.map(x_name="samx", y_name="samy", validate_bec=True)
|
||||
self.motor_map_side.map(device_x="samx", device_y="samy", validate_bec=True)
|
||||
|
||||
self.layout.addWidget(self.motor_map_side)
|
||||
self.layout.addWidget(self.motor_map_popup)
|
||||
|
||||
@@ -20,8 +20,8 @@ logger = bec_logger.logger
|
||||
class ScatterDeviceSignal(BaseModel):
|
||||
"""The configuration of a signal in the scatter waveform widget."""
|
||||
|
||||
name: str
|
||||
entry: str
|
||||
device: str
|
||||
signal: str
|
||||
|
||||
model_config: dict = {"validate_assignment": True}
|
||||
|
||||
@@ -40,13 +40,13 @@ class ScatterCurveConfig(ConnectionConfig):
|
||||
color_map: str | None = Field(
|
||||
"plasma", description="The color palette of the figure widget.", validate_default=True
|
||||
)
|
||||
x_device: ScatterDeviceSignal | None = Field(
|
||||
device_x: ScatterDeviceSignal | None = Field(
|
||||
None, description="The x device signal of the scatter waveform."
|
||||
)
|
||||
y_device: ScatterDeviceSignal | None = Field(
|
||||
device_y: ScatterDeviceSignal | None = Field(
|
||||
None, description="The y device signal of the scatter waveform."
|
||||
)
|
||||
z_device: ScatterDeviceSignal | None = Field(
|
||||
device_z: ScatterDeviceSignal | None = Field(
|
||||
None, description="The z device signal of the scatter waveform."
|
||||
)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user