|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +from collections import deque |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from pymmcore_plus import CMMCorePlus |
| 8 | +from qtpy.QtCore import QFileSystemWatcher, QObject, QTimer, QUrl, Signal |
| 9 | +from qtpy.QtGui import QCloseEvent, QDesktopServices, QFontDatabase, QPalette |
| 10 | +from qtpy.QtWidgets import ( |
| 11 | + QApplication, |
| 12 | + QHBoxLayout, |
| 13 | + QPlainTextEdit, |
| 14 | + QPushButton, |
| 15 | + QSizePolicy, |
| 16 | + QVBoxLayout, |
| 17 | + QWidget, |
| 18 | +) |
| 19 | +from superqt import QElidingLabel, QIconifyIcon |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from io import TextIOWrapper |
| 23 | + |
| 24 | + |
| 25 | +class _LogReader(QObject): |
| 26 | + """Watches a log file and emits new lines as they arrive.""" |
| 27 | + |
| 28 | + new_lines: Signal = Signal(str) |
| 29 | + finished: Signal = Signal() |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, |
| 33 | + path: str, |
| 34 | + interval: int = 200, |
| 35 | + parent: QObject | None = None, |
| 36 | + ) -> None: |
| 37 | + super().__init__(parent) |
| 38 | + self._path = path |
| 39 | + self._interval = interval |
| 40 | + self._file: TextIOWrapper | None = None |
| 41 | + |
| 42 | + # Unfortunately, on Windows, QFileSystemWatcher does not detect file changes |
| 43 | + # unless the file is flushed from cache to disk. This does NOT happen |
| 44 | + # when CMMCorePlus.logMessage() is called. So we need to poll the file for |
| 45 | + # Windows' sake. |
| 46 | + self._timer = QTimer(self) |
| 47 | + self._timer.setInterval(self._interval) |
| 48 | + self._timer.timeout.connect(self._read_new) |
| 49 | + |
| 50 | + # Watcher for rotation/truncate events |
| 51 | + self._watcher = QFileSystemWatcher(self) |
| 52 | + self._watcher.addPath(self._path) |
| 53 | + self._watcher.fileChanged.connect(self._on_file_changed) |
| 54 | + |
| 55 | + def start(self) -> None: |
| 56 | + """Open the file and start polling.""" |
| 57 | + self._file = open(self._path, encoding="utf-8", errors="replace") |
| 58 | + self._file.seek(0, os.SEEK_END) |
| 59 | + self._timer.start() |
| 60 | + |
| 61 | + def _stop(self) -> None: |
| 62 | + """Stop polling and close the file.""" |
| 63 | + self._timer.stop() |
| 64 | + if self._file: |
| 65 | + self._file.close() |
| 66 | + self.finished.emit() |
| 67 | + |
| 68 | + def _on_file_changed(self, path: str) -> None: |
| 69 | + """Handle log rotation or truncation.""" |
| 70 | + try: |
| 71 | + real_size = os.path.getsize(path) |
| 72 | + current_pos = self._file.tell() if self._file else 0 |
| 73 | + if real_size < current_pos: |
| 74 | + # rotated or truncated |
| 75 | + if self._file: |
| 76 | + self._file.close() |
| 77 | + self._file = open(self._path, encoding="utf-8", errors="replace") |
| 78 | + self._read_new() |
| 79 | + except Exception: |
| 80 | + pass |
| 81 | + |
| 82 | + def _read_new(self) -> None: |
| 83 | + """Read and emit any new lines.""" |
| 84 | + if not self._file: |
| 85 | + return |
| 86 | + for line in self._file: |
| 87 | + self.new_lines.emit(line.rstrip("\n")) |
| 88 | + |
| 89 | + |
| 90 | +class CoreLogWidget(QWidget): |
| 91 | + """High-performance log console with pause, follow-tail, clear, and initial load.""" |
| 92 | + |
| 93 | + def __init__( |
| 94 | + self, |
| 95 | + path: str | None = None, |
| 96 | + max_lines: int = 5_000, |
| 97 | + parent: QWidget | None = None, |
| 98 | + mmcore: CMMCorePlus | None = None, |
| 99 | + ) -> None: |
| 100 | + super().__init__(parent) |
| 101 | + self._mmcore = mmcore or CMMCorePlus().instance() |
| 102 | + self.setWindowTitle("Log Console") |
| 103 | + |
| 104 | + # --- Log path --- |
| 105 | + self._log_path = QElidingLabel() |
| 106 | + self._log_path.setSizePolicy( |
| 107 | + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum |
| 108 | + ) |
| 109 | + |
| 110 | + self._clear_btn = QPushButton("Clear Display") |
| 111 | + self._clear_btn.setToolTip( |
| 112 | + "Clears this view. Does not delete lines from the log file." |
| 113 | + ) |
| 114 | + |
| 115 | + self._log_btn = QPushButton() |
| 116 | + color = QApplication.palette().color(QPalette.ColorRole.WindowText).name() |
| 117 | + self._log_btn.setIcon(QIconifyIcon("majesticons:open", color=color)) |
| 118 | + self._log_btn.setToolTip("Open log file in native editor") |
| 119 | + |
| 120 | + # --- Log view --- |
| 121 | + self._log_view = QPlainTextEdit(self) |
| 122 | + self._log_view.setReadOnly(True) |
| 123 | + self._log_view.setMaximumBlockCount(max_lines) |
| 124 | + self._log_view.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap) |
| 125 | + # Monospaced font |
| 126 | + fixed_font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont) |
| 127 | + fixed_font.setPixelSize(12) |
| 128 | + self._log_view.setFont(fixed_font) |
| 129 | + |
| 130 | + path = path or self._mmcore.getPrimaryLogFile() |
| 131 | + self._log_path.setText(path) |
| 132 | + # Load the last `max_lines` from file |
| 133 | + try: |
| 134 | + with open(path, encoding="utf-8", errors="replace") as f: |
| 135 | + for line in deque(f, maxlen=max_lines): |
| 136 | + self._log_view.appendPlainText(line.rstrip("\n")) |
| 137 | + except Exception: |
| 138 | + pass |
| 139 | + |
| 140 | + # --- Reader thread setup --- |
| 141 | + self._reader = _LogReader(path) |
| 142 | + |
| 143 | + # --- Layout --- |
| 144 | + file_layout = QHBoxLayout() |
| 145 | + file_layout.setContentsMargins(5, 5, 5, 0) |
| 146 | + file_layout.addWidget(self._log_path) |
| 147 | + file_layout.addWidget(self._clear_btn) |
| 148 | + file_layout.addWidget(self._log_btn) |
| 149 | + |
| 150 | + layout = QVBoxLayout(self) |
| 151 | + layout.setContentsMargins(0, 0, 0, 0) |
| 152 | + layout.addLayout(file_layout) |
| 153 | + layout.addWidget(self._log_view) |
| 154 | + self.setLayout(layout) |
| 155 | + |
| 156 | + # --- Connections --- |
| 157 | + self._reader.new_lines.connect(self._append_line) |
| 158 | + self._clear_btn.clicked.connect(self._log_view.clear) |
| 159 | + self._log_btn.clicked.connect(self._open_native) |
| 160 | + self._reader.start() |
| 161 | + |
| 162 | + def __del__(self) -> None: |
| 163 | + """Stop reader before deletion.""" |
| 164 | + self._reader._stop() |
| 165 | + |
| 166 | + def _append_line(self, line: str) -> None: |
| 167 | + """Append a line, respecting pause/follow settings.""" |
| 168 | + self._log_view.appendPlainText(line) |
| 169 | + |
| 170 | + def closeEvent(self, event: QCloseEvent | None) -> None: |
| 171 | + """Clean up thread on close.""" |
| 172 | + self._reader._stop() |
| 173 | + # self._thread.quit() |
| 174 | + # self._thread.wait() |
| 175 | + super().closeEvent(event) |
| 176 | + |
| 177 | + def _open_native(self) -> None: |
| 178 | + """Open the log file in the system's default text editor.""" |
| 179 | + QDesktopServices.openUrl(QUrl.fromLocalFile(self._mmcore.getPrimaryLogFile())) |
0 commit comments