From ad7f1c39ef473a327ca3b467b579be0099377f55 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:17:00 -0600 Subject: Make Run the master stop switch; add Log button disabled/recording styling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run/Stop previously only paused acquisition — control outputs (motor speed, switches, PWM duty) kept whatever value was last written, so stopping the run loop didn't stop a running motor. Adds ControlWidget.safe_stop() (per-widget override, default zeros the output) and ControlPanel.safe_stop_all(), called from _toggle_run's Stop branch before engine.stop(). Per-widget behavior is deliberately not uniform: - OnOffSwitch/MotorControl/PwmControl have a latched running/enabled state, so safe_stop() drives their own toggle handler (consistent UI + write in one path) and, for Motor/PWM, zeroes the slider too. - SetpointControl/AnalogOutputControl only write on an explicit user action and have no universally safe forced value (e.g. 0 isn't necessarily "off" for an arbitrary process setpoint or analog output) — Stop leaves them untouched rather than guessing. Log button: added a :disabled QSS rule so "can't log yet" reads as clearly inert rather than a duller version of the enabled look, and a 600ms blink (toggling a "recording" dynamic property the QSS keys off) while a recording is active, so it reads as live/recording rather than a static pressed button. Master Stop now calls _toggle_log(False) explicitly when forcing the button off, since QPushButton.setChecked() doesn't emit clicked — without this the blink would keep running after a master Stop even though logging itself already halted via engine.stop()'s internal stop_logging() call. Co-Authored-By: Claude Sonnet 5 --- ui/main_window.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'ui/main_window.py') diff --git a/ui/main_window.py b/ui/main_window.py index d0e0ac4..268a9d3 100644 --- a/ui/main_window.py +++ b/ui/main_window.py @@ -196,6 +196,9 @@ class MainWindow(QMainWindow): self._clock = QTimer(self); self._clock.setInterval(1000) self._clock.timeout.connect(self._tick) + self._rec_blink = QTimer(self); self._rec_blink.setInterval(600) + self._rec_blink.timeout.connect(self._tick_rec_blink) + def _connect_signals(self): self.engine.new_data.connect(self.processor.on_raw_data) self.processor.processed_data.connect(self._chart.on_new_data) @@ -521,9 +524,12 @@ class MainWindow(QMainWindow): self._run_btn.setText("⏹ STOP"); self._log_btn.setEnabled(True) self._clock.start(); self._status.setText("Acquiring…") else: + self._ctrl.safe_stop_all() # master switch — stop outputs before halting acquisition self.engine.stop() self._run_btn.setText("▶ RUN") - if self._log_btn.isChecked(): self._log_btn.setChecked(False) + if self._log_btn.isChecked(): + self._log_btn.setChecked(False) + self._toggle_log(False) # setChecked() alone won't fire clicked — stop blink/logging explicitly self._log_btn.setEnabled(False); self._clock.stop() self._status.setText("Stopped") @@ -539,8 +545,18 @@ class MainWindow(QMainWindow): os.path.join(self._settings.get("log_dir", "logs"), "")) self._log_btn.setText("⏹ LOGGING") self._status.setText(f"Logging → {p}") + self._rec_blink.start() else: self.engine.stop_logging(); self._log_btn.setText("⬤ LOG") + self._rec_blink.stop() + self._log_btn.setProperty("recording", False) + self._log_btn.style().unpolish(self._log_btn); self._log_btn.style().polish(self._log_btn) + + def _tick_rec_blink(self): + """Pulse the Log button's background while a recording is active.""" + on = not self._log_btn.property("recording") + self._log_btn.setProperty("recording", on) + self._log_btn.style().unpolish(self._log_btn); self._log_btn.style().polish(self._log_btn) # ── Theme / settings ────────────────────────────────────────────────── -- cgit v1.2.3 From 45ff7227fabb97273d4645601733f90f5f744eb1 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:21:05 -0600 Subject: Check plugin dependencies before loading, warn instead of silent console error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit manifest.json already had an unused "requires" field (motion_capture's manifest lists opencv-python>=4.8.0) — PluginManifest never parsed it, so a missing dependency just crashed the import inside _load_plugin(), caught by the broad except and only ever printed to the console. Adds PluginManifest.requires, PluginManager.missing_requirements()/ get_missing_dependencies(), and an early check in _load_plugin() that skips the risky import entirely when a requirement is missing. main_window.plugin_enable() now checks this before calling PluginManager.enable() and shows a QMessageBox with the missing packages and a pip install command instead of failing silently. Checks by distribution name via importlib.metadata (what pip installed it as), not import name — those differ for packages like opencv-python (imports as cv2) or pyserial (imports as serial), so importlib.util. find_spec() would give false negatives. Also fixes a button-state bug this surfaces: SettingsWindow's plugin toggle optimistically flipped to "Disable" the instant Enable was clicked, before knowing whether enabling actually succeeds — pre-existing, but now trivially reproducible (any plugin missing a dependency). Enable no longer flips the button immediately; main_window calls the new sync_plugin_button() once the real outcome is known. Co-Authored-By: Claude Sonnet 5 --- plugins/plugin_manager.py | 40 +++++++++++++++++++++++++++++++++++++++- ui/main_window.py | 20 ++++++++++++++++---- ui/windows/settings_window.py | 12 +++++++++++- 3 files changed, 66 insertions(+), 6 deletions(-) (limited to 'ui/main_window.py') diff --git a/plugins/plugin_manager.py b/plugins/plugin_manager.py index 36ae71a..5cefc2e 100644 --- a/plugins/plugin_manager.py +++ b/plugins/plugin_manager.py @@ -10,12 +10,14 @@ per-plugin state separately via get_save_state / apply_save_state. from __future__ import annotations +import importlib.metadata import importlib.util import json import os +import re import sys import traceback -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Dict, List, Optional from plugins.base_plugin import LabPlugin, PluginContext @@ -35,9 +37,35 @@ class PluginManifest: description: str = "" author: str = "" entry_point: str = "plugin.Plugin" # "module.ClassName" relative to plugin dir + requires: List[str] = field(default_factory=list) # pip-style reqs, e.g. "opencv-python>=4.8.0" plugin_dir: str = "" +def _dist_name(requirement: str) -> str: + """Extract the distribution name from a requirement string, e.g. + "opencv-python>=4.8.0" -> "opencv-python".""" + return re.split(r"[<>=!~\[; ]", requirement.strip(), maxsplit=1)[0] + + +def missing_requirements(requires: List[str]) -> List[str]: + """Return the subset of `requires` whose distribution isn't installed. + + Checked by distribution name via importlib.metadata (matches what pip + installed it as), not by import name — those differ for packages like + opencv-python (imports as cv2) or pyserial (imports as serial). + """ + missing = [] + for req in requires: + name = _dist_name(req) + if not name: + continue + try: + importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + missing.append(req) + return missing + + # ── Manager ─────────────────────────────────────────────────────────────────── class PluginManager: @@ -94,6 +122,7 @@ class PluginManager: description = data.get("description", ""), author = data.get("author", ""), entry_point = data.get("entry_point", "plugin.Plugin"), + requires = data.get("requires", []), plugin_dir = plugin_dir, ) self._manifests[m.plugin_id] = m @@ -146,6 +175,11 @@ class PluginManager: print(f"[PluginManager] No manifest for '{plugin_id}'") return None + missing = missing_requirements(manifest.requires) + if missing: + print(f"[Plugin] '{plugin_id}' missing dependencies: {', '.join(missing)}") + return None + module_name, class_name = manifest.entry_point.rsplit(".", 1) module_file = os.path.join( manifest.plugin_dir, *module_name.split("/") @@ -218,6 +252,10 @@ class PluginManager: def get_manifests(self) -> List[PluginManifest]: return list(self._manifests.values()) + def get_missing_dependencies(self, plugin_id: str) -> List[str]: + manifest = self._manifests.get(plugin_id) + return missing_requirements(manifest.requires) if manifest else [] + def get_loaded(self) -> List[LabPlugin]: return list(self._loaded.values()) diff --git a/ui/main_window.py b/ui/main_window.py index d0e0ac4..95cdb84 100644 --- a/ui/main_window.py +++ b/ui/main_window.py @@ -296,10 +296,22 @@ class MainWindow(QMainWindow): def plugin_enable(self, plugin_id: str): """Called by SettingsWindow when user enables a plugin.""" - ctx = self._make_plugin_context() - plugin = self._plugin_mgr.enable(plugin_id, ctx) - if plugin: - self._install_plugin(plugin) + missing = self._plugin_mgr.get_missing_dependencies(plugin_id) + if missing: + from PyQt6.QtWidgets import QMessageBox + QMessageBox.warning( + self, "Missing Plugin Dependencies", + f"Can't enable this plugin — missing Python packages:\n\n" + f" {', '.join(missing)}\n\n" + f"Install with:\n pip install {' '.join(missing)}" + ) + else: + ctx = self._make_plugin_context() + plugin = self._plugin_mgr.enable(plugin_id, ctx) + if plugin: + self._install_plugin(plugin) + if self._win_settings: + self._win_settings.sync_plugin_button(plugin_id) def plugin_disable(self, plugin_id: str): """Called by SettingsWindow when user disables a plugin.""" diff --git a/ui/windows/settings_window.py b/ui/windows/settings_window.py index 1630efa..553a3a7 100644 --- a/ui/windows/settings_window.py +++ b/ui/windows/settings_window.py @@ -50,6 +50,7 @@ class SettingsWindow(QWidget): self.registry = registry self.engine = engine self._plugin_mgr = plugin_manager + self._plugin_buttons: dict = {} # plugin_id -> QPushButton self.cfg = dict(self._defaults) if current: self.cfg.update(current) @@ -233,6 +234,7 @@ class SettingsWindow(QWidget): toggle.clicked.connect( lambda _, pid=manifest.plugin_id, btn=toggle: self._toggle_plugin(pid, btn) ) + self._plugin_buttons[manifest.plugin_id] = toggle hdr.addWidget(toggle) cl.addLayout(hdr) @@ -261,8 +263,16 @@ class SettingsWindow(QWidget): self.plugin_disable_requested.emit(plugin_id) btn.setText("Enable") else: + # Don't flip to "Disable" yet — enabling can fail (missing + # dependencies, bad plugin code). main_window confirms the + # real outcome via sync_plugin_button() once enable() returns. self.plugin_enable_requested.emit(plugin_id) - btn.setText("Disable") + + def sync_plugin_button(self, plugin_id: str): + """Refresh one plugin's toggle button to match its actual enabled state.""" + btn = self._plugin_buttons.get(plugin_id) + if btn is not None and self._plugin_mgr is not None: + btn.setText("Disable" if self._plugin_mgr.is_enabled(plugin_id) else "Enable") # ── Actions ─────────────────────────────────────────────────────────── -- cgit v1.2.3 From 2298f779fdf7d828c1a84ca933b4eee9e8103212 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:22:26 -0600 Subject: Offer to pip install missing plugin dependencies instead of just warning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds on the previous branch's dependency check: the missing-deps QMessageBox is now a Yes/No prompt. Yes runs a blocking `sys.executable -m pip install ` (subprocess.run, output captured), shows a result dialog, and on success proceeds straight to enabling the plugin — no need to click Enable a second time. Blocking is a deliberate simplification, not an oversight: this codebase has no worker-thread/progress-dialog pattern for slow operations anywhere else, so a threaded installer would be inconsistent with everything else here. pip install is a one-time, infrequent action, unlike e.g. a serial connect that runs constantly. Co-Authored-By: Claude Sonnet 5 --- ui/main_window.py | 51 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 7 deletions(-) (limited to 'ui/main_window.py') diff --git a/ui/main_window.py b/ui/main_window.py index 95cdb84..c04230c 100644 --- a/ui/main_window.py +++ b/ui/main_window.py @@ -299,20 +299,57 @@ class MainWindow(QMainWindow): missing = self._plugin_mgr.get_missing_dependencies(plugin_id) if missing: from PyQt6.QtWidgets import QMessageBox - QMessageBox.warning( + reply = QMessageBox.question( self, "Missing Plugin Dependencies", - f"Can't enable this plugin — missing Python packages:\n\n" + f"This plugin needs packages that aren't installed:\n\n" f" {', '.join(missing)}\n\n" - f"Install with:\n pip install {' '.join(missing)}" + f"Install them now with pip?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No, ) + if reply == QMessageBox.StandardButton.Yes: + if self._pip_install(missing): + self._enable_plugin_now(plugin_id) else: - ctx = self._make_plugin_context() - plugin = self._plugin_mgr.enable(plugin_id, ctx) - if plugin: - self._install_plugin(plugin) + self._enable_plugin_now(plugin_id) if self._win_settings: self._win_settings.sync_plugin_button(plugin_id) + def _enable_plugin_now(self, plugin_id: str): + ctx = self._make_plugin_context() + plugin = self._plugin_mgr.enable(plugin_id, ctx) + if plugin: + self._install_plugin(plugin) + + def _pip_install(self, requirements: list) -> bool: + """Blocking `pip install` of the given requirement strings. + Returns True on success; shows a result dialog either way.""" + import subprocess + import sys + from PyQt6.QtWidgets import QMessageBox + + QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor) + try: + result = subprocess.run( + [sys.executable, "-m", "pip", "install", *requirements], + capture_output=True, text=True, + ) + finally: + QApplication.restoreOverrideCursor() + + if result.returncode == 0: + QMessageBox.information( + self, "Install Complete", + f"Installed: {', '.join(requirements)}" + ) + return True + QMessageBox.critical( + self, "Install Failed", + f"pip install failed for: {', '.join(requirements)}\n\n" + f"{result.stderr.strip()[-1500:]}" + ) + return False + def plugin_disable(self, plugin_id: str): """Called by SettingsWindow when user disables a plugin.""" self._uninstall_plugin(plugin_id) -- cgit v1.2.3 From cf33095f77e6ff902fb69932fa704eb6192b3418 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:28:24 -0600 Subject: Add Developer Mode setting, Debug window, and gate simulate behind it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Settings > General > "Developer mode" checkbox (default on, so this repo's simulate-by-default workflow is unaffected out of the box) persisted through the existing core/app_settings.py load/save functions. Exposed to code that can't easily receive the settings dict via core.app_settings.is_developer_mode()/set_developer_mode(), a small in-memory cache MainWindow keeps in sync whenever settings are loaded or applied. Debug window (ui/windows/debug_window.py): minimal first pass per the plan — a live console. core/debug_log.py tees stdout/stderr into a ring buffer + Qt signal (installed once in main.py, before anything prints), so the window shows everything printed since app start, including from background poll threads, not just what's printed while it happens to be open. Its toolbar button is hidden unless developer mode is on. Simulate gating: every device's Simulation Mode checkbox/dropdown is now hidden when developer mode is off — ui/add_device_dialog.py (also covers the motion_capture camera panel, which shares this same checkbox rather than having its own), and the per-device config widgets in analog_input.py, arduino_device.py, digital_io.py, nidaqmx_device.py, serial_device.py. Hiding rather than force-clearing an already-simulating device's state — an existing simulated device keeps working if developer mode is turned off later; the option is just not offered again until it's back on. Co-Authored-By: Claude Sonnet 5 --- core/app_settings.py | 19 +++++++++++++ core/debug_log.py | 65 +++++++++++++++++++++++++++++++++++++++++++ devices/analog_input.py | 2 ++ devices/arduino_device.py | 2 ++ devices/digital_io.py | 2 ++ devices/nidaqmx_device.py | 2 ++ devices/serial_device.py | 6 +++- main.py | 2 ++ ui/add_device_dialog.py | 2 ++ ui/main_window.py | 31 ++++++++++++++++++++- ui/windows/debug_window.py | 65 +++++++++++++++++++++++++++++++++++++++++++ ui/windows/settings_window.py | 11 ++++++++ 12 files changed, 207 insertions(+), 2 deletions(-) create mode 100644 core/debug_log.py create mode 100644 ui/windows/debug_window.py (limited to 'ui/main_window.py') diff --git a/core/app_settings.py b/core/app_settings.py index e8bc7ae..ea3ac49 100644 --- a/core/app_settings.py +++ b/core/app_settings.py @@ -51,3 +51,22 @@ def save_settings(cfg: dict) -> None: json.dump(cfg, f, indent=2) except Exception: pass + + +# ── Developer mode ──────────────────────────────────────────────────────── +# +# In-memory cache so widgets that build device/config UI (Add Device dialog, +# per-device config panels, plugin panels) can check this without needing +# the full settings dict threaded through their constructors. MainWindow +# keeps it in sync with the persisted setting whenever settings are +# loaded/applied — see set_developer_mode() calls in ui/main_window.py. +_dev_mode = True + + +def is_developer_mode() -> bool: + return _dev_mode + + +def set_developer_mode(value: bool) -> None: + global _dev_mode + _dev_mode = value diff --git a/core/debug_log.py b/core/debug_log.py new file mode 100644 index 0000000..86a8a59 --- /dev/null +++ b/core/debug_log.py @@ -0,0 +1,65 @@ +""" +core/debug_log.py + +Tees stdout/stderr into an in-memory ring buffer + Qt signal so the Debug +window can show everything the app has printed since startup — including +messages from background poll threads (e.g. "[CMLLayer] poll error: ...") — +not just whatever gets printed while the window happens to be open. + +install() should be called once, early, before anything prints. The real +streams are still written to, so running from a terminal is unaffected. +""" + +from __future__ import annotations + +import sys +from collections import deque +from typing import Optional + +from PyQt6.QtCore import QObject, pyqtSignal + + +class _Broadcaster(QObject): + line_written = pyqtSignal(str) + + +class _StreamTee: + def __init__(self, real_stream, lines: deque, broadcaster: _Broadcaster): + self._real = real_stream + self._lines = lines + self._broadcaster = broadcaster + + def write(self, text: str) -> None: + self._real.write(text) + if text: + self._lines.append(text) + self._broadcaster.line_written.emit(text) + + def flush(self) -> None: + self._real.flush() + + def isatty(self) -> bool: + return False + + +_lines: Optional[deque] = None +_broadcaster: Optional[_Broadcaster] = None + + +def install(max_lines: int = 2000) -> None: + """Redirect sys.stdout/sys.stderr through the tee. Safe to call once.""" + global _lines, _broadcaster + if _broadcaster is not None: + return + _lines = deque(maxlen=max_lines) + _broadcaster = _Broadcaster() + sys.stdout = _StreamTee(sys.stdout, _lines, _broadcaster) + sys.stderr = _StreamTee(sys.stderr, _lines, _broadcaster) + + +def get_broadcaster() -> Optional[_Broadcaster]: + return _broadcaster + + +def get_history() -> str: + return "".join(_lines) if _lines is not None else "" diff --git a/devices/analog_input.py b/devices/analog_input.py index c9e5d2a..6ac82d4 100644 --- a/devices/analog_input.py +++ b/devices/analog_input.py @@ -250,6 +250,8 @@ class AnalogInputConfigWidget(QWidget): self.sim_check = QCheckBox("Simulation Mode (no hardware)") self.sim_check.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_check.setVisible(is_developer_mode()) be_form.addRow(self.sim_check) root.addWidget(be_grp) diff --git a/devices/arduino_device.py b/devices/arduino_device.py index 7c1d21b..954d387 100644 --- a/devices/arduino_device.py +++ b/devices/arduino_device.py @@ -287,6 +287,8 @@ class ArduinoConfigWidget(QWidget): self.sim_chk = QCheckBox("Simulation Mode (no hardware)") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) ser_form.addRow(self.sim_chk) scan_row = QHBoxLayout() diff --git a/devices/digital_io.py b/devices/digital_io.py index 53395dc..2bd0243 100644 --- a/devices/digital_io.py +++ b/devices/digital_io.py @@ -290,6 +290,8 @@ class DigitalIOConfigWidget(QWidget): be_form.addRow("Backend:", self.be_cb) self.sim_chk = QCheckBox("Simulate") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) be_form.addRow(self.sim_chk) self.ni_dev_edit = QLineEdit(self.device._ni_device) diff --git a/devices/nidaqmx_device.py b/devices/nidaqmx_device.py index 88bb932..3f64998 100644 --- a/devices/nidaqmx_device.py +++ b/devices/nidaqmx_device.py @@ -294,6 +294,8 @@ class NidaqmxConfigWidget(QWidget): self.sim_chk = QCheckBox("Simulation Mode (no hardware)") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) ni_form.addRow(self.sim_chk) scan_row = QHBoxLayout() diff --git a/devices/serial_device.py b/devices/serial_device.py index 067656a..bd953b8 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -448,7 +448,11 @@ class SerialConfigWidget(QWidget): self._sim_cb = QComboBox() self._sim_cb.addItems(["Simulate", "Real Hardware"]) self._sim_cb.setCurrentIndex(0 if self.device.simulate else 1) - conn_form.addRow("Mode:", self._sim_cb) + from core.app_settings import is_developer_mode + mode_lbl = QLabel("Mode:") + dev_mode = is_developer_mode() + mode_lbl.setVisible(dev_mode); self._sim_cb.setVisible(dev_mode) + conn_form.addRow(mode_lbl, self._sim_cb) root.addWidget(conn_grp) diff --git a/main.py b/main.py index b023b99..ede6277 100644 --- a/main.py +++ b/main.py @@ -13,11 +13,13 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from PyQt6.QtWidgets import QApplication from ui.main_window import MainWindow +from core.debug_log import install as install_debug_log def main(): app = QApplication(sys.argv) app.setApplicationName("LabDAQ") + install_debug_log() # tee stdout/stderr for the Debug window, before anything prints qss = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ui", "style_dark.qss") if os.path.exists(qss): diff --git a/ui/add_device_dialog.py b/ui/add_device_dialog.py index 2956a96..4b2b373 100644 --- a/ui/add_device_dialog.py +++ b/ui/add_device_dialog.py @@ -17,6 +17,7 @@ from devices.device_registry import DeviceRegistry from devices.arduino_device import ArduinoDevice from devices.nidaqmx_device import NidaqmxDevice from devices.serial_device import SerialDevice, _FORMAT_LABELS +from core.app_settings import is_developer_mode # ── Background scan threads ─────────────────────────────────────────────────── @@ -276,6 +277,7 @@ class AddDeviceDialog(QDialog): conn_form.addRow(self._ni_lbl, self._ni_edit) self._sim_chk = QCheckBox("Simulation mode") + self._sim_chk.setVisible(is_developer_mode()) # dev-mode-only escape hatch conn_form.addRow(self._sim_chk) root.addLayout(conn_form) diff --git a/ui/main_window.py b/ui/main_window.py index d0e0ac4..ca4274c 100644 --- a/ui/main_window.py +++ b/ui/main_window.py @@ -45,7 +45,7 @@ from ui.windows.settings_window import SettingsWindow from plugins.plugin_manager import PluginManager from plugins.base_plugin import PluginContext -from core.app_settings import load_settings, save_settings +from core.app_settings import load_settings, save_settings, set_developer_mode _DARK_QSS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "style_dark.qss") @@ -68,6 +68,7 @@ class MainWindow(QMainWindow): self._win_channels = None self._win_plot = None self._win_settings = None + self._win_debug = None _plugins_dir = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), "plugins") @@ -171,6 +172,12 @@ class MainWindow(QMainWindow): set_btn.clicked.connect(lambda c: self._toggle_win("settings", c, set_btn)) tb.addWidget(set_btn); self._btn_settings = set_btn + debug_btn = QPushButton("🐞 Debug") + debug_btn.setObjectName("toolbarSectionBtn"); debug_btn.setCheckable(True) + debug_btn.clicked.connect(lambda c: self._toggle_win("debug", c, debug_btn)) + tb.addWidget(debug_btn); self._btn_debug = debug_btn + debug_btn.setVisible(False) # shown/hidden per developer-mode setting + # ── Central ─────────────────────────────────────────────────────── central = QWidget(); self.setCentralWidget(central) @@ -314,12 +321,14 @@ class MainWindow(QMainWindow): "channels": self._open_channels, "plot": self._open_plot, "settings": self._open_settings, + "debug": self._open_debug, } wins = { "devices": "_win_devices", "channels": "_win_channels", "plot": "_win_plot", "settings": "_win_settings", + "debug": "_win_debug", } if checked: creators[name]() @@ -370,6 +379,22 @@ class MainWindow(QMainWindow): self._win_settings.closed.connect(lambda: self._btn_settings.setChecked(False)) self._show_win(self._win_settings, "right") + def _open_debug(self): + from ui.windows.debug_window import DebugWindow + if self._win_debug is None: + self._win_debug = DebugWindow(self) + self._win_debug.closed.connect(lambda: self._btn_debug.setChecked(False)) + self._show_win(self._win_debug, "right") + + def _update_debug_btn_visibility(self): + from core.app_settings import is_developer_mode + on = is_developer_mode() + self._btn_debug.setVisible(on) + if not on: + self._btn_debug.setChecked(False) + if self._win_debug: + self._win_debug.hide() + def _show_win(self, win: QWidget, position: str = "right"): if not win.isVisible(): screen = QApplication.screenAt(self.geometry().center()) @@ -554,10 +579,14 @@ class MainWindow(QMainWindow): def _apply_settings_on_startup(self): self._apply_theme(self._settings.get("theme", "dark")) self.engine._interval = self._settings.get("poll_ms", 100) / 1000.0 + set_developer_mode(self._settings.get("developer_mode", True)) + self._update_debug_btn_visibility() def _on_settings(self, cfg: dict): self._settings.update(cfg) self.engine._interval = cfg.get("poll_ms", 100) / 1000.0 + set_developer_mode(self._settings.get("developer_mode", True)) + self._update_debug_btn_visibility() save_settings(self._settings) def _tick(self): diff --git a/ui/windows/debug_window.py b/ui/windows/debug_window.py new file mode 100644 index 0000000..0e891ed --- /dev/null +++ b/ui/windows/debug_window.py @@ -0,0 +1,65 @@ +""" +ui/windows/debug_window.py + +DEBUG window — developer-mode only. + +Minimal first pass: a live console showing everything the app has printed +via core.debug_log (stdout/stderr tee), so debugging doesn't require a +terminal. Not wired to any other diagnostics yet — extend as needed. +""" + +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, + QTextEdit, QFrame, +) +from PyQt6.QtCore import Qt, pyqtSignal +from PyQt6.QtGui import QFont, QCloseEvent + +from core.debug_log import get_broadcaster, get_history + + +class DebugWindow(QWidget): + closed = pyqtSignal() + + def __init__(self, parent=None): + super().__init__(parent, Qt.WindowType.Window | Qt.WindowType.Tool) + self.setWindowTitle("Debug") + self.setMinimumSize(560, 420) + self.resize(700, 500) + self._build() + + broadcaster = get_broadcaster() + if broadcaster is not None: + broadcaster.line_written.connect(self._append) + + def _build(self): + root = QVBoxLayout(self); root.setContentsMargins(0, 0, 0, 0); root.setSpacing(0) + + hdr = QWidget(); hdr.setObjectName("devWindowTitleBar"); hdr.setFixedHeight(44) + hl = QHBoxLayout(hdr); hl.setContentsMargins(14, 0, 14, 0) + title = QLabel("DEBUG"); title.setObjectName("devWindowTitle") + hl.addWidget(title, 1) + clear_btn = QPushButton("Clear"); clear_btn.setObjectName("configButton") + clear_btn.clicked.connect(lambda: self._console.clear()) + hl.addWidget(clear_btn) + root.addWidget(hdr) + + div = QFrame(); div.setFrameShape(QFrame.Shape.HLine) + div.setObjectName("devWindowDivider"); root.addWidget(div) + + self._console = QTextEdit(); self._console.setObjectName("codeEditor") + self._console.setReadOnly(True) + mono = QFont("IBM Plex Mono, Consolas, Monospace") + mono.setStyleHint(QFont.StyleHint.Monospace) + self._console.setFont(mono) + self._console.setPlainText(get_history()) + self._console.verticalScrollBar().setValue(self._console.verticalScrollBar().maximum()) + root.addWidget(self._console, 1) + + def _append(self, text: str): + self._console.insertPlainText(text) + sb = self._console.verticalScrollBar() + sb.setValue(sb.maximum()) + + def closeEvent(self, e: QCloseEvent): + self.closed.emit(); e.accept() diff --git a/ui/windows/settings_window.py b/ui/windows/settings_window.py index 1630efa..e24da7f 100644 --- a/ui/windows/settings_window.py +++ b/ui/windows/settings_window.py @@ -40,6 +40,7 @@ class SettingsWindow(QWidget): "show_grid": True, "font_size": 12, "antialias": True, + "developer_mode": True, } def __init__(self, registry: DeviceRegistry, @@ -108,6 +109,14 @@ class SettingsWindow(QWidget): self._aa_chk = QCheckBox(); self._aa_chk.setChecked(self.cfg["antialias"]) lay.addRow("Anti-alias plots:", self._aa_chk) + self._dev_chk = QCheckBox() + self._dev_chk.setChecked(self.cfg["developer_mode"]) + self._dev_chk.setToolTip( + "Controls whether the Debug window and each device's Simulation\n" + "Mode option are available. Off = real-hardware-only, no debug tools." + ) + lay.addRow("Developer mode:", self._dev_chk) + rst = QPushButton("Reset to Defaults"); rst.setObjectName("configButton") rst.clicked.connect(self._reset_to_defaults) lay.addRow("", rst) @@ -120,6 +129,7 @@ class SettingsWindow(QWidget): self._theme_cb.setCurrentText(self.cfg["theme"].title()) self._font_sp.setValue(self.cfg["font_size"]) self._aa_chk.setChecked(self.cfg["antialias"]) + self._dev_chk.setChecked(self.cfg["developer_mode"]) self._poll_sp.setValue(self.cfg["poll_ms"]) self._buf_sp.setValue(self.cfg["buffer_size"]) self._log_edit.setText(self.cfg["log_dir"]) @@ -288,6 +298,7 @@ class SettingsWindow(QWidget): "theme": theme, "font_size": self._font_sp.value(), "antialias": self._aa_chk.isChecked(), + "developer_mode": self._dev_chk.isChecked(), "poll_ms": self._poll_sp.value(), "buffer_size": self._buf_sp.value(), "log_dir": self._log_edit.text(), -- cgit v1.2.3