Files
MDHelper/mdhelper/main_window.py
T
2026-05-25 22:00:37 +08:00

2386 lines
95 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import html
import json
import logging
import os
import re
import shutil
import ctypes
from pathlib import Path
from urllib.parse import unquote, urlsplit
from PySide6.QtCore import QFileSystemWatcher, QObject, QProcess, QSettings, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot
from PySide6.QtGui import QAction, QActionGroup, QCloseEvent, QDesktopServices, QFont, QShowEvent
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineSettings
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import (
QApplication,
QFileDialog,
QFontDialog,
QInputDialog,
QLabel,
QLineEdit,
QDialog,
QMainWindow,
QMenu,
QMessageBox,
QProgressBar,
QSplitter,
QStatusBar,
QStyledItemDelegate,
QTabWidget,
QToolBar,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from .bookmark_dialog import BookmarkManagerDialog
from . import __version__
from .document_tree import DocumentEntry, discover_documents, first_heading
from .history import HistoryItem, NavigationHistory
from .markdown_utils import extract_headings
from .markdown_renderer import MarkdownRenderer
from .media import is_markdown_url, is_webpage_url, media_kind, media_mime_type
from .search import SearchIndex
from .settings_dialog import AppPreferences, SettingsDialog
BOOKMARKS_SETTING_KEY = "bookmarks/items"
SCROLL_POSITIONS_SETTING_KEY = "reader/scroll_positions"
EXTERNAL_APPLICATIONS_SETTING_KEY = "external_apps/by_extension"
LOGGER = logging.getLogger(__name__)
def re_find_markdown_links(source: str) -> list[str]:
markdown_targets = re.findall(r"!?\[[^\]]*]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", source)
html_targets = re.findall(r"""(?:src|href)=["']([^"']+)["']""", source, flags=re.IGNORECASE)
return markdown_targets + html_targets
class ReaderPage(QWebEnginePage):
anchor_requested = Signal(str)
local_link_requested = Signal(QUrl, bool)
external_url_requested = Signal(QUrl)
def acceptNavigationRequest(
self,
url: QUrl,
navigation_type: QWebEnginePage.NavigationType,
is_main_frame: bool,
) -> bool:
if navigation_type != QWebEnginePage.NavigationType.NavigationTypeLinkClicked:
return super().acceptNavigationRequest(url, navigation_type, is_main_frame)
if url.scheme() in {"http", "https"}:
self.external_url_requested.emit(url)
return False
if url.fragment() and not url.scheme():
self.anchor_requested.emit(url.fragment())
return False
if url.scheme() and url.scheme() not in {"file", "qrc"}:
self.external_url_requested.emit(url)
return False
if url.isLocalFile():
self.local_link_requested.emit(url, False)
return False
return super().acceptNavigationRequest(url, navigation_type, is_main_frame)
class ReaderBridge(QObject):
scroll_changed = Signal(float, str, int)
image_save_requested = Signal(str)
image_reveal_requested = Signal(str)
@Slot(float, str, int)
def reportScroll(self, progress: float, heading_id: str, scroll_y: int) -> None:
self.scroll_changed.emit(progress, heading_id, scroll_y)
@Slot(str)
def saveImage(self, url: str) -> None:
self.image_save_requested.emit(url)
@Slot(str)
def revealImage(self, url: str) -> None:
self.image_reveal_requested.emit(url)
class ReaderView(QWebEngineView):
open_link_requested = Signal(QUrl, bool)
def contextMenuEvent(self, event: object) -> None:
request = self.lastContextMenuRequest()
link_url = request.linkUrl()
if link_url.isValid() and not link_url.isEmpty():
menu = QMenu(self)
open_current = menu.addAction("在本标签页打开")
open_new = menu.addAction("新建标签页打开")
chosen = menu.exec(event.globalPos())
if chosen == open_current:
self.open_link_requested.emit(link_url, False)
request.setAccepted(True)
return
if chosen == open_new:
self.open_link_requested.emit(link_url, True)
request.setAccepted(True)
return
super().contextMenuEvent(event)
class CompactTreeDelegate(QStyledItemDelegate):
def sizeHint(self, option: object, index: object) -> object:
size = super().sizeHint(option, index)
line_height = option.fontMetrics.height()
size.setHeight(max(18, round(line_height * 1.16) + 2))
return size
class MainWindow(QMainWindow):
def __init__(self, project_root: Path, initial_path: Path | None = None) -> None:
super().__init__()
self.project_root = project_root.resolve()
self.renderer = MarkdownRenderer(self.project_root)
self.entries: list[DocumentEntry] = discover_documents(self.project_root)
self.search_index = SearchIndex(self.entries)
self.settings = QSettings("MDHelper", "MDHelper")
self.current_file: Path | None = None
self.current_fragment = ""
self.pending_fragment = ""
self.pending_find_text = ""
self.pending_scroll_y: int | None = None
self.font_scale = 1.0
self.theme = "light"
self.theme_color = "white"
self.theme_background = "none"
self.ui_font_family = ""
self.ui_font_point_size = 0
self.document_font_family = ""
self.document_font_size = 16
self.math_engine = "katex"
self.auto_refresh_enabled = True
self.non_preview_action = "ask"
self.recent_files: list[Path] = []
self.bookmarks: list[dict[str, str]] = []
self.scroll_positions: dict[str, int] = {}
self.external_applications: dict[str, str] = {}
self.path_to_item: dict[Path, QTreeWidgetItem] = {}
self.file_watcher = QFileSystemWatcher(self)
self.file_watcher.fileChanged.connect(self._on_watched_file_changed)
self.file_watcher.directoryChanged.connect(self._on_watched_directory_changed)
self.refresh_timer = QTimer(self)
self.refresh_timer.setSingleShot(True)
self.refresh_timer.setInterval(250)
self.refresh_timer.timeout.connect(self._auto_refresh_current_document)
self.tree_refresh_timer = QTimer(self)
self.tree_refresh_timer.setSingleShot(True)
self.tree_refresh_timer.setInterval(350)
self.tree_refresh_timer.timeout.connect(self._refresh_document_entries)
self.scroll_capture_timer = QTimer(self)
self.scroll_capture_timer.setInterval(1500)
self.scroll_capture_timer.timeout.connect(self._save_current_scroll_position)
self._load_preferences()
self.setWindowTitle("MDHelper")
self._build_ui()
self.scroll_capture_timer.start()
self._populate_tree()
self._restore_window_state()
QTimer.singleShot(0, self._apply_navigation_style)
initial = initial_path.resolve() if initial_path is not None and initial_path.exists() else self.project_root / "sample.md"
if initial_path is None and self.recent_files and self.recent_files[0].exists():
initial = self.recent_files[0]
if not initial.exists() and self.entries:
initial = self.entries[0].path
if initial.exists():
if initial.suffix.lower() in {".md", ".markdown"}:
self._ensure_document_entry(initial)
self.open_document(initial)
elif initial.suffix.lower() in {".html", ".htm", ".xhtml"}:
self._open_webpage_file_now(initial)
else:
QTimer.singleShot(0, lambda path=initial: self._open_local_file_now(path))
def _build_ui(self) -> None:
file_menu = self.menuBar().addMenu("文件")
edit_menu = self.menuBar().addMenu("编辑")
bookmarks_menu_root = self.menuBar().addMenu("书签")
tools_menu = self.menuBar().addMenu("工具")
self.theme_menu = self.menuBar().addMenu("主题")
toolbar = QToolBar("主工具栏")
toolbar.setMovable(False)
self.addToolBar(toolbar)
self.back_action = QAction("后退", self)
self.back_action.triggered.connect(self.go_back)
toolbar.addAction(self.back_action)
self.forward_action = QAction("前进", self)
self.forward_action.triggered.connect(self.go_forward)
toolbar.addAction(self.forward_action)
self.home_action = QAction("首页", self)
self.home_action.triggered.connect(self.open_home)
toolbar.addAction(self.home_action)
self.open_action = QAction("打开", self)
self.open_action.setShortcut("Ctrl+O")
self.open_action.triggered.connect(self.open_markdown_file)
toolbar.addAction(self.open_action)
file_menu.addAction(self.open_action)
self.export_pdf_action = QAction("导出 PDF", self)
self.export_pdf_action.setShortcut("Ctrl+P")
self.export_pdf_action.triggered.connect(self.export_current_pdf)
file_menu.addAction(self.export_pdf_action)
self.export_html_action = QAction("导出 HTML", self)
self.export_html_action.triggered.connect(self.export_current_html)
file_menu.addAction(self.export_html_action)
self.export_config_action = QAction("导出配置", self)
self.export_config_action.triggered.connect(self.export_configuration)
file_menu.addAction(self.export_config_action)
self.import_config_action = QAction("导入配置", self)
self.import_config_action.triggered.connect(self.import_configuration)
file_menu.addAction(self.import_config_action)
self.recent_menu = file_menu.addMenu("最近文件")
self.clear_recent_action = QAction("清空最近文件", self)
self.clear_recent_action.triggered.connect(self.clear_recent_files)
file_menu.addSeparator()
file_menu.addAction(self.clear_recent_action)
self.refresh_action = QAction("刷新", self)
self.refresh_action.setShortcut("F5")
self.refresh_action.triggered.connect(self.refresh_document)
toolbar.addAction(self.refresh_action)
toolbar.addSeparator()
self.zoom_out_action = QAction("A-", self)
self.zoom_out_action.triggered.connect(self.decrease_font)
toolbar.addAction(self.zoom_out_action)
self.zoom_in_action = QAction("A+", self)
self.zoom_in_action.triggered.connect(self.increase_font)
toolbar.addAction(self.zoom_in_action)
self.focus_find_action = QAction("页内查找", self)
self.focus_find_action.setShortcut("Ctrl+F")
self.focus_find_action.triggered.connect(self.focus_find_box)
edit_menu.addAction(self.focus_find_action)
self.focus_search_action = QAction("全文搜索", self)
self.focus_search_action.setShortcut("Ctrl+Shift+F")
self.focus_search_action.triggered.connect(self.focus_search_box)
edit_menu.addAction(self.focus_search_action)
self.math_engine_menu = edit_menu.addMenu("公式引擎")
self.math_engine_group = QActionGroup(self)
self.math_engine_group.setExclusive(True)
self.katex_action = QAction("KaTeX", self)
self.katex_action.setCheckable(True)
self.katex_action.setData("katex")
self.mathjax_action = QAction("MathJax", self)
self.mathjax_action.setCheckable(True)
self.mathjax_action.setData("mathjax")
for action in (self.katex_action, self.mathjax_action):
self.math_engine_group.addAction(action)
self.math_engine_menu.addAction(action)
self.math_engine_group.triggered.connect(self.set_math_engine)
self.settings_action = QAction("设置", self)
self.settings_action.triggered.connect(self.open_settings_dialog)
tools_menu.addAction(self.settings_action)
self.about_action = QAction("关于 MDHelper", self)
self.about_action.triggered.connect(self.show_about_dialog)
tools_menu.addAction(self.about_action)
self._build_theme_menu()
self.add_bookmark_action = QAction("添加书签", self)
self.add_bookmark_action.setShortcut("Ctrl+D")
self.add_bookmark_action.triggered.connect(self.add_current_bookmark)
bookmarks_menu_root.addAction(self.add_bookmark_action)
self.bookmarks_menu = bookmarks_menu_root.addMenu("打开书签")
self.manage_bookmarks_action = QAction("管理书签", self)
self.manage_bookmarks_action.triggered.connect(self.manage_bookmarks)
self.clear_bookmarks_action = QAction("清空书签", self)
self.clear_bookmarks_action.triggered.connect(self.clear_bookmarks)
bookmarks_menu_root.addSeparator()
bookmarks_menu_root.addAction(self.manage_bookmarks_action)
bookmarks_menu_root.addAction(self.clear_bookmarks_action)
toolbar.addWidget(QLabel("页内"))
self.find_box = QLineEdit()
self.find_box.setPlaceholderText("查找当前页")
self.find_box.setMaximumWidth(220)
self.find_box.returnPressed.connect(self.find_next)
self.find_box.textChanged.connect(self.find_current_text)
toolbar.addWidget(self.find_box)
self.find_previous_action = QAction("上一个", self)
self.find_previous_action.triggered.connect(self.find_previous)
toolbar.addAction(self.find_previous_action)
self.find_next_action = QAction("下一个", self)
self.find_next_action.triggered.connect(self.find_next)
toolbar.addAction(self.find_next_action)
self.find_result_label = QLabel("")
self.find_result_label.setMinimumWidth(72)
toolbar.addWidget(self.find_result_label)
self.tree = QTreeWidget()
self.tree.setObjectName("navigationTree")
self.tree.setHeaderHidden(True)
self._configure_navigation_tree(self.tree)
self.tree.itemActivated.connect(self._open_tree_item)
self.tree.itemClicked.connect(self._open_tree_item)
self.search_box = QLineEdit()
self.search_box.setObjectName("panelSearchBox")
self.search_box.setPlaceholderText("搜索标题、文件名或正文")
self.search_box.textChanged.connect(self._filter_tree)
self.search_results_label = QLabel("搜索结果")
self.search_results_label.setObjectName("panelSubTitle")
self.search_results_label.hide()
self.search_results = QTreeWidget()
self.search_results.setObjectName("navigationTree")
self.search_results.setHeaderHidden(True)
self._configure_navigation_tree(self.search_results)
self.search_results.itemActivated.connect(self._open_search_result)
self.search_results.itemClicked.connect(self._open_search_result)
self.search_results.hide()
left_panel = QWidget()
left_panel.setObjectName("navigationPanel")
left_panel.setMinimumWidth(260)
left_layout = QVBoxLayout(left_panel)
left_layout.setContentsMargins(12, 12, 12, 12)
left_layout.setSpacing(10)
left_layout.addWidget(self._panel_title("文档", "本地帮助文件"))
left_layout.addWidget(self.search_box)
left_layout.addWidget(self.search_results_label)
left_layout.addWidget(self.search_results)
left_layout.addWidget(self.tree)
self.tabs = QTabWidget()
self.tabs.setDocumentMode(True)
self.tabs.setTabsClosable(True)
self.tabs.currentChanged.connect(self._on_tab_changed)
self.tabs.tabCloseRequested.connect(self._close_tab)
self.web_view = self._create_reader_view()
self.tabs.addTab(self.web_view, "阅读")
self.toc_tree = QTreeWidget()
self.toc_tree.setObjectName("tocTree")
self.toc_tree.setHeaderHidden(True)
self._configure_navigation_tree(self.toc_tree)
self.toc_tree.itemActivated.connect(self._open_toc_item)
self.toc_tree.itemClicked.connect(self._open_toc_item)
toc_panel = QWidget()
toc_panel.setObjectName("tocPanel")
toc_panel.setMinimumWidth(220)
toc_layout = QVBoxLayout(toc_panel)
toc_layout.setContentsMargins(12, 12, 12, 12)
toc_layout.setSpacing(10)
toc_layout.addWidget(self._panel_title("目录", "当前文档章节"))
toc_layout.addWidget(self.toc_tree)
self.splitter = QSplitter(Qt.Orientation.Horizontal)
self.splitter.setObjectName("mainSplitter")
self.splitter.addWidget(left_panel)
self.splitter.addWidget(self.tabs)
self.splitter.addWidget(toc_panel)
self.splitter.setSizes([320, 820, 280])
self.splitter.setStretchFactor(1, 1)
self.setCentralWidget(self.splitter)
status = QStatusBar()
self.setStatusBar(status)
self.status_label = QLabel("就绪")
status.addWidget(self.status_label)
self.reading_progress = QProgressBar()
self.reading_progress.setRange(0, 100)
self.reading_progress.setFixedWidth(150)
self.reading_progress.setTextVisible(True)
self.reading_progress.setFormat("%p%")
status.addPermanentWidget(self.reading_progress)
self._update_theme_menu_state()
self._update_math_engine_actions()
self._apply_ui_font()
self._apply_navigation_style()
self._update_recent_menu()
self._update_bookmarks_menu()
def _build_theme_menu(self) -> None:
self.theme_color_menu = self.theme_menu.addMenu("主题颜色")
self.theme_color_group = QActionGroup(self)
self.theme_color_group.setExclusive(True)
for label, value in (
("黑色", "black"),
("白色", "white"),
("深灰色", "dark_gray"),
("彩色", "colorful"),
):
action = QAction(label, self)
action.setCheckable(True)
action.setData(value)
self.theme_color_group.addAction(action)
self.theme_color_menu.addAction(action)
self.theme_color_group.triggered.connect(self.set_theme_color_from_action)
self.theme_background_menu = self.theme_menu.addMenu("主题背景")
self.theme_background_group = QActionGroup(self)
self.theme_background_group.setExclusive(True)
for label, value in (
("无", "none"),
("春天", "spring"),
("稻草", "straw"),
("电路", "circuit"),
("年轮", "tree_rings"),
("几何图形", "geometry"),
("书法", "calligraphy"),
("水下", "underwater"),
):
action = QAction(label, self)
action.setCheckable(True)
action.setData(value)
self.theme_background_group.addAction(action)
self.theme_background_menu.addAction(action)
self.theme_background_group.triggered.connect(self.set_theme_background_from_action)
self.theme_menu.addSeparator()
self.interface_font_action = QAction("界面字体", self)
self.interface_font_action.triggered.connect(self.choose_interface_font)
self.theme_menu.addAction(self.interface_font_action)
self.document_font_action = QAction("文档字体", self)
self.document_font_action.triggered.connect(self.choose_document_font)
self.theme_menu.addAction(self.document_font_action)
self.document_font_size_menu = self.theme_menu.addMenu("文档字号")
self.document_font_size_group = QActionGroup(self)
self.document_font_size_group.setExclusive(True)
for size in (12, 14, 16, 18, 20, 22, 24, 28):
action = QAction(f"{size}px", self)
action.setCheckable(True)
action.setData(size)
self.document_font_size_group.addAction(action)
self.document_font_size_menu.addAction(action)
self.custom_document_font_size_action = QAction("自定义...", self)
self.custom_document_font_size_action.triggered.connect(self.choose_custom_document_font_size)
self.document_font_size_menu.addAction(self.custom_document_font_size_action)
self.document_font_size_group.triggered.connect(self.set_document_font_size_from_action)
def _configure_web_settings(self, settings: QWebEngineSettings) -> None:
attributes = QWebEngineSettings.WebAttribute
settings.setAttribute(attributes.LocalContentCanAccessFileUrls, True)
settings.setAttribute(attributes.LocalContentCanAccessRemoteUrls, True)
settings.setAttribute(attributes.PlaybackRequiresUserGesture, False)
settings.setAttribute(attributes.FullScreenSupportEnabled, True)
settings.setAttribute(attributes.JavascriptEnabled, True)
def _create_reader_view(self) -> ReaderView:
web_view = ReaderView()
web_view.navigation_history = NavigationHistory()
web_view.reader_bridge = ReaderBridge()
web_view.reader_channel = QWebChannel(web_view)
web_view.reader_channel.registerObject("mdhelperBridge", web_view.reader_bridge)
web_view.reader_bridge.scroll_changed.connect(self._on_reader_scroll_changed)
web_view.reader_bridge.image_save_requested.connect(self._save_image_from_url)
web_view.reader_bridge.image_reveal_requested.connect(self._reveal_image_from_url)
page = ReaderPage(web_view)
page.anchor_requested.connect(self.scroll_to_anchor)
page.local_link_requested.connect(self.open_link_url)
page.external_url_requested.connect(self.open_external_url)
page.linkHovered.connect(self._show_link_status)
page.pdfPrintingFinished.connect(self._on_pdf_printing_finished)
web_view.open_link_requested.connect(self.open_link_url)
web_view.setPage(page)
page.setWebChannel(web_view.reader_channel)
self._configure_web_settings(page.settings())
web_view.loadFinished.connect(self._on_load_finished)
return web_view
def _prepare_target_tab(self, new_tab: bool, title: str) -> ReaderView:
if new_tab:
web_view = self._create_reader_view()
index = self.tabs.addTab(web_view, title)
self.tabs.setCurrentIndex(index)
self.web_view = web_view
return web_view
current = self.tabs.currentWidget()
if isinstance(current, ReaderView):
self.web_view = current
return current
self.web_view = self._create_reader_view()
index = self.tabs.addTab(self.web_view, title)
self.tabs.setCurrentIndex(index)
return self.web_view
def _update_tab_title(self, web_view: QWebEngineView, title: str) -> None:
index = self.tabs.indexOf(web_view)
if index >= 0:
self.tabs.setTabText(index, title)
self.tabs.setTabToolTip(index, title)
def _panel_title(self, title: str, caption: str) -> QWidget:
container = QWidget()
container.setObjectName("panelTitleBlock")
layout = QVBoxLayout(container)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(2)
title_label = QLabel(title)
title_label.setObjectName("panelTitle")
caption_label = QLabel(caption)
caption_label.setObjectName("panelCaption")
layout.addWidget(title_label)
layout.addWidget(caption_label)
return container
def _configure_navigation_tree(self, tree: QTreeWidget) -> None:
tree.setAlternatingRowColors(False)
tree.setAnimated(True)
tree.setIndentation(16)
tree.setRootIsDecorated(True)
tree.setUniformRowHeights(True)
tree.setTextElideMode(Qt.TextElideMode.ElideRight)
tree.setItemDelegate(CompactTreeDelegate(tree))
def _reader_theme_for_color(self, theme_color: str) -> str:
return "dark" if theme_color in {"black", "dark_gray"} else "light"
def _set_theme_color(self, theme_color: str) -> None:
if theme_color not in {"white", "black", "dark_gray", "colorful"}:
theme_color = "white"
self.theme_color = theme_color
self.theme = self._reader_theme_for_color(theme_color)
def _theme_color_label(self) -> str:
return {
"white": "白色",
"black": "黑色",
"dark_gray": "深灰色",
"colorful": "彩色",
}.get(self.theme_color, "白色")
def _theme_background_label(self) -> str:
return {
"none": "无",
"spring": "春天",
"straw": "稻草",
"circuit": "电路",
"tree_rings": "年轮",
"geometry": "几何图形",
"calligraphy": "书法",
"underwater": "水下",
}.get(self.theme_background, "无")
def _update_theme_menu_state(self) -> None:
if hasattr(self, "theme_color_group"):
for action in self.theme_color_group.actions():
action.setChecked(action.data() == self.theme_color)
if hasattr(self, "theme_background_group"):
for action in self.theme_background_group.actions():
action.setChecked(action.data() == self.theme_background)
if hasattr(self, "document_font_size_group"):
for action in self.document_font_size_group.actions():
action.setChecked(int(action.data()) == self.document_font_size)
def _apply_ui_font(self) -> None:
app = QApplication.instance()
if app is None:
return
font = app.font()
if self.ui_font_family:
font.setFamily(self.ui_font_family)
if self.ui_font_point_size > 0:
font.setPointSize(self.ui_font_point_size)
app.setFont(font)
def _apply_navigation_style(self) -> None:
palettes = {
"white": {
"chrome": "#f7f8fb",
"surface": "#ffffff",
"text": "#111827",
"muted": "#6b7280",
"border": "#dde2eb",
"hover": "#eef4ff",
"selected": "#dbeafe",
"selected_text": "#0f172a",
"splitter": "#e5e7eb",
"focus": "#3b82f6",
"tab_bg": "#edf1f7",
},
"black": {
"chrome": "#0c0d10",
"surface": "#17191f",
"text": "#f3f4f6",
"muted": "#a7adb7",
"border": "#2a2e38",
"hover": "#252b36",
"selected": "#243b5a",
"selected_text": "#f8fafc",
"splitter": "#252a33",
"focus": "#60a5fa",
"tab_bg": "#111318",
},
"dark_gray": {
"chrome": "#282c33",
"surface": "#343943",
"text": "#f1f5f9",
"muted": "#c1c7d0",
"border": "#48505d",
"hover": "#3f4a59",
"selected": "#365b82",
"selected_text": "#ffffff",
"splitter": "#48505d",
"focus": "#7dd3fc",
"tab_bg": "#303640",
},
"colorful": {
"chrome": "#eef5ff",
"surface": "#ffffff",
"text": "#132238",
"muted": "#667085",
"border": "#cbd9ef",
"hover": "#e7f0ff",
"selected": "#cfe2ff",
"selected_text": "#10213d",
"splitter": "#cbd9ef",
"focus": "#2563eb",
"tab_bg": "#dceaff",
},
}
palette = palettes.get(self.theme_color, palettes["white"])
background_accents = {
"none": ("", palette["chrome"]),
"spring": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #edf7ef, stop:0.55 #f7f8fb, stop:1 #fff0f5)", "#f6faf6"),
"straw": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #fbf3d3, stop:0.5 #f7f8fb, stop:1 #f1dfaa)", "#fbf7e6"),
"circuit": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #e8f7fb, stop:0.5 #f7f8fb, stop:1 #eaf2ff)", "#f3f8fb"),
"tree_rings": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #f6ead8, stop:0.5 #f7f8fb, stop:1 #ead8bd)", "#fbf3e8"),
"geometry": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #eef2ff, stop:0.5 #f7f8fb, stop:1 #e0f2fe)", "#f4f7ff"),
"calligraphy": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #f9f1df, stop:0.5 #f7f8fb, stop:1 #efe6d2)", "#faf6ec"),
"underwater": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #e2f7fb, stop:0.5 #eef8ff, stop:1 #dff7f2)", "#effafc"),
}
dark_background_accents = {
"none": ("", palette["chrome"]),
"spring": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #16251d, stop:0.55 #151922, stop:1 #251a23)", "#171d22"),
"straw": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #2c2515, stop:0.5 #151922, stop:1 #332913)", "#1f1d18"),
"circuit": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #10272c, stop:0.5 #151922, stop:1 #13213a)", "#161f28"),
"tree_rings": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #2b2118, stop:0.5 #151922, stop:1 #241b13)", "#211d1a"),
"geometry": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #172039, stop:0.5 #151922, stop:1 #0f2a38)", "#171d29"),
"calligraphy": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #2a251c, stop:0.5 #151922, stop:1 #1e1b16)", "#201e1a"),
"underwater": ("qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #0d2834, stop:0.5 #101b2a, stop:1 #0e332f)", "#111f29"),
}
accent_source = dark_background_accents if self.theme == "dark" else background_accents
header_background, themed_panel = accent_source.get(self.theme_background, accent_source["none"])
panel_bg = themed_panel if self.theme_background != "none" else palette["chrome"]
chrome_bg = header_background or panel_bg
text = palette["text"]
muted = palette["muted"]
surface = palette["surface"]
border = palette["border"]
hover = palette["hover"]
selected = palette["selected"]
selected_text = palette["selected_text"]
splitter = palette["splitter"]
input_bg = palette["surface"]
focus = palette["focus"]
tab_bg = palette["tab_bg"]
tab_active = palette["surface"]
self.setStyleSheet(
f"""
QMainWindow {{
background: {panel_bg};
}}
QMenuBar,
QToolBar,
QStatusBar {{
color: {text};
background: {chrome_bg};
border: 0;
}}
QToolBar {{
border-bottom: 1px solid {splitter};
spacing: 4px;
}}
QToolButton {{
color: {text};
background: transparent;
border: 1px solid transparent;
border-radius: 5px;
padding: 4px 7px;
}}
QToolButton:hover {{
background: {hover};
color: {selected_text};
}}
QToolButton:pressed,
QToolButton:checked {{
background: {selected};
color: {selected_text};
}}
QStatusBar {{
border-top: 1px solid {splitter};
}}
QProgressBar {{
color: {text};
background: {surface};
border: 1px solid {border};
border-radius: 5px;
text-align: center;
}}
QProgressBar::chunk {{
background: {focus};
border-radius: 4px;
}}
QMenuBar::item {{
padding: 5px 9px;
background: transparent;
}}
QMenuBar::item:selected {{
background: {hover};
color: {selected_text};
border-radius: 4px;
}}
QMenu {{
color: {text};
background: {surface};
border: 1px solid {border};
padding: 4px;
}}
QMenu::item {{
padding: 5px 24px 5px 10px;
}}
QMenu::item:selected {{
background: {hover};
color: {selected_text};
}}
QTabWidget {{
background: {tab_bg};
}}
QTabWidget::tab-bar {{
background: {tab_bg};
}}
QTabWidget::pane {{
border: 0;
border-left: 1px solid {splitter};
border-right: 1px solid {splitter};
background: {tab_active};
}}
QTabBar {{
background: {tab_bg};
qproperty-drawBase: 0;
}}
QTabBar::tab {{
color: {muted};
background: {tab_bg};
border: 1px solid {splitter};
border-bottom: 0;
padding: 6px 12px;
margin-right: 2px;
}}
QTabBar::tab:selected {{
color: {text};
background: {tab_active};
}}
QTabBar::tab:hover {{
color: {text};
background: {hover};
}}
QWidget#navigationPanel,
QWidget#tocPanel {{
background: {panel_bg};
border: 0;
}}
QWidget#panelTitleBlock {{
background: transparent;
}}
QLabel#panelTitle {{
color: {text};
font-size: 15px;
font-weight: 700;
}}
QLabel#panelCaption,
QLabel#panelSubTitle {{
color: {muted};
font-size: 12px;
}}
QLineEdit#panelSearchBox {{
min-height: 30px;
padding: 5px 9px;
color: {text};
background: {input_bg};
border: 1px solid {border};
border-radius: 6px;
selection-background-color: {focus};
}}
QLineEdit#panelSearchBox:focus {{
border-color: {focus};
}}
QTreeWidget#navigationTree,
QTreeWidget#tocTree {{
color: {text};
background: {surface};
border: 1px solid {border};
border-radius: 7px;
padding: 3px;
outline: 0;
show-decoration-selected: 1;
}}
QTreeWidget#navigationTree::item,
QTreeWidget#tocTree::item {{
min-height: 20px;
padding: 1px 6px;
border-radius: 5px;
}}
QTreeWidget#navigationTree::item:hover,
QTreeWidget#tocTree::item:hover {{
background: {hover};
color: {selected_text};
}}
QTreeWidget#navigationTree::item:selected,
QTreeWidget#tocTree::item:selected {{
background: {selected};
color: {selected_text};
}}
QTreeWidget#navigationTree::branch,
QTreeWidget#tocTree::branch {{
background: transparent;
}}
QSplitter#mainSplitter::handle {{
background: {splitter};
}}
QSplitter#mainSplitter::handle:horizontal {{
width: 1px;
}}
"""
)
self._apply_window_title_bar_style(palette["chrome"], text)
def _apply_window_title_bar_style(self, background: str, foreground: str) -> None:
if os.name != "nt":
return
def colorref(value: str) -> int:
value = value.lstrip("#")
red = int(value[0:2], 16)
green = int(value[2:4], 16)
blue = int(value[4:6], 16)
return red | (green << 8) | (blue << 16)
try:
hwnd = int(self.winId())
dwmapi = ctypes.windll.dwmapi
dark_mode = ctypes.c_int(1 if self.theme == "dark" else 0)
for attribute in (20, 19):
dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(dark_mode), ctypes.sizeof(dark_mode))
for attribute, value in ((35, background), (36, foreground), (34, background)):
color = ctypes.c_int(colorref(value))
dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(color), ctypes.sizeof(color))
except (AttributeError, OSError, ValueError):
return
def _on_tab_changed(self, index: int) -> None:
widget = self.tabs.widget(index)
if not isinstance(widget, ReaderView):
return
self.web_view = widget
file_value = widget.property("current_file")
fragment_value = widget.property("current_fragment") or ""
if file_value:
self.current_file = Path(str(file_value))
self.current_fragment = str(fragment_value)
self.setWindowTitle(f"{self.current_file.name} - MDHelper")
self.status_label.setText(self._display_path(self.current_file))
if self.current_file.suffix.lower() in {".md", ".markdown"} and self.current_file.exists():
self._select_tree_item(self.current_file)
self._populate_toc(self.current_file)
else:
self.toc_tree.clear()
self._update_watched_paths()
self._update_actions()
def _close_tab(self, index: int) -> None:
if self.tabs.count() <= 1:
return
widget = self.tabs.widget(index)
self.tabs.removeTab(index)
if widget is not None:
widget.deleteLater()
def _render_local_file_page(self, path: Path) -> str:
title = html.escape(path.name)
uri = html.escape(path.as_uri(), quote=True)
kind = media_kind(path.as_uri())
mime_type = html.escape(media_mime_type(path.as_uri()), quote=True)
if kind in {"image", "gif"}:
body = f'<figure class="media-block media-image"><img src="{uri}" alt="{title}"><figcaption>{title}</figcaption></figure>'
elif kind == "audio":
body = (
f'<figure class="media-block media-audio" data-media-src="{uri}">'
f'<audio controls preload="metadata"><source src="{uri}" type="{mime_type}">当前环境无法播放此音频。</audio>'
f"<figcaption>{title}</figcaption></figure>"
)
elif kind == "video":
body = (
f'<figure class="media-block media-video" data-media-src="{uri}">'
f'<video controls preload="metadata" playsinline><source src="{uri}" type="{mime_type}">当前环境无法播放此视频。</video>'
f"<figcaption>{title}</figcaption></figure>"
)
elif self._is_text_file(path):
content = self._read_text_preview(path)
body = f'<h1>{title}</h1><pre class="plain-file-view">{html.escape(content)}</pre>'
else:
body = (
f"<h1>{title}</h1>"
"<p>此文件类型暂不能直接预览。</p>"
f'<p><code>{html.escape(str(path))}</code></p>'
)
return self.renderer.wrap_body_for_display(
body=body,
title=path.name,
theme=self.theme,
font_scale=self.font_scale,
document_font_family=self.document_font_family,
document_font_size=self.document_font_size,
math_engine=self.math_engine,
)
def _is_text_file(self, path: Path) -> bool:
if path.suffix.lower() in {".txt", ".log", ".csv", ".tsv", ".json", ".xml", ".html", ".htm", ".py", ".c", ".cpp", ".h", ".hpp"}:
return True
try:
chunk = path.read_bytes()[:2048]
except OSError:
return False
return b"\x00" not in chunk
def _read_text_preview(self, path: Path) -> str:
for encoding in ("utf-8", "utf-8-sig", "gbk"):
try:
return path.read_text(encoding=encoding)
except UnicodeDecodeError:
continue
except OSError as exc:
return f"读取失败:{exc}"
return path.read_text(encoding="utf-8", errors="replace")
def _populate_tree(self) -> None:
self.tree.clear()
self.path_to_item.clear()
root_item = QTreeWidgetItem(["MDHelper"])
root_item.setData(0, Qt.ItemDataRole.UserRole, None)
self.tree.addTopLevelItem(root_item)
docs_item = QTreeWidgetItem(["docs"])
docs_item.setData(0, Qt.ItemDataRole.UserRole, None)
for entry in self.entries:
label = f"{entry.title} ({entry.relative_path})"
item = QTreeWidgetItem([label])
item.setToolTip(0, entry.relative_path)
item.setData(0, Qt.ItemDataRole.UserRole, str(entry.path))
self.path_to_item[entry.path] = item
if entry.relative_path.startswith("docs/"):
docs_item.addChild(item)
else:
root_item.addChild(item)
if docs_item.childCount():
root_item.addChild(docs_item)
self.tree.expandAll()
def open_document_from_link(self, path: Path, fragment: str = "") -> None:
if not path.exists():
QMessageBox.warning(self, "文件不存在", f"无法打开:\n{path}")
return
self.open_document(path, fragment=fragment)
def open_markdown_file(self) -> None:
file_name, _ = QFileDialog.getOpenFileName(
self,
"打开 Markdown 文件",
str(self.project_root),
"Markdown Files (*.md *.markdown);;All Files (*)",
)
if file_name:
self._ensure_document_entry(Path(file_name).resolve())
self.open_document(Path(file_name))
def open_link_url(self, url: QUrl, new_tab: bool) -> None:
QTimer.singleShot(0, lambda target=QUrl(url), tab=new_tab: self._open_link_url_now(target, tab))
def _open_link_url_now(self, url: QUrl, new_tab: bool) -> None:
if self._is_current_page_anchor_url(url):
self.scroll_to_anchor(url.fragment())
return
if url.isLocalFile():
path = Path(url.toLocalFile()).resolve()
if is_markdown_url(url.toString()):
self.open_document(path, fragment=url.fragment(), new_tab=new_tab)
elif is_webpage_url(url.toString()):
self.open_webpage_file(path, new_tab)
else:
self.confirm_open_with_local_app(path)
return
if url.fragment() and not url.scheme():
self.scroll_to_anchor(url.fragment())
return
self.open_external_url(url)
def _is_current_page_anchor_url(self, url: QUrl) -> bool:
if not url.fragment():
return False
if not url.scheme():
return True
if not url.isLocalFile() or self.current_file is None:
return False
try:
target_path = Path(url.toLocalFile()).resolve()
current_path = self.current_file.resolve()
except OSError:
return False
return target_path in {current_path, current_path.parent}
def open_local_file(self, path: Path, new_tab: bool = False) -> None:
QTimer.singleShot(0, lambda file_path=Path(path), tab=new_tab: self._open_local_file_now(file_path, tab))
def open_webpage_file(self, path: Path, new_tab: bool = False) -> None:
QTimer.singleShot(0, lambda file_path=Path(path), tab=new_tab: self._open_webpage_file_now(file_path, tab))
def open_external_url(self, url: QUrl) -> None:
LOGGER.info("Opening external URL: %s", url.toString())
QTimer.singleShot(0, lambda target=QUrl(url): QDesktopServices.openUrl(target))
def confirm_open_with_local_app(self, path: Path) -> None:
QTimer.singleShot(0, lambda file_path=Path(path): self._confirm_open_with_local_app_now(file_path))
def _confirm_open_with_local_app_now(self, path: Path) -> None:
path = path.resolve()
if not path.exists():
QMessageBox.warning(self, "文件不存在", f"无法打开:\n{path}")
return
if self.non_preview_action == "block":
QMessageBox.information(self, "已阻止打开", f"此文件类型未在 MDHelper 内预览:\n{path}")
return
if self._open_with_saved_application(path):
return
if self.non_preview_action == "ask":
answer = QMessageBox.question(
self,
"使用本地软件打开",
f"此文件类型不在 MDHelper 内预览。\n\n是否使用本地默认软件打开?\n\n{path}",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if answer != QMessageBox.StandardButton.Yes:
LOGGER.info("User canceled opening local file: %s", path)
return
LOGGER.info("Opening local file with default application: %s", path)
try:
os.startfile(str(path))
except OSError as exc:
LOGGER.exception("Failed to open local file: %s", path)
self._offer_select_application_after_open_failure(path, exc)
def _offer_select_application_after_open_failure(self, path: Path, error: OSError) -> None:
message = QMessageBox(self)
message.setIcon(QMessageBox.Icon.Warning)
message.setWindowTitle("无法用默认程序打开")
message.setText("Windows 没有为此文件类型配置可用的默认应用,或默认应用启动失败。")
message.setInformativeText(
f"文件:\n{path}\n\n"
f"系统错误:\n{error}\n\n"
"你可以选择一个本地程序来打开此文件。选择成功后,MDHelper 会记住此扩展名对应的程序。"
)
choose_button = message.addButton("选择程序打开", QMessageBox.ButtonRole.AcceptRole)
message.addButton("取消", QMessageBox.ButtonRole.RejectRole)
message.exec()
if message.clickedButton() == choose_button:
self._open_with_selected_application(path)
def _open_with_selected_application(self, path: Path) -> None:
program, _ = QFileDialog.getOpenFileName(
self,
"选择用于打开文件的程序",
str(Path.home()),
"可执行程序 (*.exe);;所有文件 (*)",
)
if not program:
LOGGER.info("User canceled selecting application for: %s", path)
return
LOGGER.info("Opening local file with selected application: %s -> %s", program, path)
if self._start_external_application(program, path):
self._remember_external_application(path, program)
self.status_label.setText(f"已记住 {path.suffix.lower()} 的打开程序")
else:
QMessageBox.warning(
self,
"打开失败",
f"无法启动所选程序:\n{program}\n\n要打开的文件:\n{path}",
)
def _open_with_saved_application(self, path: Path) -> bool:
extension = path.suffix.lower()
program = self.external_applications.get(extension)
if not extension or not program:
return False
program_path = Path(program)
if not program_path.exists():
LOGGER.warning("Saved application no longer exists for %s: %s", extension, program)
self._forget_external_application(extension)
return False
LOGGER.info("Opening local file with saved application: %s -> %s", program, path)
if self._start_external_application(program, path):
return True
LOGGER.warning("Saved application failed for %s: %s", extension, program)
self._forget_external_application(extension)
QMessageBox.warning(
self,
"打开失败",
f"已记住的程序无法启动,MDHelper 已清除此记录。\n\n程序:\n{program}\n\n文件:\n{path}",
)
return False
def _start_external_application(self, program: str, path: Path) -> bool:
return QProcess.startDetached(program, [str(path)])
def _remember_external_application(self, path: Path, program: str) -> None:
extension = path.suffix.lower()
if not extension:
return
self.external_applications[extension] = str(Path(program).resolve())
self._save_preferences()
LOGGER.info("Remembered external application for %s: %s", extension, program)
def _forget_external_application(self, extension: str) -> None:
self.external_applications.pop(extension.lower(), None)
self._save_preferences()
def _save_image_from_url(self, url: str) -> None:
source = self._local_path_from_url(url)
if source is None or not source.exists() or not source.is_file():
QMessageBox.warning(self, "保存失败", f"无法定位图片文件:\n{url}")
return
file_name, _ = QFileDialog.getSaveFileName(
self,
"保存图片",
str(self.project_root / source.name),
"Images (*.png *.jpg *.jpeg *.webp *.bmp *.gif *.svg);;All Files (*)",
)
if not file_name:
return
target = Path(file_name)
if not target.suffix and source.suffix:
target = target.with_suffix(source.suffix)
try:
shutil.copyfile(source, target)
except OSError as exc:
LOGGER.exception("Failed to save image: %s -> %s", source, target)
QMessageBox.warning(self, "保存失败", f"无法保存图片:\n{target}\n\n{exc}")
return
self.status_label.setText(f"图片已保存:{target}")
def _reveal_image_from_url(self, url: str) -> None:
source = self._local_path_from_url(url)
if source is None or not source.exists():
QMessageBox.warning(self, "定位失败", f"无法定位图片文件:\n{url}")
return
if os.name == "nt":
if QProcess.startDetached("explorer.exe", ["/select,", str(source)]):
return
QDesktopServices.openUrl(QUrl.fromLocalFile(str(source.parent)))
def _local_path_from_url(self, url: str) -> Path | None:
qurl = QUrl(url)
if qurl.isLocalFile():
return Path(qurl.toLocalFile()).resolve()
return None
def _open_webpage_file_now(self, path: Path, new_tab: bool = False) -> None:
path = path.resolve()
if not path.exists():
QMessageBox.warning(self, "文件不存在", f"无法打开:\n{path}")
return
web_view = self._prepare_target_tab(new_tab, path.name)
web_view.load(QUrl.fromLocalFile(str(path)))
web_view.setProperty("current_file", str(path))
web_view.setProperty("current_fragment", "")
self.current_file = path
self.current_fragment = ""
self.pending_fragment = ""
self.pending_find_text = ""
self.pending_scroll_y = None
self.setWindowTitle(f"{path.name} - MDHelper")
self.status_label.setText(self._display_path(path))
self.toc_tree.clear()
self._update_tab_title(web_view, path.name)
self._update_watched_paths()
LOGGER.info("Opened webpage file: %s", path)
def _open_local_file_now(self, path: Path, new_tab: bool = False) -> None:
path = path.resolve()
if not path.exists():
QMessageBox.warning(self, "文件不存在", f"无法打开:\n{path}")
return
if path.suffix.lower() in {".md", ".markdown"}:
self.open_document(path, new_tab=new_tab)
return
if path.suffix.lower() in {".html", ".htm", ".xhtml"}:
self._open_webpage_file_now(path, new_tab=new_tab)
return
self._confirm_open_with_local_app_now(path)
def export_current_pdf(self) -> None:
if self.current_file is None:
return
default_name = self.current_file.with_suffix(".pdf").name
file_name, _ = QFileDialog.getSaveFileName(
self,
"导出当前文档为 PDF",
str(self.project_root / default_name),
"PDF Files (*.pdf)",
)
if not file_name:
return
output_path = Path(file_name)
if output_path.suffix.lower() != ".pdf":
output_path = output_path.with_suffix(".pdf")
self.web_view.page().printToPdf(str(output_path))
LOGGER.info("Exporting PDF: %s", output_path)
self.status_label.setText(f"正在导出 PDF:{output_path}")
def export_current_html(self) -> None:
if self.current_file is None:
return
default_name = self.current_file.with_suffix(".html").name
file_name, _ = QFileDialog.getSaveFileName(
self,
"导出当前文档为 HTML",
str(self.project_root / default_name),
"HTML Files (*.html *.htm)",
)
if not file_name:
return
output_path = Path(file_name)
if output_path.suffix.lower() not in {".html", ".htm"}:
output_path = output_path.with_suffix(".html")
if self.current_file.suffix.lower() in {".md", ".markdown"}:
try:
content = self.renderer.render_file(
self.current_file,
theme=self.theme,
font_scale=self.font_scale,
document_font_family=self.document_font_family,
document_font_size=self.document_font_size,
math_engine=self.math_engine,
)
except OSError as exc:
LOGGER.exception("Failed to render HTML export: %s", self.current_file)
QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}")
return
self._write_exported_html(output_path, content)
return
self.status_label.setText(f"正在导出 HTML:{output_path}")
self.web_view.page().toHtml(lambda content, target=output_path: self._write_exported_html(target, content))
def _write_exported_html(self, output_path: Path, content: str) -> None:
try:
output_path.write_text(content, encoding="utf-8")
except OSError as exc:
LOGGER.exception("Failed to export HTML: %s", output_path)
QMessageBox.warning(self, "导出失败", f"无法写入 HTML 文件:\n{output_path}\n\n{exc}")
return
LOGGER.info("HTML exported: %s", output_path)
self.status_label.setText(f"HTML 已导出:{output_path}")
def export_configuration(self) -> None:
default_path = self.project_root / "mdhelper_config.json"
file_name, _ = QFileDialog.getSaveFileName(
self,
"导出配置",
str(default_path),
"JSON Files (*.json)",
)
if not file_name:
return
output_path = Path(file_name)
if output_path.suffix.lower() != ".json":
output_path = output_path.with_suffix(".json")
try:
output_path.write_text(
json.dumps(self._configuration_snapshot(), ensure_ascii=False, indent=2),
encoding="utf-8",
)
except OSError as exc:
LOGGER.exception("Failed to export configuration: %s", output_path)
QMessageBox.warning(self, "导出失败", f"无法写入配置文件:\n{output_path}\n\n{exc}")
return
LOGGER.info("Configuration exported: %s", output_path)
self.status_label.setText(f"配置已导出:{output_path}")
def import_configuration(self) -> None:
file_name, _ = QFileDialog.getOpenFileName(
self,
"导入配置",
str(self.project_root),
"JSON Files (*.json);;All Files (*)",
)
if not file_name:
return
config_path = Path(file_name)
try:
payload = json.loads(config_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
LOGGER.exception("Failed to import configuration: %s", config_path)
QMessageBox.warning(self, "导入失败", f"无法读取配置文件:\n{config_path}\n\n{exc}")
return
if not isinstance(payload, dict):
QMessageBox.warning(self, "导入失败", "配置文件格式不正确。")
return
self._apply_configuration(payload)
self._save_preferences()
self._update_recent_menu()
self._update_bookmarks_menu()
self._update_math_engine_actions()
self._apply_ui_font()
self._update_theme_menu_state()
self._apply_navigation_style()
self._filter_tree(self.search_box.text())
self.refresh_document()
LOGGER.info("Configuration imported: %s", config_path)
self.status_label.setText(f"配置已导入:{config_path}")
def show_about_dialog(self) -> None:
QMessageBox.about(
self,
"关于 MDHelper",
(
f"<h3>MDHelper {html.escape(__version__)}</h3>"
"<p>本地 Markdown 帮助文档阅读器。</p>"
f"<p>项目目录:<br><code>{html.escape(str(self.project_root))}</code></p>"
"<p>支持离线 Mermaid、KaTeX/MathJax、媒体预览、全文搜索和多标签阅读。</p>"
),
)
def _configuration_snapshot(self) -> dict[str, object]:
return {
"app": "MDHelper",
"version": __version__,
"reader": {
"theme": self.theme,
"theme_color": self.theme_color,
"theme_background": self.theme_background,
"font_scale": self.font_scale,
"ui_font_family": self.ui_font_family,
"ui_font_point_size": self.ui_font_point_size,
"document_font_family": self.document_font_family,
"document_font_size": self.document_font_size,
"math_engine": self.math_engine,
"auto_refresh": self.auto_refresh_enabled,
"non_preview_action": self.non_preview_action,
},
"recent_files": [str(path) for path in self.recent_files],
"bookmarks": self.bookmarks,
"scroll_positions": self.scroll_positions,
"external_applications": self.external_applications,
}
def _apply_configuration(self, payload: dict[str, object]) -> None:
reader = payload.get("reader", {})
if isinstance(reader, dict):
theme_color = str(reader.get("theme_color", self.theme_color))
if theme_color in {"white", "black", "dark_gray", "colorful"}:
self._set_theme_color(theme_color)
theme_background = str(reader.get("theme_background", self.theme_background))
if theme_background in {
"none",
"spring",
"straw",
"circuit",
"tree_rings",
"geometry",
"calligraphy",
"underwater",
}:
self.theme_background = theme_background
theme = str(reader.get("theme", self.theme))
if "theme_color" not in reader and theme in {"light", "dark"}:
self.theme = theme
self.theme_color = "black" if theme == "dark" else "white"
math_engine = str(reader.get("math_engine", self.math_engine))
if math_engine in {"katex", "mathjax"}:
self.math_engine = math_engine
try:
self.font_scale = max(0.8, min(1.6, float(reader.get("font_scale", self.font_scale))))
except (TypeError, ValueError):
pass
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
try:
self.document_font_size = max(12, min(28, int(reader.get("document_font_size", self.document_font_size))))
self.font_scale = self.document_font_size / 16
except (TypeError, ValueError):
pass
self.ui_font_family = str(reader.get("ui_font_family", self.ui_font_family)).strip()
try:
self.ui_font_point_size = max(0, min(32, int(reader.get("ui_font_point_size", self.ui_font_point_size))))
except (TypeError, ValueError):
pass
self.document_font_family = str(reader.get("document_font_family", self.document_font_family)).strip()
self.auto_refresh_enabled = bool(reader.get("auto_refresh", self.auto_refresh_enabled))
non_preview_action = str(reader.get("non_preview_action", self.non_preview_action))
if non_preview_action in {"ask", "open", "block"}:
self.non_preview_action = non_preview_action
recent_files = payload.get("recent_files", [])
if isinstance(recent_files, list):
self.recent_files = [Path(str(path)).expanduser().resolve() for path in recent_files if str(path)]
bookmarks = payload.get("bookmarks", [])
if isinstance(bookmarks, list):
self.bookmarks = [item for item in bookmarks if isinstance(item, dict)]
scroll_positions = payload.get("scroll_positions", {})
if isinstance(scroll_positions, dict):
self.scroll_positions = {
str(path): int(position)
for path, position in scroll_positions.items()
if self._is_int_like(position)
}
external_applications = payload.get("external_applications", {})
if isinstance(external_applications, dict):
self.external_applications = {
str(extension).lower(): str(program)
for extension, program in external_applications.items()
if str(extension).startswith(".") and str(program)
}
def _is_int_like(self, value: object) -> bool:
try:
int(value)
except (TypeError, ValueError):
return False
return True
def open_document(
self,
path: Path,
fragment: str = "",
add_history: bool = True,
scroll_y: int | None = None,
new_tab: bool = False,
) -> None:
path = path.resolve()
self._save_current_scroll_position()
try:
html = self.renderer.render_file(
path,
theme=self.theme,
font_scale=self.font_scale,
document_font_family=self.document_font_family,
document_font_size=self.document_font_size,
math_engine=self.math_engine,
)
except OSError as exc:
LOGGER.exception("Failed to read document: %s", path)
QMessageBox.critical(self, "读取失败", f"无法读取文档:\n{path}\n\n{exc}")
return
web_view = self._prepare_target_tab(new_tab, path.name)
self.current_file = path
self.current_fragment = fragment
self.pending_fragment = fragment
if fragment:
self.pending_scroll_y = None
elif scroll_y is not None:
self.pending_scroll_y = max(0, scroll_y)
else:
self.pending_scroll_y = self.scroll_positions.get(str(path))
if add_history:
self._tab_history(web_view).push(HistoryItem(path=path, fragment=fragment, scroll_y=scroll_y or 0))
self._remember_recent_file(path)
base_path = str(path.parent.resolve()) + os.sep
web_view.setHtml(html, QUrl.fromLocalFile(base_path))
web_view.setProperty("current_file", str(path))
web_view.setProperty("current_fragment", fragment)
self.setWindowTitle(f"{path.name} - MDHelper")
self.status_label.setText(self._display_path(path))
self._select_tree_item(path)
self._populate_toc(path)
self._update_tab_title(web_view, path.name)
self._update_watched_paths()
self._update_actions()
LOGGER.info("Opened document: %s", path)
def open_home(self) -> None:
home = self.project_root / "sample.md"
if home.exists():
self.open_document(home)
def refresh_document(self) -> None:
if self.current_file is not None:
if self.current_file.suffix.lower() in {".html", ".htm", ".xhtml"}:
self.open_webpage_file(self.current_file)
return
if self.current_file.suffix.lower() not in {".md", ".markdown"}:
self.confirm_open_with_local_app(self.current_file)
return
path = self.current_file
fragment = self.current_fragment
def reload_at_scroll(scroll_y: object) -> None:
try:
position = int(float(scroll_y or 0))
except (TypeError, ValueError):
position = 0
self.open_document(path, fragment=fragment, add_history=False, scroll_y=position)
self.web_view.page().runJavaScript("Math.max(0, window.scrollY || 0)", reload_at_scroll)
def go_back(self) -> None:
self._store_current_history_scroll()
item = self._current_history().back()
if item is not None:
self.open_document(
item.path,
fragment=item.fragment,
add_history=False,
scroll_y=item.scroll_y if not item.fragment else None,
)
def go_forward(self) -> None:
self._store_current_history_scroll()
item = self._current_history().forward()
if item is not None:
self.open_document(
item.path,
fragment=item.fragment,
add_history=False,
scroll_y=item.scroll_y if not item.fragment else None,
)
def increase_font(self) -> None:
self.document_font_size = min(28, self.document_font_size + 1)
self.font_scale = self.document_font_size / 16
self._update_theme_menu_state()
self._save_preferences()
self.refresh_document()
def decrease_font(self) -> None:
self.document_font_size = max(12, self.document_font_size - 1)
self.font_scale = self.document_font_size / 16
self._update_theme_menu_state()
self._save_preferences()
self.refresh_document()
def toggle_theme(self) -> None:
self._set_theme_color("white" if self.theme == "dark" else "black")
self._update_theme_menu_state()
self._apply_navigation_style()
self._save_preferences()
self.refresh_document()
def set_theme_color_from_action(self, action: QAction) -> None:
self._set_theme_color(str(action.data() or "white"))
self._update_theme_menu_state()
self._apply_navigation_style()
self._save_preferences()
self.refresh_document()
def set_theme_background_from_action(self, action: QAction) -> None:
background = str(action.data() or "none")
if background not in {
"none",
"spring",
"straw",
"circuit",
"tree_rings",
"geometry",
"calligraphy",
"underwater",
}:
background = "none"
self.theme_background = background
self._update_theme_menu_state()
self._apply_navigation_style()
self._save_preferences()
def choose_interface_font(self) -> None:
current = QApplication.instance().font() if QApplication.instance() is not None else QFont()
font, accepted = QFontDialog.getFont(current, self, "选择界面字体")
if not accepted:
return
self.ui_font_family = font.family()
self.ui_font_point_size = font.pointSize()
self._apply_ui_font()
self._apply_navigation_style()
self._save_preferences()
def choose_document_font(self) -> None:
font = QFont(self.document_font_family or "Microsoft YaHei UI")
font.setPointSize(max(8, round(self.document_font_size * 0.75)))
selected, accepted = QFontDialog.getFont(font, self, "选择文档字体")
if not accepted:
return
self.document_font_family = selected.family()
if selected.pointSize() > 0:
self.document_font_size = max(12, min(28, round(selected.pointSize() / 0.75)))
self.font_scale = self.document_font_size / 16
self._update_theme_menu_state()
self._save_preferences()
self.refresh_document()
def set_document_font_size_from_action(self, action: QAction) -> None:
try:
size = int(action.data())
except (TypeError, ValueError):
return
self.document_font_size = max(12, min(size, 28))
self.font_scale = self.document_font_size / 16
self._update_theme_menu_state()
self._save_preferences()
self.refresh_document()
def choose_custom_document_font_size(self) -> None:
size, accepted = QInputDialog.getInt(self, "文档字号", "字号(px)", self.document_font_size, 12, 28, 1)
if not accepted:
return
self.document_font_size = size
self.font_scale = self.document_font_size / 16
self._update_theme_menu_state()
self._save_preferences()
self.refresh_document()
def set_math_engine(self, action: QAction) -> None:
engine = str(action.data() or "katex")
if engine not in {"katex", "mathjax"}:
engine = "katex"
if engine == self.math_engine:
return
self.math_engine = engine
self._update_math_engine_actions()
self._save_preferences()
self.refresh_document()
self.status_label.setText(f"公式引擎:{'MathJax' if engine == 'mathjax' else 'KaTeX'}")
def _update_math_engine_actions(self) -> None:
if hasattr(self, "katex_action"):
self.katex_action.setChecked(self.math_engine == "katex")
if hasattr(self, "mathjax_action"):
self.mathjax_action.setChecked(self.math_engine == "mathjax")
def open_settings_dialog(self) -> None:
dialog = SettingsDialog(
AppPreferences(
theme=self.theme,
theme_color=self.theme_color,
theme_background=self.theme_background,
font_scale=self.font_scale,
auto_refresh=self.auto_refresh_enabled,
non_preview_action=self.non_preview_action,
),
self,
)
if dialog.exec() != QDialog.DialogCode.Accepted:
return
preferences = dialog.preferences()
theme_changed = (
preferences.theme != self.theme
or preferences.theme_color != self.theme_color
or preferences.theme_background != self.theme_background
)
font_changed = abs(preferences.font_scale - self.font_scale) > 0.001
self._set_theme_color(preferences.theme_color)
self.theme_background = preferences.theme_background
self.font_scale = preferences.font_scale
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
self.auto_refresh_enabled = preferences.auto_refresh
self.non_preview_action = preferences.non_preview_action
self._update_theme_menu_state()
self._apply_navigation_style()
self._save_preferences()
if theme_changed or font_changed:
self.refresh_document()
LOGGER.info("Updated preferences: %s", preferences)
def find_current_text(self) -> None:
if self.find_box.text().strip():
self.find_in_page(backward=False)
def focus_find_box(self) -> None:
self.find_box.setFocus()
self.find_box.selectAll()
def focus_search_box(self) -> None:
self.search_box.setFocus()
self.search_box.selectAll()
def find_next(self) -> None:
self.find_in_page(backward=False)
def find_previous(self) -> None:
self.find_in_page(backward=True)
def find_in_page(self, backward: bool) -> None:
text = self.find_box.text()
if not text:
self.find_result_label.clear()
return
flags = QWebEnginePage.FindFlag(0)
if backward:
flags = QWebEnginePage.FindFlag.FindBackward
self.web_view.findText(text, flags, self._on_find_text_result)
def _on_find_text_result(self, result: object) -> None:
try:
active = int(result.activeMatch())
total = int(result.numberOfMatches())
except (AttributeError, TypeError, ValueError):
return
if total <= 0:
self.find_result_label.setText("0/0")
else:
self.find_result_label.setText(f"{active}/{total}")
def clear_recent_files(self) -> None:
self.recent_files.clear()
self._update_recent_menu()
self._save_preferences()
def add_current_bookmark(self) -> None:
if self.current_file is None:
return
label = self.current_file.stem
if self.current_fragment:
label = f"{label} #{self.current_fragment}"
bookmark = {
"path": str(self.current_file),
"fragment": self.current_fragment,
"label": label,
}
self.bookmarks = [
item
for item in self.bookmarks
if item.get("path") != bookmark["path"] or item.get("fragment", "") != bookmark["fragment"]
]
self.bookmarks.insert(0, bookmark)
self.bookmarks = self.bookmarks[:40]
self._update_bookmarks_menu()
self._save_preferences()
self.status_label.setText(f"已添加书签:{label}")
def clear_bookmarks(self) -> None:
self.bookmarks.clear()
self._update_bookmarks_menu()
self._save_preferences()
def manage_bookmarks(self) -> None:
dialog = BookmarkManagerDialog(self.bookmarks, self)
dialog.exec()
self.bookmarks = dialog.bookmarks()
self._update_bookmarks_menu()
self._save_preferences()
if dialog.selected_bookmark:
path = Path(dialog.selected_bookmark.get("path", ""))
fragment = dialog.selected_bookmark.get("fragment", "")
if path.exists():
self.open_document(path, fragment=fragment)
def scroll_to_anchor(self, fragment: str, add_history: bool = True) -> None:
if not fragment:
return
self.current_fragment = fragment
current = self.tabs.currentWidget()
if isinstance(current, ReaderView):
current.setProperty("current_fragment", fragment)
if add_history and self.current_file is not None:
self._store_current_history_scroll()
self._current_history().push(HistoryItem(path=self.current_file, fragment=fragment, scroll_y=0))
self._update_actions()
script = (
"const id = decodeURIComponent("
f"{json.dumps(fragment)}"
");"
"const target = document.getElementById(id);"
"if (target) { target.scrollIntoView({block: 'start'}); }"
)
self.web_view.page().runJavaScript(script)
def _open_tree_item(self, item: QTreeWidgetItem) -> None:
data = item.data(0, Qt.ItemDataRole.UserRole)
if data:
self.open_document(Path(data))
def _filter_tree(self, query: str) -> None:
visible_paths = {entry.path for entry in self.entries if self.search_index.matches_entry(entry, query)}
matches = self.search_index.search(query)
self.search_results.clear()
def apply_visibility(item: QTreeWidgetItem) -> bool:
data = item.data(0, Qt.ItemDataRole.UserRole)
if data:
visible = Path(data) in visible_paths
item.setHidden(not visible)
return visible
any_visible = False
for child_index in range(item.childCount()):
any_visible = apply_visibility(item.child(child_index)) or any_visible
item.setHidden(not any_visible)
return any_visible
for index in range(self.tree.topLevelItemCount()):
apply_visibility(self.tree.topLevelItem(index))
if query.strip():
for match in matches:
count_label = f"{match.match_count}处" if match.match_count else "匹配"
label = f"[{match.match_kind} {count_label}] {match.entry.title} ({match.entry.relative_path})"
result_item = QTreeWidgetItem([label])
result_item.setData(0, Qt.ItemDataRole.UserRole, str(match.entry.path))
result_item.setToolTip(0, f"{match.match_kind}命中,共 {match.match_count} 处\n{match.snippet}")
self.search_results.addTopLevelItem(result_item)
self.search_results_label.show()
self.search_results.show()
total_hits = sum(match.match_count for match in matches)
self.search_results_label.setText(f"搜索结果:{len(matches)} 个文档 / {total_hits} 处命中")
self.status_label.setText(f"找到 {len(matches)} 个匹配文档,{total_hits} 处命中")
elif self.current_file is not None:
self.search_results_label.setText("搜索结果")
self.search_results_label.hide()
self.search_results.hide()
self.status_label.setText(self._display_path(self.current_file))
def _select_tree_item(self, path: Path) -> None:
item = self.path_to_item.get(path)
if item is None:
return
self.tree.setCurrentItem(item)
self.tree.scrollToItem(item)
def _on_load_finished(self, ok: bool) -> None:
if not ok:
self.status_label.setText("加载失败")
return
if self.pending_fragment:
self.scroll_to_anchor(self.pending_fragment, add_history=False)
self.pending_fragment = ""
if self.pending_find_text:
self.find_in_page(backward=False)
self.pending_find_text = ""
elif self.pending_scroll_y is not None:
self._scroll_to_position(self.pending_scroll_y)
self.pending_scroll_y = None
def _on_reader_scroll_changed(self, progress: float, heading_id: str, scroll_y: int) -> None:
sender_bridge = self.sender()
current = self.tabs.currentWidget()
if not isinstance(current, ReaderView) or getattr(current, "reader_bridge", None) is not sender_bridge:
return
current.setProperty("scroll_y", max(0, int(scroll_y)))
self.reading_progress.setValue(max(0, min(100, int(round(progress)))))
self._highlight_toc_heading(heading_id)
def _update_actions(self) -> None:
history = self._current_history()
self.back_action.setEnabled(history.can_go_back)
self.forward_action.setEnabled(history.can_go_forward)
def _tab_history(self, web_view: QWebEngineView) -> NavigationHistory:
history = getattr(web_view, "navigation_history", None)
if isinstance(history, NavigationHistory):
return history
history = NavigationHistory()
setattr(web_view, "navigation_history", history)
return history
def _current_history(self) -> NavigationHistory:
current = self.tabs.currentWidget()
if isinstance(current, QWebEngineView):
return self._tab_history(current)
return NavigationHistory()
def _store_current_history_scroll(self) -> None:
current = self.tabs.currentWidget()
if not isinstance(current, ReaderView):
return
history = self._tab_history(current)
item = history.current
if item is None:
return
try:
scroll_y = int(current.property("scroll_y") or 0)
except (TypeError, ValueError):
scroll_y = 0
history.replace_current(HistoryItem(path=item.path, fragment=item.fragment, scroll_y=max(0, scroll_y)))
def _populate_toc(self, path: Path) -> None:
self.toc_tree.clear()
stack: list[tuple[int, QTreeWidgetItem]] = []
for heading in extract_headings(path):
item = QTreeWidgetItem([heading.title])
item.setData(0, Qt.ItemDataRole.UserRole, heading.slug)
item.setToolTip(0, f"#{heading.slug}")
while stack and stack[-1][0] >= heading.level:
stack.pop()
if stack:
stack[-1][1].addChild(item)
else:
self.toc_tree.addTopLevelItem(item)
stack.append((heading.level, item))
self.toc_tree.expandAll()
def _highlight_toc_heading(self, heading_id: str) -> None:
if not heading_id:
return
matches = self.toc_tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive)
for item in matches:
if item.data(0, Qt.ItemDataRole.UserRole) == heading_id:
if self.toc_tree.currentItem() is not item:
self.toc_tree.setCurrentItem(item)
return
def _open_toc_item(self, item: QTreeWidgetItem) -> None:
slug = item.data(0, Qt.ItemDataRole.UserRole)
if slug:
self.scroll_to_anchor(str(slug))
def _open_search_result(self, item: QTreeWidgetItem) -> None:
data = item.data(0, Qt.ItemDataRole.UserRole)
if data:
query = self.search_box.text().strip()
if query:
self.pending_find_text = query
blocker = QSignalBlocker(self.find_box)
self.find_box.setText(query)
del blocker
self.open_document(Path(data))
def _ensure_document_entry(self, path: Path) -> None:
if any(entry.path == path for entry in self.entries):
return
title = first_heading(path) or path.stem.replace("_", " ").title()
try:
relative_path = path.relative_to(self.project_root).as_posix()
except ValueError:
relative_path = str(path)
self.entries.append(DocumentEntry(path=path, title=title, relative_path=relative_path))
self.search_index.rebuild(self.entries)
self._populate_tree()
self._filter_tree(self.search_box.text())
def _display_path(self, path: Path) -> str:
try:
return path.relative_to(self.project_root).as_posix()
except ValueError:
return str(path)
def _show_link_status(self, url: str) -> None:
if url:
self.status_label.setText(url)
elif self.current_file is not None:
self.status_label.setText(self._display_path(self.current_file))
def _on_pdf_printing_finished(self, file_path: str, success: bool) -> None:
if success:
LOGGER.info("PDF exported: %s", file_path)
self.status_label.setText(f"PDF 已导出:{file_path}")
else:
LOGGER.error("PDF export failed: %s", file_path)
QMessageBox.warning(self, "导出失败", f"无法导出 PDF:\n{file_path}")
def _remember_recent_file(self, path: Path) -> None:
if path.suffix.lower() not in {".md", ".markdown"}:
return
self.recent_files = [item for item in self.recent_files if item != path]
self.recent_files.insert(0, path)
self.recent_files = self.recent_files[:10]
self._update_recent_menu()
def _update_recent_menu(self) -> None:
self.recent_menu.clear()
existing = [path for path in self.recent_files if path.exists()]
self.recent_files = existing[:10]
if not self.recent_files:
empty_action = QAction("无最近文件", self)
empty_action.setEnabled(False)
self.recent_menu.addAction(empty_action)
return
for path in self.recent_files:
action = QAction(self._display_path(path), self)
action.setToolTip(str(path))
action.triggered.connect(lambda checked=False, file_path=path: self.open_document(file_path))
self.recent_menu.addAction(action)
def _update_bookmarks_menu(self) -> None:
self.bookmarks_menu.clear()
valid_bookmarks = [item for item in self.bookmarks if Path(item.get("path", "")).exists()]
self.bookmarks = valid_bookmarks[:40]
if not self.bookmarks:
empty_action = QAction("无书签", self)
empty_action.setEnabled(False)
self.bookmarks_menu.addAction(empty_action)
return
for item in self.bookmarks:
path = Path(item["path"])
fragment = item.get("fragment", "")
label = item.get("label") or self._display_path(path)
action = QAction(label, self)
action.setToolTip(str(path))
action.triggered.connect(
lambda checked=False, file_path=path, target_fragment=fragment: self.open_document(
file_path,
fragment=target_fragment,
)
)
self.bookmarks_menu.addAction(action)
def _load_preferences(self) -> None:
self.theme = str(self.settings.value("reader/theme", "light"))
self.theme_color = str(self.settings.value("reader/theme_color", ""))
if self.theme_color not in {"white", "black", "dark_gray", "colorful"}:
self.theme_color = "black" if self.theme == "dark" else "white"
self.theme = self._reader_theme_for_color(self.theme_color)
self.theme_background = str(self.settings.value("reader/theme_background", "none"))
if self.theme_background not in {
"none",
"spring",
"straw",
"circuit",
"tree_rings",
"geometry",
"calligraphy",
"underwater",
}:
self.theme_background = "none"
self.math_engine = str(self.settings.value("reader/math_engine", "katex"))
if self.math_engine not in {"katex", "mathjax"}:
self.math_engine = "katex"
self.font_scale = float(self.settings.value("reader/font_scale", 1.0))
self.document_font_size = max(12, min(28, round(self.font_scale * 16)))
try:
self.document_font_size = max(12, min(28, int(self.settings.value("reader/document_font_size", self.document_font_size))))
except (TypeError, ValueError):
pass
self.font_scale = self.document_font_size / 16
self.ui_font_family = str(self.settings.value("reader/ui_font_family", "")).strip()
try:
self.ui_font_point_size = max(0, min(32, int(self.settings.value("reader/ui_font_point_size", 0))))
except (TypeError, ValueError):
self.ui_font_point_size = 0
self.document_font_family = str(self.settings.value("reader/document_font_family", "")).strip()
self.auto_refresh_enabled = self.settings.value("reader/auto_refresh", True, type=bool)
self.non_preview_action = str(self.settings.value("reader/non_preview_action", "ask"))
if self.non_preview_action not in {"ask", "open", "block"}:
self.non_preview_action = "ask"
recent_value = self.settings.value("recent/files", [])
if isinstance(recent_value, str):
recent_paths = [recent_value]
else:
recent_paths = list(recent_value or [])
self.recent_files = [Path(str(path)).resolve() for path in recent_paths if str(path)]
bookmarks = self._load_json_setting(BOOKMARKS_SETTING_KEY, [])
scroll_positions = self._load_json_setting(SCROLL_POSITIONS_SETTING_KEY, {})
external_applications = self._load_json_setting(EXTERNAL_APPLICATIONS_SETTING_KEY, {})
self.bookmarks = bookmarks if isinstance(bookmarks, list) else []
self.scroll_positions = scroll_positions if isinstance(scroll_positions, dict) else {}
if isinstance(external_applications, dict):
self.external_applications = {
str(extension).lower(): str(program)
for extension, program in external_applications.items()
if str(extension).startswith(".") and str(program)
}
def _save_preferences(self) -> None:
self.settings.setValue("reader/theme", self.theme)
self.settings.setValue("reader/theme_color", self.theme_color)
self.settings.setValue("reader/theme_background", self.theme_background)
self.settings.setValue("reader/math_engine", self.math_engine)
self.settings.setValue("reader/font_scale", self.font_scale)
self.settings.setValue("reader/ui_font_family", self.ui_font_family)
self.settings.setValue("reader/ui_font_point_size", self.ui_font_point_size)
self.settings.setValue("reader/document_font_family", self.document_font_family)
self.settings.setValue("reader/document_font_size", self.document_font_size)
self.settings.setValue("reader/auto_refresh", self.auto_refresh_enabled)
self.settings.setValue("reader/non_preview_action", self.non_preview_action)
self.settings.setValue("recent/files", [str(path) for path in self.recent_files])
self.settings.setValue(BOOKMARKS_SETTING_KEY, json.dumps(self.bookmarks, ensure_ascii=False))
self.settings.setValue(SCROLL_POSITIONS_SETTING_KEY, json.dumps(self.scroll_positions, ensure_ascii=False))
self.settings.setValue(
EXTERNAL_APPLICATIONS_SETTING_KEY,
json.dumps(self.external_applications, ensure_ascii=False),
)
if hasattr(self, "splitter"):
self.settings.setValue("window/splitter", self.splitter.saveState())
self.settings.setValue("window/geometry", self.saveGeometry())
def _restore_window_state(self) -> None:
geometry = self.settings.value("window/geometry")
if geometry is not None:
self.restoreGeometry(geometry)
splitter_state = self.settings.value("window/splitter")
if splitter_state is not None:
self.splitter.restoreState(splitter_state)
def _load_json_setting(self, key: str, fallback: object) -> object:
value = self.settings.value(key, "")
if not value:
return fallback
try:
return json.loads(str(value))
except json.JSONDecodeError:
return fallback
def _save_current_scroll_position(self) -> None:
if self.current_file is None:
return
path_key = str(self.current_file)
def store_scroll(scroll_y: object) -> None:
try:
position = int(float(scroll_y or 0))
except (TypeError, ValueError):
position = 0
self.scroll_positions[path_key] = max(0, position)
self.web_view.page().runJavaScript("Math.max(0, window.scrollY || 0)", store_scroll)
def _scroll_to_position(self, scroll_y: int) -> None:
script = f"window.scrollTo({{top: {max(0, scroll_y)}, behavior: 'instant'}});"
self.web_view.page().runJavaScript(script)
def _update_watched_paths(self) -> None:
watched_files = self.file_watcher.files()
watched_dirs = self.file_watcher.directories()
if watched_files:
self.file_watcher.removePaths(watched_files)
if watched_dirs:
self.file_watcher.removePaths(watched_dirs)
paths: set[Path] = set()
directories: set[Path] = {self.project_root}
docs_dir = self.project_root / "docs"
media_dir = self.project_root / "media"
if docs_dir.exists():
directories.add(docs_dir)
if media_dir.exists():
directories.add(media_dir)
sample = self.project_root / "sample.md"
if sample.exists():
paths.add(sample.resolve())
if self.current_file is not None:
paths.add(self.current_file)
directories.add(self.current_file.parent)
paths.update(self._referenced_local_paths(self.current_file))
file_paths = [str(path) for path in paths if path.exists() and path.is_file()]
dir_paths = [str(path) for path in directories if path.exists() and path.is_dir()]
if file_paths:
self.file_watcher.addPaths(file_paths)
if dir_paths:
self.file_watcher.addPaths(dir_paths)
def _referenced_local_paths(self, markdown_path: Path) -> set[Path]:
try:
source = markdown_path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return set()
paths: set[Path] = set()
for match in re_find_markdown_links(source):
target = match.strip()
parsed = urlsplit(target)
if parsed.scheme or not parsed.path or parsed.path.startswith("#"):
continue
local_path = (markdown_path.parent / unquote(parsed.path)).resolve()
if local_path.exists() and local_path.is_file():
paths.add(local_path)
return paths
def _on_watched_file_changed(self, changed_path: str) -> None:
if not self.auto_refresh_enabled:
return
changed = Path(changed_path).resolve()
if self.current_file is not None and changed == self.current_file:
self.refresh_timer.start()
elif self.current_file is not None and changed in self._referenced_local_paths(self.current_file):
self.refresh_timer.start()
self._update_watched_paths()
def _on_watched_directory_changed(self, changed_path: str) -> None:
if not self.auto_refresh_enabled:
return
changed = Path(changed_path).resolve()
docs_dir = (self.project_root / "docs").resolve()
if changed in {self.project_root, docs_dir}:
self.tree_refresh_timer.start()
if self.current_file is not None:
media_dir = (self.project_root / "media").resolve()
if changed in {self.current_file.parent.resolve(), media_dir}:
self.refresh_timer.start()
self._update_watched_paths()
def _auto_refresh_current_document(self) -> None:
if self.current_file is not None and self.current_file.exists():
self.refresh_document()
def _refresh_document_entries(self) -> None:
previous_current = self.current_file
self.entries = discover_documents(self.project_root)
self.search_index.rebuild(self.entries)
if (
previous_current is not None
and previous_current.exists()
and all(entry.path != previous_current for entry in self.entries)
):
self._ensure_document_entry(previous_current)
else:
self._populate_tree()
self._filter_tree(self.search_box.text())
self._update_watched_paths()
def closeEvent(self, event: QCloseEvent) -> None:
self._save_current_scroll_position()
self._save_preferences()
super().closeEvent(event)
def showEvent(self, event: QShowEvent) -> None:
super().showEvent(event)
QTimer.singleShot(0, self._apply_navigation_style)