diff --git a/python/set_devices/qt_ports/logic_capture.py b/python/set_devices/qt_ports/logic_capture.py new file mode 100644 index 0000000..d8dd8f7 --- /dev/null +++ b/python/set_devices/qt_ports/logic_capture.py @@ -0,0 +1,187 @@ +"""Shared Qt controls and worker for online logic analyzer acquisition.""" + +from threading import Event + +try: + from PySide6.QtCore import QThread, Signal + from PySide6.QtWidgets import QCheckBox, QComboBox, QGroupBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget +except ImportError: + from PySide2.QtCore import QThread, Signal + from PySide2.QtWidgets import QCheckBox, QComboBox, QGroupBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget + +from logic_analyzer.files import ImportCancelled + + +class CaptureWorker(QThread): + """Run device discovery or acquisition using the driver's callbacks.""" + + devices = Signal(object) + captured = Signal(object) + status = Signal(str) + failed = Signal(str) + + def __init__(self, parent, *, discover=None, acquire=None, repeat=False): + super().__init__(parent) + if (discover is None) == (acquire is None): + raise ValueError("Provide one discovery or acquisition callback") + self.discover = discover + self.acquire = acquire + self.repeat = repeat + self.stop_event = Event() + + def run(self): + try: + if self.discover is not None: + devices = self.discover(self.isInterruptionRequested) + if not self.isInterruptionRequested(): + self.devices.emit(devices) + return + while not self.isInterruptionRequested(): + capture = self.acquire(self.stop_event.is_set, self.isInterruptionRequested, self.status.emit) + if self.isInterruptionRequested(): + return + self.captured.emit(capture) + if not self.repeat or self.stop_event.wait(.25): + return + except ImportCancelled: + pass + except Exception as error: + if not self.isInterruptionRequested(): + self.failed.emit(str(error)) + + +class CapturePanel(QGroupBox): + """Manage one worker and the common controls of an analyzer panel. + + The device panel implements find_devices, start_capture, _devices and + _device_changed. It fills config_layout before adding the capture controls. + """ + + captured = Signal(object) + busy_changed = Signal(bool) + + def __init__(self, title, device_name, settings, parent=None): + super().__init__(title, parent) + self._device_name = device_name + self.settings = settings + self.worker = None + self.configuration = QWidget() + self.config_layout = QVBoxLayout(self.configuration) + self.config_layout.setContentsMargins(0, 0, 0, 0) + QVBoxLayout(self).addWidget(self.configuration) + self.refresh = QPushButton('Найти устройства') + self.device = QComboBox() + self.device.setMinimumWidth(210) + self.mode = QComboBox() + self.mode.addItems(('Один захват', 'Повторять', 'До остановки')) + self.mode.setCurrentIndex(int(self.settings.value('mode', 0))) + + def add_channel_controls(self): + row = QHBoxLayout() + row.addWidget(QLabel('Каналы:')) + self.channels = [] + selected = str(self.settings.value('channels', '0,1')).split(',') + for index in range(16): + check = QCheckBox('D%d' % index) + check.setChecked(str(index) in selected) + row.addWidget(check) + self.channels.append(check) + self.config_layout.addLayout(row) + + def selected_channels(self): + return tuple(i for i, check in enumerate(self.channels) if check.isEnabled() and check.isChecked()) + + def add_capture_controls(self, status_text): + row = QHBoxLayout() + self.start = QPushButton('Начать захват') + self.stop = QPushButton('Стоп и показать') + self.cancel = QPushButton('Отменить') + for button in (self.start, self.stop, self.cancel): + button.setEnabled(False) + row.addWidget(button) + self.status = QLabel(status_text + ' График обновляется после захвата; повторные окна имеют разрывы.') + self.status.setWordWrap(True) + row.addWidget(self.status, 1) + self.layout().addLayout(row) + self.refresh.clicked.connect(self.find_devices) + self.start.clicked.connect(self.start_capture) + self.stop.clicked.connect(self.stop_capture) + self.cancel.clicked.connect(self.cancel_capture) + self.device.currentIndexChanged.connect(self._device_changed) + self.mode.currentIndexChanged.connect(self._mode_changed) + self._mode_changed() + + def _mode_changed(self): + self.duration.setEnabled(self.mode.currentIndex() != 2) + + def _invalidate_devices(self): + self.device.clear() + self.start.setEnabled(False) + + def _show_devices(self, devices, title, empty_message): + self.device.clear() + saved = self.settings.value('device', '') + for device in devices: + self.device.addItem(title(device), device) + if device.device_id == saved: + self.device.setCurrentIndex(self.device.count() - 1) + self.status.setText('Выберите параметры и начните захват.' if devices else empty_message) + + def _launch(self, worker): + self.worker = worker + worker.devices.connect(self._devices) + worker.captured.connect(self._captured) + worker.status.connect(self._status) + worker.failed.connect(self._failed) + worker.finished.connect(self._finished) + self.configuration.setEnabled(False) + self.start.setEnabled(False) + self.stop.setEnabled(worker.acquire is not None) + self.cancel.setEnabled(True) + self.busy_changed.emit(True) + worker.start() + + def _captured(self, capture): + if self.worker and not self.worker.isInterruptionRequested(): + self.captured.emit(capture) + self.status.setText('Получено %d каналов · %.6g с' % + (len(capture.channels), capture.end - capture.start)) + + def _failed(self, text): + self.status.setText(f'Ошибка {self._device_name}: {text}') + + def _status(self, text): + if self.worker and not self.worker.isInterruptionRequested(): + self.status.setText(text) + + def stop_capture(self): + if self.worker: + self.worker.stop_event.set() + self.stop.setEnabled(False) + self.status.setText('Остановка и получение записи…') + + def cancel_capture(self): + if self.worker: + self.worker.requestInterruption() + self.worker.stop_event.set() + self.status.setText('Отмена… Предыдущая запись сохранена.') + self.stop.setEnabled(False) + self.cancel.setEnabled(False) + + def _finished(self): + worker = self.sender() + worker.deleteLater() + if worker is not self.worker: + return + self.worker = None + self.configuration.setEnabled(True) + self._device_changed() + self.stop.setEnabled(False) + self.cancel.setEnabled(False) + self.busy_changed.emit(False) + + def shutdown(self): + if self.worker: + self.worker.requestInterruption() + self.worker.stop_event.set() + self.worker.wait() diff --git a/python/set_devices/qt_ports/widget_helpers.py b/python/set_devices/qt_ports/widget_helpers.py new file mode 100644 index 0000000..f7f1198 --- /dev/null +++ b/python/set_devices/qt_ports/widget_helpers.py @@ -0,0 +1,81 @@ +"""Shared scroll areas and read-only tables for Qt workspaces.""" + +from __future__ import annotations + +try: + from PySide6.QtCore import Qt + from PySide6.QtGui import QAction, QKeySequence + from PySide6.QtWidgets import ( + QAbstractItemView, QApplication, QHeaderView, QScrollArea, QTableWidget, QVBoxLayout, QWidget, + ) +except ImportError: + from PySide2.QtCore import Qt + from PySide2.QtGui import QKeySequence + from PySide2.QtWidgets import ( + QAbstractItemView, QAction, QApplication, QHeaderView, QScrollArea, QTableWidget, QVBoxLayout, QWidget, + ) + + +def make_scrollable(content: QWidget) -> QScrollArea: + """Wrap a widget in a resizable, frameless scroll area.""" + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QScrollArea.NoFrame) + scroll.setWidget(content) + return scroll + + +def make_settings_page(settings: QWidget) -> QScrollArea: + """Keep settings at the top of a scrollable page.""" + page = QWidget() + layout = QVBoxLayout(page) + layout.setContentsMargins(12, 12, 12, 12) + layout.addWidget(settings) + layout.addStretch(1) + return make_scrollable(page) + + +def copy_table_selection(table: QTableWidget) -> str: + """Copy the selected cells as tab-separated rows.""" + indexes = sorted(table.selectedIndexes(), key=lambda item: (item.row(), item.column())) + if not indexes: + return "" + + rows: dict[int, list[str]] = {} + for index in indexes: + value = index.data() + rows.setdefault(index.row(), []).append("" if value is None else str(value)) + text = "\n".join("\t".join(values) for values in rows.values()) + QApplication.clipboard().setText(text) + return text + + +def enable_table_copy(table: QTableWidget) -> None: + """Add Ctrl+C and a copy action to the table.""" + table.setSelectionMode(QTableWidget.ExtendedSelection) + action = QAction("Копировать выбранное", table) + action.setShortcut(QKeySequence.Copy) + action.setShortcutContext(Qt.WidgetShortcut) + action.triggered.connect(lambda: copy_table_selection(table)) + table.addAction(action) + table.setContextMenuPolicy(Qt.ActionsContextMenu) + table.setToolTip( + "Выделите одну или несколько строк и нажмите Ctrl+C; " + "копирование также доступно по правой кнопке мыши." + ) + + +def make_monitor_table(headers, *, font, widths=()) -> QTableWidget: + """Create a read-only monitor table with row selection and clipboard support.""" + table = QTableWidget(0, len(headers)) + table.setHorizontalHeaderLabels(headers) + table.setEditTriggers(QAbstractItemView.NoEditTriggers) + table.setSelectionBehavior(QAbstractItemView.SelectRows) + enable_table_copy(table) + table.verticalHeader().setVisible(False) + table.setFont(font) + for column, width in enumerate(widths): + table.setColumnWidth(column, width) + if headers: + table.horizontalHeader().setSectionResizeMode(len(headers) - 1, QHeaderView.Stretch) + return table