Files
PDFReaderLite/pdfreaderlite/app.py
T
2026-07-02 12:12:22 +08:00

82 lines
2.3 KiB
Python

from __future__ import annotations
import logging
import sys
from pathlib import Path
from PySide6.QtCore import QtMsgType, QStandardPaths, qInstallMessageHandler
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication, QMessageBox
from pdfreaderlite import __version__
from pdfreaderlite.resources import software_icon_path
from pdfreaderlite.ui.main_window import MainWindow
def configure_logging() -> Path:
log_dir = Path(
QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
)
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / "PDFReaderLite.log"
logging.basicConfig(
filename=log_path,
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
encoding="utf-8",
)
logging.info("PDFReaderLite %s started", __version__)
return log_path
def install_qt_message_logger() -> None:
level_map = {
QtMsgType.QtDebugMsg: logging.DEBUG,
QtMsgType.QtInfoMsg: logging.INFO,
QtMsgType.QtWarningMsg: logging.WARNING,
QtMsgType.QtCriticalMsg: logging.ERROR,
QtMsgType.QtFatalMsg: logging.CRITICAL,
}
def handler(message_type, context, message) -> None:
level = level_map.get(message_type, logging.INFO)
logging.getLogger("Qt").log(
level,
"%s (%s:%s)",
message,
context.file or "",
context.line,
)
qInstallMessageHandler(handler)
def main() -> int:
app = QApplication(sys.argv)
app.setApplicationName("PDFReaderLite")
app.setOrganizationName("PDFReaderLite")
app.setApplicationVersion(__version__)
app.setWindowIcon(QIcon(software_icon_path().as_posix()))
log_path = configure_logging()
install_qt_message_logger()
def handle_exception(exc_type, exc_value, exc_traceback) -> None:
logging.exception("Unhandled exception", exc_info=(exc_type, exc_value, exc_traceback))
QMessageBox.critical(
None,
"程序错误",
f"PDFReaderLite 遇到未处理错误。\n\n日志位置:{log_path}",
)
sys.excepthook = handle_exception
window = MainWindow()
window.show()
if len(sys.argv) > 1:
window.open_file(sys.argv[1])
else:
window.offer_restore_last_file()
return app.exec()