diff options
| author | Christian Kolset <christian.kolset@gmail.com> | 2026-09-20 23:45:18 -0600 |
|---|---|---|
| committer | Christian Kolset <christian.kolset@gmail.com> | 2026-09-20 23:45:18 -0600 |
| commit | a0473245f1f453bfc87ea1bc9bd479311e8a944b (patch) | |
| tree | 5c317d6b39c436fb58824e0553d7ba4603cc0829 /ui/namespace_panel.py | |
| parent | 006366ef8099c8313ae596bf6267e9f98dfbeb5e (diff) | |
Persist dock layout to profiles; dedupe port names; Channels-tab Create button
- Fix duplicated device names ("FT231X USB UART - FT231X USB UART (...)")
— pyserial on Linux often reports the same udev model string twice for
cheap FTDI/CH340-style adapters. Collapse it at the list_ports() source
so every consumer (device auto-name, port picker) benefits.
- Save Control Panel / Namespace dock area, floating geometry, visibility,
size and order to .labui profiles via QMainWindow.saveState()/
restoreState(), round-tripped through the existing Profile.settings
passthrough (self._settings) — no profile schema change needed.
- Channels tab: replace the per-row Signal ⊕ button (and its pinned/
frozen-column overlay) with a single "Create Channel" button below the
Namespace panel. Select one or more Signal/Channel rows (multi-select
now supported) and click it — selected rows become the new Channel's
sources, or an empty Channel is created if nothing's selected. Fixes a
bug in the process: the multi/zero-source path defaulted to
kind="expression" with no expression text, which fails to compile and
silently dropped the channel; use kind="none" instead, which the user
then edits in the Channels pane.
NamespacePanel itself (ui/namespace_panel.py) goes back to a plain
read-only reference widget — the create-channel button and its logic
live entirely in ConfigWindow (config_window.py), so the shared
dockable Namespace panel on the main window is unaffected.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'ui/namespace_panel.py')
| -rw-r--r-- | ui/namespace_panel.py | 101 |
1 files changed, 57 insertions, 44 deletions
diff --git a/ui/namespace_panel.py b/ui/namespace_panel.py index e2b8809..f8804c0 100644 --- a/ui/namespace_panel.py +++ b/ui/namespace_panel.py @@ -5,24 +5,27 @@ NAMESPACE panel — dockable, live browser of everything referenceable in a script: Signals (raw device endpoints), Channels (processed/derived values), and vars (the shared dict bridging Control Panel On Action Scripts and Channel scripts). Read-only reference, not an editor — editing -still happens in Configuration > Channels — with one narrow exception: -when constructed with `on_create_channel`, each Signal row gets a ⊕ -button to create a passthrough Channel from it directly. Only -ConfigWindow's Channels-tab instance opts into this (config_window.py); -the dockable instance on the main window (ui/main_window.py) does not -pass a callback, so it stays exactly the plain read-only reference. +still happens in Configuration > Channels. + +Rows support multi-select (Ctrl/Shift-click). selected_references() exposes +the currently-selected Signal/Channel rows as (dev_id, ch_id, name, unit, +color) tuples — used by ConfigWindow's "Create Channel" button (Channels +tab, config_window.py), which sits below this panel rather than inside it: +this widget stays a plain reference browser with no create-channel +knowledge of its own, reusable as-is for the read-only dockable instance +on the main window (ui/main_window.py). Docked opposite the Control Panel (ui/main_window.py), built the same way: a QDockWidget you can drag, float, redock, or close. """ from __future__ import annotations -from typing import Callable, Dict, Optional, Tuple +from typing import Dict, List, Tuple from PyQt6.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QLabel, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, - QToolButton, QApplication, + QApplication, ) from PyQt6.QtCore import QTimer, pyqtSlot from PyQt6.QtGui import QColor @@ -38,7 +41,6 @@ _C_NAME = 2 _C_DIR = 3 _C_VALUE = 4 _C_SOURCE = 5 -_C_CREATE = 6 # only present when on_create_channel is set def _fmt_value(v) -> str: @@ -60,14 +62,10 @@ def _fmt_ref(dev_id: str, ch_id: str) -> str: class NamespacePanel(QWidget): - def __init__(self, registry: DeviceRegistry, processor: SignalProcessor, - on_create_channel: Optional[Callable[[str, str, str, str, str], None]] = None): + def __init__(self, registry: DeviceRegistry, processor: SignalProcessor): super().__init__() self.registry = registry self.processor = processor - # (dev_id, ch_id, name, unit, color) -> None, called when a Signal - # row's ⊕ button is clicked. None hides the column entirely. - self.on_create_channel = on_create_channel # row key -> row index. Keys: # ("signal", dev_id, ch_id) | ("channel", channel_id) | ("var", name) self._row_index: Dict[Tuple, int] = {} @@ -85,7 +83,8 @@ class NamespacePanel(QWidget): lay.setSpacing(0) hint = QLabel( - "Double-click a row to copy reference to clipboard" + "Double-click a row to copy reference to clipboard · " + "select rows to use as sources for Create Channel" ) hint.setObjectName("traceSource") hint.setWordWrap(True) @@ -94,11 +93,8 @@ class NamespacePanel(QWidget): self._table = QTableWidget() self._table.setObjectName("channelTable") - labels = ["Kind", "ID", "Name", "Dir", "Value", "Source"] - if self.on_create_channel: - labels.append("") - self._table.setColumnCount(len(labels)) - self._table.setHorizontalHeaderLabels(labels) + self._table.setColumnCount(6) + self._table.setHorizontalHeaderLabels(["Kind", "ID", "Name", "Dir", "Value", "Source"]) hdr = self._table.horizontalHeader() hdr.setSectionResizeMode(_C_SOURCE, QHeaderView.ResizeMode.Stretch) hdr.setSectionResizeMode(_C_KIND, QHeaderView.ResizeMode.ResizeToContents) @@ -106,25 +102,57 @@ class NamespacePanel(QWidget): hdr.setSectionResizeMode(_C_NAME, QHeaderView.ResizeMode.ResizeToContents) hdr.setSectionResizeMode(_C_DIR, QHeaderView.ResizeMode.ResizeToContents) hdr.setSectionResizeMode(_C_VALUE, QHeaderView.ResizeMode.ResizeToContents) - if self.on_create_channel: - hdr.setSectionResizeMode(_C_CREATE, QHeaderView.ResizeMode.ResizeToContents) self._table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self._table.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self._table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) self._table.setAlternatingRowColors(True) self._table.verticalHeader().setVisible(False) self._table.cellDoubleClicked.connect(self._on_double_clicked) lay.addWidget(self._table) - def _apply_min_width(self): - """Floor the panel's width at the sum of its columns' natural sizes - (Source gets a fixed placeholder rather than its live stretched - width, which would be circular) — so dragging the Channels-tab - splitter divider narrower can never push the ⊕ create-channel - column (or any other column) behind the horizontal scrollbar.""" + def natural_width(self) -> int: + """Sum of current column widths (Source, being Stretch, counted at + a fixed placeholder rather than its live stretched width, which + would be circular) — how wide this panel would need to be to show + every column without a horizontal scrollbar. A query only, not an + enforced constraint: this panel never sets its own minimum width + (that fights QMainWindow's dock layout when this class is docked + stacked/tabbed with another dock, e.g. Control Panel, in + ui/main_window.py). A caller that wants "start small but readable" + sizing — see ConfigWindow's Channels tab — uses this once for + initial splitter sizing instead.""" total = 0 for i in range(self._table.columnCount()): total += 80 if i == _C_SOURCE else self._table.columnWidth(i) - self.setMinimumWidth(total + 24) + return total + 24 + + # ── Selection ──────────────────────────────────────────────────────────── + + def selected_references(self) -> List[Tuple[str, str, str, str, str]]: + """Currently-selected Signal/Channel rows as (dev_id, ch_id, name, + unit, color) — the shape ConfigWindow's "Create Channel" button + needs to build a new Channel's sources. Selected "var" rows and any + row whose underlying Signal/Channel has since vanished are skipped + silently (vars aren't valid Channel sources; a vanished row means + the selection is stale).""" + rows = {idx.row() for idx in self._table.selectionModel().selectedRows()} + out: List[Tuple[str, str, str, str, str]] = [] + for key, row in self._row_index.items(): + if row not in rows: + continue + if key[0] == "signal": + _, dev_id, ch_id = key + dev = self.registry.get_instance(dev_id) + ch = dev.get_signal(ch_id) if dev else None + if ch is not None: + out.append((dev_id, ch_id, ch.name, ch.unit, ch.color)) + elif key[0] == "channel": + _, channel_id = key + dc = next((d for d in self.processor.get_derived() + if d.channel_id == channel_id), None) + if dc is not None: + out.append(("derived", channel_id, dc.name, dc.unit, dc.color)) + return out # ── Row-set (structural) rebuild — devices/channels/vars added or removed ── @@ -149,13 +177,9 @@ class NamespacePanel(QWidget): for row, key in enumerate(keys): self._row_index[key] = row self._paint_row(row, key) - self._apply_min_width() def _paint_row(self, row: int, key: Tuple): kind = key[0] - if self.on_create_channel: - self._table.removeCellWidget(row, _C_CREATE) # row's kind may have - # changed since last paint if kind == "signal": _, dev_id, ch_id = key dev = self.registry.get_instance(dev_id) @@ -164,17 +188,6 @@ class NamespacePanel(QWidget): is_wr = bool(ch and ch.writable) self._set_row(row, "Signal", ch_id, name, "WRITE" if is_wr else "READ", None, _fmt_ref(dev_id, ch_id)) - if self.on_create_channel and ch is not None: - btn = QToolButton() - btn.setText("⊕") - btn.setObjectName("addTraceBtn") - btn.setFixedSize(24, 22) - btn.setToolTip("Create a Channel from this Signal") - btn.clicked.connect( - lambda _=False, d=dev_id, c=ch_id, n=ch.name, u=ch.unit, col=ch.color: - self.on_create_channel(d, c, n, u, col) - ) - self._table.setCellWidget(row, _C_CREATE, btn) elif kind == "channel": _, channel_id = key dc = next((d for d in self.processor.get_derived() |
