"""로그 — 프로그램을 켠 뒤 남은 기록 전체. 복사하거나 파일로 저장해 보낼 수 있다.""" from __future__ import annotations import platform from datetime import datetime from PySide6.QtCore import Signal from PySide6.QtGui import QFontDatabase, QGuiApplication from PySide6.QtWidgets import ( QFileDialog, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget, ) from ...config import AppConfig from ...constants import APP_NAME, APP_VERSION, user_data_dir from ...log_buffer import BUFFER, MAX_RECORDS, LogBuffer from ..theme import SPACING from ..widgets import Card, PageHeader class LogPage(QWidget): #: 로그는 아무 스레드에서나 들어오므로 시그널로 GUI 스레드에 넘긴다. line_logged = Signal(str) def __init__( self, config: AppConfig, buffer: LogBuffer = BUFFER, parent: QWidget | None = None ): super().__init__(parent) self.config = config self.buffer = buffer root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) root.setSpacing(SPACING + 4) root.addWidget( PageHeader( "로그", "프로그램을 켠 뒤 남은 기록 전체입니다. 문제가 생기면 '복사'나 " "'파일로 저장'을 눌러 그대로 보내 주세요.", ) ) card = Card() buttons = QWidget() row = QHBoxLayout(buttons) row.setContentsMargins(0, 0, 0, 0) row.setSpacing(10) self.copy_button = QPushButton("복사") self.copy_button.setObjectName("Primary") self.copy_button.clicked.connect(self.copy_to_clipboard) self.save_button = QPushButton("파일로 저장") self.save_button.clicked.connect(self._save_dialog) self.clear_button = QPushButton("화면 비우기") self.clear_button.setToolTip( "이 화면만 비웁니다. 복사·저장에는 이번 실행 기록이 전부 그대로 들어갑니다." ) self.clear_button.clicked.connect(self.clear) for button in (self.copy_button, self.save_button, self.clear_button): row.addWidget(button) row.addStretch(1) self.notice = QLabel() self.notice.setObjectName("Hint") row.addWidget(self.notice) card.add(buttons) self.view = QPlainTextEdit() self.view.setReadOnly(True) self.view.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth) self.view.setMaximumBlockCount(MAX_RECORDS) self.view.setFont(QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)) self.view.setMinimumHeight(520) card.add(self.view) root.addWidget(card, 1) self.view.setPlainText(buffer.text()) self.line_logged.connect(self._append) signal = self.line_logged def forward(line: str) -> None: try: signal.emit(line) except RuntimeError: # 창이 이미 사라졌다 buffer.unsubscribe(forward) self._forward = forward buffer.subscribe(forward) # --- 동작 ----------------------------------------------------------- def report(self) -> str: """보낼 내용 전체. 맨 위에 실행 환경을 붙여서 로그만 봐도 상황을 알게 한다.""" models = self.config.models audio = self.config.audio header = [ f"{APP_NAME} v{APP_VERSION} · {platform.platform()} · Python {platform.python_version()}", f"티어 {models.tier} · 장치 {models.device} · 원본 {models.source_lang} → " f"번역 {models.target_lang} · 소리 {audio.backend}" f"{' ' + audio.target_process_name if audio.backend == 'process' else ''}", f"저장 위치 {user_data_dir()} · 기록 시각 {datetime.now():%Y-%m-%d %H:%M:%S}", "-" * 60, ] return "\n".join(header) + "\n" + self.buffer.full_text() + "\n" def copy_to_clipboard(self) -> None: text = self.report() QGuiApplication.clipboard().setText(text) self.notice.setText(f"{text.count(chr(10))}줄을 복사했습니다") def save_to(self, path: str) -> None: with open(path, "w", encoding="utf-8") as f: f.write(self.report()) self.notice.setText(f"저장했습니다: {path}") def _save_dialog(self) -> None: default = user_data_dir() / datetime.now().strftime("livesub-log-%Y%m%d-%H%M%S.txt") path, _ = QFileDialog.getSaveFileName( self, "로그 저장", str(default), "텍스트 파일 (*.txt)" ) if not path: return try: self.save_to(path) except OSError as exc: self.notice.setText(f"저장하지 못했습니다: {exc}") def clear(self) -> None: self.buffer.clear() self.view.clear() self.notice.setText("") def _append(self, line: str) -> None: bar = self.view.verticalScrollBar() at_bottom = bar.value() >= bar.maximum() - 4 self.view.appendPlainText(line) # 위로 올려 읽는 중이면 끌어내리지 않는다. if at_bottom: bar.setValue(bar.maximum()) def showEvent(self, event) -> None: # noqa: N802 # 숨어 있는 동안 쌓인 줄은 스크롤 위치를 못 맞춘다. 열 때 최신 줄로 내린다. super().showEvent(event) bar = self.view.verticalScrollBar() bar.setValue(bar.maximum())