Files
MDHelper/mdhelper/app.py
T
2026-05-26 18:05:10 +08:00

81 lines
3.0 KiB
Python

from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
from PySide6.QtCore import QSettings, Qt
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication
from . import __version__
from .doc_check import main as check_documents_main
from .logging_config import setup_logging
from .main_window import MainWindow
def parse_arguments(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="MDHelper 本地 Markdown 帮助文档阅读器")
parser.add_argument("file", nargs="?", help="启动后打开的 Markdown、网页或本地文件")
parser.add_argument("--check", action="store_true", help="检查 sample.md 和 docs/ 中缺失的本地链接/媒体")
parser.add_argument("--project-root", default=None, help="项目根目录,默认使用 MDHelper 所在目录")
return parser.parse_args(argv)
def runtime_paths() -> tuple[Path, Path]:
if getattr(sys, "frozen", False):
content_root = Path(getattr(sys, "_MEIPASS")).resolve()
log_root = Path(sys.executable).resolve().parent
return content_root, log_root
root = Path(__file__).resolve().parent.parent
return root, root
def main(argv: list[str] | None = None) -> int:
args = parse_arguments(list(sys.argv[1:] if argv is None else argv))
content_root, log_root = runtime_paths()
cli_initial_path = Path(args.file).expanduser().resolve() if args.file else None
cli_project_root = Path(args.project_root).expanduser().resolve() if args.project_root else None
project_root = cli_project_root
if project_root is None and cli_initial_path is not None:
project_root = cli_initial_path.parent if cli_initial_path.is_file() else cli_initial_path
if args.check:
return check_documents_main([str(project_root or content_root)])
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True)
setup_logging(log_root)
app = QApplication([sys.argv[0]])
app.setApplicationName("MDHelper")
app.setApplicationVersion(__version__)
app.setOrganizationName("MDHelper")
settings = QSettings("MDHelper", "MDHelper")
if project_root is None:
last_project_root = Path(str(settings.value("project/last_root", ""))).expanduser()
if str(last_project_root) and last_project_root.exists():
project_root = last_project_root.resolve()
logging.getLogger(__name__).info(
"Starting MDHelper %s with project_root=%s content_root=%s log_root=%s",
__version__,
project_root,
content_root,
log_root,
)
icon_path = content_root / "icon_glass.png"
if icon_path.exists():
app.setWindowIcon(QIcon(str(icon_path)))
window = MainWindow(
project_root=project_root,
initial_path=cli_initial_path if cli_initial_path is not None and cli_initial_path.is_file() else None,
app_root=content_root,
prompt_for_project=project_root is None,
)
window.show()
return app.exec()