diff --git a/MDHelper.spec b/MDHelper.spec index fe79fcb..5e82009 100644 --- a/MDHelper.spec +++ b/MDHelper.spec @@ -6,6 +6,7 @@ from pathlib import Path project_root = Path(SPECPATH) datas = [ + (str(project_root / "icon_glass.png"), "."), (str(project_root / "sample.md"), "."), (str(project_root / "docs"), "docs"), (str(project_root / "media"), "media"), @@ -46,4 +47,5 @@ exe = EXE( target_arch=None, codesign_identity=None, entitlements_file=None, + icon=str(project_root / "icon_glass.ico"), ) diff --git a/icon_glass.ico b/icon_glass.ico new file mode 100644 index 0000000..20d3d53 Binary files /dev/null and b/icon_glass.ico differ diff --git a/icon_glass.png b/icon_glass.png new file mode 100644 index 0000000..88b552f Binary files /dev/null and b/icon_glass.png differ diff --git a/mdhelper/app.py b/mdhelper/app.py index 2cbf08e..5857636 100644 --- a/mdhelper/app.py +++ b/mdhelper/app.py @@ -5,7 +5,8 @@ import logging import sys from pathlib import Path -from PySide6.QtCore import Qt +from PySide6.QtCore import QSettings, Qt +from PySide6.QtGui import QIcon from PySide6.QtWidgets import QApplication from . import __version__ @@ -22,11 +23,7 @@ def parse_arguments(argv: list[str]) -> argparse.Namespace: return parser.parse_args(argv) -def runtime_paths(project_root_arg: str | None = None) -> tuple[Path, Path]: - if project_root_arg: - root = Path(project_root_arg).resolve() - return root, root - +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 @@ -38,27 +35,46 @@ def runtime_paths(project_root_arg: str | None = None) -> tuple[Path, Path]: def main(argv: list[str] | None = None) -> int: args = parse_arguments(list(sys.argv[1:] if argv is None else argv)) - project_root, log_root = runtime_paths(args.project_root) + 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)]) + return check_documents_main([str(project_root or content_root)]) QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True) setup_logging(log_root) - logging.getLogger(__name__).info( - "Starting MDHelper %s with project_root=%s log_root=%s", - __version__, - project_root, - 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() - initial_path = Path(args.file).expanduser().resolve() if args.file else None - window = MainWindow(project_root=project_root, initial_path=initial_path) - window.resize(1280, 820) + 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() diff --git a/mdhelper/document_tree.py b/mdhelper/document_tree.py index dc1ada6..90782e4 100644 --- a/mdhelper/document_tree.py +++ b/mdhelper/document_tree.py @@ -3,8 +3,26 @@ from __future__ import annotations from dataclasses import dataclass from pathlib import Path +from .media import MARKDOWN_EXTENSIONS, WEBPAGE_EXTENSIONS from .markdown_utils import extract_headings +SUPPORTED_DOCUMENT_EXTENSIONS = MARKDOWN_EXTENSIONS | WEBPAGE_EXTENSIONS + +EXCLUDED_DIR_NAMES = { + ".git", + "__pycache__", + ".pytest_cache", + ".mypy_cache", + "build", + "dist", + "logs", + "html", + "mdhelper_env", + "vendor", + "venv", + ".venv", +} + @dataclass(frozen=True) class DocumentEntry: @@ -14,20 +32,20 @@ class DocumentEntry: def first_heading(path: Path) -> str | None: + if path.suffix.lower() not in {".md", ".markdown"}: + return None headings = extract_headings(path) return headings[0].title if headings else None def discover_documents(project_root: Path) -> list[DocumentEntry]: - candidates: list[Path] = [] - - sample = project_root / "sample.md" - if sample.exists(): - candidates.append(sample) - - docs_dir = project_root / "docs" - if docs_dir.exists(): - candidates.extend(sorted(docs_dir.rglob("*.md"))) + candidates = [ + path + for path in sorted(project_root.rglob("*")) + if path.is_file() + and path.suffix.lower() in SUPPORTED_DOCUMENT_EXTENSIONS + and not any(part.startswith(".") or part in EXCLUDED_DIR_NAMES for part in path.relative_to(project_root).parts) + ] entries: list[DocumentEntry] = [] for path in candidates: diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 0b0792f..0d1ae1e 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -1,6 +1,7 @@ from __future__ import annotations import html +import time import json import logging import os @@ -10,14 +11,29 @@ 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.QtCore import QFileSystemWatcher, QObject, QPoint, QProcess, QSettings, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot +from PySide6.QtGui import ( + QAction, + QActionGroup, + QBrush, + QCloseEvent, + QColor, + QDesktopServices, + QFont, + QIcon, + QPainter, + QPen, + QPixmap, + QShowEvent, +) from PySide6.QtWebChannel import QWebChannel from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineSettings from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWidgets import ( QApplication, + QComboBox, QFileDialog, + QFontComboBox, QFontDialog, QInputDialog, QLabel, @@ -27,22 +43,26 @@ from PySide6.QtWidgets import ( QMenu, QMessageBox, QProgressBar, + QPushButton, QSplitter, QStatusBar, QStyledItemDelegate, + QStyle, QTabWidget, QToolBar, QTreeWidget, QTreeWidgetItem, + QHBoxLayout, QVBoxLayout, QWidget, ) from .bookmark_dialog import BookmarkManagerDialog from . import __version__ -from .document_tree import DocumentEntry, discover_documents, first_heading +from .document_tree import DocumentEntry, SUPPORTED_DOCUMENT_EXTENSIONS, discover_documents, first_heading from .history import HistoryItem, NavigationHistory -from .markdown_utils import extract_headings +from .markdown_utils import Heading, extract_headings, extract_headings_from_text +from .markdown_editor import MarkdownEditorDialog as RichMarkdownEditorDialog from .markdown_renderer import MarkdownRenderer from .media import is_markdown_url, is_webpage_url, media_kind, media_mime_type from .search import SearchIndex @@ -52,7 +72,30 @@ 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" +EDITOR_DRAFTS_SETTING_KEY = "editor/drafts" +LAST_PROJECT_ROOT_SETTING_KEY = "project/last_root" LOGGER = logging.getLogger(__name__) +THEME_COLOR_VALUES = {"white", "black", "dark_gray", "colorful"} +THEME_BACKGROUND_OPTIONS = ( + ("无", "none"), + ("中国结", "chinese_knot"), + ("祥云", "cloud"), + ("如意", "ruyi"), + ("毛笔", "brush"), + ("牡丹", "peony"), + ("竹", "bamboo"), + ("回纹", "meander"), +) +THEME_BACKGROUND_VALUES = {value for _, value in THEME_BACKGROUND_OPTIONS} +LEGACY_THEME_BACKGROUND_VALUES = { + "spring", + "straw", + "circuit", + "tree_rings", + "geometry", + "calligraphy", + "underwater", +} def re_find_markdown_links(source: str) -> list[str]: @@ -119,20 +162,32 @@ class ReaderView(QWebEngineView): 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) + if self._show_link_context_menu(link_url, event.globalPos()): request.setAccepted(True) return super().contextMenuEvent(event) + def _show_link_context_menu(self, link_url: QUrl, global_pos: object) -> bool: + menu = self._create_link_context_menu() + chosen = menu.exec(global_pos) + if chosen is None: + return False + return self._handle_link_context_action(link_url, bool(chosen.data())) + + def _create_link_context_menu(self) -> QMenu: + menu = QMenu(self) + open_current = menu.addAction("在本标签页打开") + open_current.setData(False) + open_new = menu.addAction("新建标签页打开") + open_new.setData(True) + return menu + + def _handle_link_context_action(self, link_url: QUrl, new_tab: bool) -> bool: + if not link_url.isValid() or link_url.isEmpty(): + return False + self.open_link_requested.emit(link_url, new_tab) + return True + class CompactTreeDelegate(QStyledItemDelegate): def sizeHint(self, option: object, index: object) -> object: @@ -143,11 +198,21 @@ class CompactTreeDelegate(QStyledItemDelegate): class MainWindow(QMainWindow): - def __init__(self, project_root: Path, initial_path: Path | None = None) -> None: + def __init__( + self, + project_root: Path | None, + initial_path: Path | None = None, + app_root: Path | None = None, + prompt_for_project: bool = False, + ) -> None: super().__init__() - self.project_root = project_root.resolve() + self.app_root = (app_root or project_root or Path.cwd()).resolve() + self.resources_dir = Path(__file__).resolve().parent / "resources" + self.base_window_icon_path = self.app_root / "icon_glass.png" + self.project_root = (project_root or self.app_root).resolve() + self.has_project = project_root is not None self.renderer = MarkdownRenderer(self.project_root) - self.entries: list[DocumentEntry] = discover_documents(self.project_root) + self.entries: list[DocumentEntry] = discover_documents(self.project_root) if self.has_project else [] self.search_index = SearchIndex(self.entries) self.settings = QSettings("MDHelper", "MDHelper") self.current_file: Path | None = None @@ -157,12 +222,13 @@ class MainWindow(QMainWindow): self.pending_scroll_y: int | None = None self.font_scale = 1.0 self.theme = "light" - self.theme_color = "white" + self.theme_color = "colorful" self.theme_background = "none" self.ui_font_family = "" self.ui_font_point_size = 0 self.document_font_family = "" self.document_font_size = 16 + self.document_tree_label_mode = "title" self.math_engine = "katex" self.auto_refresh_enabled = True self.non_preview_action = "ask" @@ -170,7 +236,11 @@ class MainWindow(QMainWindow): self.bookmarks: list[dict[str, str]] = [] self.scroll_positions: dict[str, int] = {} self.external_applications: dict[str, str] = {} + self.editor_drafts: dict[str, dict[str, str]] = {} self.path_to_item: dict[Path, QTreeWidgetItem] = {} + self.file_tree_icon_cache: dict[tuple[str, str], QIcon] = {} + self.folder_tree_icon_cache: dict[str, QIcon] = {} + self.internal_save_paths: set[Path] = set() 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) @@ -191,25 +261,42 @@ class MainWindow(QMainWindow): self._load_preferences() self.setWindowTitle("MDHelper") + icon_path = self.base_window_icon_path + if icon_path.exists(): + icon = QIcon(str(icon_path)) + self.setWindowIcon(icon) + app = QApplication.instance() + if app is not None: + app.setWindowIcon(icon) self._build_ui() self.scroll_capture_timer.start() self._populate_tree() - self._restore_window_state() + if not self._restore_window_state(): + self.resize(1280, 820) 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_path is not None and initial_path.exists(): + initial = initial_path.resolve() if initial.suffix.lower() in {".md", ".markdown"}: + self.set_project_root(initial.parent, save=True) self._ensure_document_entry(initial) self.open_document(initial) elif initial.suffix.lower() in {".html", ".htm", ".xhtml"}: + self.set_project_root(initial.parent, save=True) self._open_webpage_file_now(initial) else: + self.set_project_root(initial.parent, save=True) QTimer.singleShot(0, lambda path=initial: self._open_local_file_now(path)) + elif self.has_project: + self.status_label.setText(f"已打开文件夹:{self.project_root}") + else: + self.status_label.setText("请选择文件夹或文件") + if prompt_for_project: + QTimer.singleShot(0, self.prompt_open_project) + + def _standard_icon(self, standard_name: str, fallback: QStyle.StandardPixmap) -> QIcon: + pixmap = getattr(QStyle.StandardPixmap, standard_name, fallback) + return self.style().standardIcon(pixmap) def _build_ui(self) -> None: file_menu = self.menuBar().addMenu("文件") @@ -220,26 +307,33 @@ class MainWindow(QMainWindow): toolbar = QToolBar("主工具栏") toolbar.setMovable(False) + toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) self.addToolBar(toolbar) self.back_action = QAction("后退", self) + self.back_action.setIcon(self._standard_icon("SP_ArrowBack", QStyle.StandardPixmap.SP_ArrowLeft)) + self.back_action.setToolTip("后退") self.back_action.triggered.connect(self.go_back) toolbar.addAction(self.back_action) self.forward_action = QAction("前进", self) + self.forward_action.setIcon(self._standard_icon("SP_ArrowForward", QStyle.StandardPixmap.SP_ArrowRight)) + self.forward_action.setToolTip("前进") 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.setIcon(self._standard_icon("SP_DialogOpenButton", QStyle.StandardPixmap.SP_DirOpenIcon)) + self.open_action.setToolTip("打开") 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.open_folder_action = QAction("打开文件夹", self) + self.open_folder_action.triggered.connect(self.open_project_folder) + file_menu.addAction(self.open_folder_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) @@ -264,19 +358,32 @@ class MainWindow(QMainWindow): file_menu.addAction(self.clear_recent_action) self.refresh_action = QAction("刷新", self) + self.refresh_action.setIcon(self._standard_icon("SP_BrowserReload", QStyle.StandardPixmap.SP_FileDialogContentsView)) + self.refresh_action.setToolTip("刷新") 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) + toolbar.addWidget(QLabel("字体")) + self.document_font_box = QFontComboBox() + self.document_font_box.setToolTip("文档字体") + self.document_font_box.setMaximumWidth(180) + if self.document_font_family: + self.document_font_box.setCurrentFont(QFont(self.document_font_family)) + self.document_font_box.currentFontChanged.connect(self.set_document_font_from_toolbar) + toolbar.addWidget(self.document_font_box) - self.zoom_in_action = QAction("A+", self) - self.zoom_in_action.triggered.connect(self.increase_font) - toolbar.addAction(self.zoom_in_action) + toolbar.addWidget(QLabel("字号")) + self.document_font_size_box = QComboBox() + self.document_font_size_box.setToolTip("文档字号") + self.document_font_size_box.setFixedWidth(72) + for size in range(12, 29): + self.document_font_size_box.addItem(str(size), size) + self.document_font_size_box.setCurrentText(str(self.document_font_size)) + self.document_font_size_box.currentTextChanged.connect(self.set_document_font_size_from_toolbar) + toolbar.addWidget(self.document_font_size_box) self.focus_find_action = QAction("页内查找", self) self.focus_find_action.setShortcut("Ctrl+F") @@ -288,6 +395,12 @@ class MainWindow(QMainWindow): self.focus_search_action.triggered.connect(self.focus_search_box) edit_menu.addAction(self.focus_search_action) + edit_menu.addSeparator() + self.edit_current_action = QAction("编辑当前 Markdown", self) + self.edit_current_action.setShortcut("Ctrl+E") + self.edit_current_action.triggered.connect(self.edit_current_markdown) + edit_menu.addAction(self.edit_current_action) + self.math_engine_menu = edit_menu.addMenu("公式引擎") self.math_engine_group = QActionGroup(self) self.math_engine_group.setExclusive(True) @@ -306,6 +419,10 @@ class MainWindow(QMainWindow): self.settings_action.triggered.connect(self.open_settings_dialog) tools_menu.addAction(self.settings_action) + self.manage_external_apps_action = QAction("管理外部打开程序", self) + self.manage_external_apps_action.triggered.connect(self.manage_external_applications) + tools_menu.addAction(self.manage_external_apps_action) + self.about_action = QAction("关于 MDHelper", self) self.about_action.triggered.connect(self.show_about_dialog) tools_menu.addAction(self.about_action) @@ -352,6 +469,8 @@ class MainWindow(QMainWindow): self._configure_navigation_tree(self.tree) self.tree.itemActivated.connect(self._open_tree_item) self.tree.itemClicked.connect(self._open_tree_item) + self.tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.tree.customContextMenuRequested.connect(self._show_tree_context_menu) self.search_box = QLineEdit() self.search_box.setObjectName("panelSearchBox") @@ -388,14 +507,14 @@ class MainWindow(QMainWindow): 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._show_welcome_tab() 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) + self.toc_tree.itemActivated.connect(lambda item, column: self._open_toc_item(item)) + self.toc_tree.itemPressed.connect(lambda item, column: self._open_toc_item(item)) toc_panel = QWidget() toc_panel.setObjectName("tocPanel") @@ -437,10 +556,10 @@ class MainWindow(QMainWindow): self.theme_color_group = QActionGroup(self) self.theme_color_group.setExclusive(True) for label, value in ( + ("彩色", "colorful"), ("黑色", "black"), ("白色", "white"), ("深灰色", "dark_gray"), - ("彩色", "colorful"), ): action = QAction(label, self) action.setCheckable(True) @@ -452,16 +571,7 @@ class MainWindow(QMainWindow): 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"), - ): + for label, value in THEME_BACKGROUND_OPTIONS: action = QAction(label, self) action.setCheckable(True) action.setData(value) @@ -523,6 +633,7 @@ class MainWindow(QMainWindow): return web_view def _prepare_target_tab(self, new_tab: bool, title: str) -> ReaderView: + self._close_welcome_tab() if new_tab: web_view = self._create_reader_view() index = self.tabs.addTab(web_view, title) @@ -540,8 +651,85 @@ class MainWindow(QMainWindow): 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) + def _welcome_html(self) -> str: + body = """ +

欢迎使用 MDHelper

+

MDHelper 是一个本地 Markdown 帮助文档阅读器,支持目录导航、全文搜索、多标签阅读、图片/音频/视频预览、Mermaid 图表和数学公式。

+

开始使用

+ +

常用操作

+ +

请选择文件夹或文件开始阅读。

+""" + return self.renderer.wrap_body_for_display( + body, + "欢迎", + 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 _refresh_welcome_tab(self) -> None: + index = self._welcome_tab_index() + if index < 0: + return + widget = self.tabs.widget(index) + if not isinstance(widget, ReaderView): + return + widget.setHtml(self._welcome_html(), QUrl.fromLocalFile(str(self.app_root) + os.sep)) + if self.tabs.currentIndex() == index: + self.web_view = widget + + def _show_welcome_tab(self) -> None: + if self._welcome_tab_index() >= 0: + return + web_view = self._create_reader_view() + web_view.setProperty("is_welcome", True) + web_view.setHtml(self._welcome_html(), QUrl.fromLocalFile(str(self.app_root) + os.sep)) + index = self.tabs.addTab(web_view, "欢迎") + self.tabs.setCurrentIndex(index) + self.web_view = web_view + self.current_file = None + self.current_fragment = "" + if hasattr(self, "toc_tree"): + self.toc_tree.clear() + + def _welcome_tab_index(self) -> int: + if not hasattr(self, "tabs"): + return -1 + for index in range(self.tabs.count()): + if bool(self.tabs.widget(index).property("is_welcome")): + return index + return -1 + + def _close_welcome_tab(self) -> None: + index = self._welcome_tab_index() + if index < 0: + return + widget = self.tabs.widget(index) + self.tabs.removeTab(index) + if widget is not None: + widget.deleteLater() + + def _ensure_welcome_if_empty(self) -> None: + if self.tabs.count() == 0: + self._show_welcome_tab() + + def _update_tab_title(self, widget: QWidget, title: str) -> None: + index = self.tabs.indexOf(widget) if index >= 0: self.tabs.setTabText(index, title) self.tabs.setTabToolTip(index, title) @@ -564,7 +752,7 @@ class MainWindow(QMainWindow): def _configure_navigation_tree(self, tree: QTreeWidget) -> None: tree.setAlternatingRowColors(False) tree.setAnimated(True) - tree.setIndentation(16) + tree.setIndentation(20) tree.setRootIsDecorated(True) tree.setUniformRowHeights(True) tree.setTextElideMode(Qt.TextElideMode.ElideRight) @@ -574,10 +762,30 @@ class MainWindow(QMainWindow): 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" + if theme_color not in THEME_COLOR_VALUES: + theme_color = "colorful" self.theme_color = theme_color self.theme = self._reader_theme_for_color(theme_color) + self._enforce_theme_background_rule() + + def _theme_background_enabled(self) -> bool: + return self.theme_color == "colorful" + + def _normalized_theme_background(self, theme_background: str, theme_color: str | None = None) -> str: + if theme_background in THEME_BACKGROUND_VALUES: + normalized = theme_background + elif theme_background in LEGACY_THEME_BACKGROUND_VALUES: + normalized = "none" + else: + normalized = "none" + + active_theme_color = theme_color or self.theme_color + if active_theme_color != "colorful" and normalized != "none": + return "none" + return normalized + + def _enforce_theme_background_rule(self) -> None: + self.theme_background = self._normalized_theme_background(self.theme_background) def _theme_color_label(self) -> str: return { @@ -585,30 +793,34 @@ class MainWindow(QMainWindow): "black": "黑色", "dark_gray": "深灰色", "colorful": "彩色", - }.get(self.theme_color, "白色") + }.get(self.theme_color, "彩色") def _theme_background_label(self) -> str: - return { - "none": "无", - "spring": "春天", - "straw": "稻草", - "circuit": "电路", - "tree_rings": "年轮", - "geometry": "几何图形", - "calligraphy": "书法", - "underwater": "水下", - }.get(self.theme_background, "无") + return dict(THEME_BACKGROUND_OPTIONS).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"): + background_enabled = self._theme_background_enabled() for action in self.theme_background_group.actions(): - action.setChecked(action.data() == self.theme_background) + data = action.data() + action.setChecked(data == self.theme_background) + action.setEnabled(background_enabled or data == "none") + if hasattr(self, "theme_background_menu"): + self.theme_background_menu.setToolTip("只有主题颜色为“彩色”时可以选择主题背景") 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) + if hasattr(self, "document_font_size_box"): + blocker = QSignalBlocker(self.document_font_size_box) + self.document_font_size_box.setCurrentText(str(self.document_font_size)) + del blocker + if hasattr(self, "document_font_box") and self.document_font_family: + blocker = QSignalBlocker(self.document_font_box) + self.document_font_box.setCurrentFont(QFont(self.document_font_family)) + del blocker def _apply_ui_font(self) -> None: app = QApplication.instance() @@ -621,6 +833,9 @@ class MainWindow(QMainWindow): font.setPointSize(self.ui_font_point_size) app.setFont(font) + def _stylesheet_url(self, path: Path) -> str: + return path.resolve().as_posix() + def _apply_navigation_style(self) -> None: palettes = { "white": { @@ -678,27 +893,28 @@ class MainWindow(QMainWindow): } 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"), + "none": ("", palette["chrome"], ""), + "chinese_knot": ("#d92f2f", "#fff1ef", "theme_chinese_knot.svg"), + "cloud": ("#8bd5ff", "#effaff", "theme_cloud.svg"), + "ruyi": ("#bfe9ca", "#f1fbf3", "theme_ruyi.svg"), + "brush": ("#d6d7dc", "#f5f6f8", "theme_brush.svg"), + "peony": ("#ffd0df", "#fff3f7", "theme_peony.svg"), + "bamboo": ("#a9d878", "#f1faeb", "theme_bamboo.svg"), + "meander": ("#ffd94d", "#fff8d8", "theme_meander.svg"), } 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"), + "none": ("", palette["chrome"], ""), + "chinese_knot": ("#6e171a", "#26191c", "theme_chinese_knot.svg"), + "cloud": ("#16384d", "#122330", "theme_cloud.svg"), + "ruyi": ("#1c4229", "#17251b", "theme_ruyi.svg"), + "brush": ("#3a3d45", "#1e2026", "theme_brush.svg"), + "peony": ("#552333", "#2a1a22", "theme_peony.svg"), + "bamboo": ("#254018", "#1a2616", "theme_bamboo.svg"), + "meander": ("#574913", "#282416", "theme_meander.svg"), } 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"]) + self._enforce_theme_background_rule() + header_background, themed_panel, pattern_file = 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"] @@ -713,18 +929,28 @@ class MainWindow(QMainWindow): focus = palette["focus"] tab_bg = palette["tab_bg"] tab_active = palette["surface"] + branch_closed_icon = self._stylesheet_url(self.resources_dir / "tree_closed.svg") + branch_open_icon = self._stylesheet_url(self.resources_dir / "tree_open.svg") + pattern_style = "" + chrome_pattern_style = "" + if pattern_file: + pattern_url = self._stylesheet_url(self.resources_dir / pattern_file) + pattern_style = f'background-image: url("{pattern_url}"); background-repeat: repeat;' + chrome_pattern_style = f'background-image: url("{pattern_url}"); background-repeat: repeat;' self.setStyleSheet( f""" QMainWindow {{ - background: {panel_bg}; + background-color: {panel_bg}; + {pattern_style} }} QMenuBar, QToolBar, QStatusBar {{ color: {text}; - background: {chrome_bg}; + background-color: {chrome_bg}; + {chrome_pattern_style} border: 0; }} @@ -837,7 +1063,8 @@ class MainWindow(QMainWindow): QWidget#navigationPanel, QWidget#tocPanel {{ - background: {panel_bg}; + background-color: {panel_bg}; + {pattern_style} border: 0; }} @@ -906,6 +1133,16 @@ class MainWindow(QMainWindow): background: transparent; }} + QTreeWidget#navigationTree::branch:closed:has-children, + QTreeWidget#tocTree::branch:closed:has-children {{ + image: url("{branch_closed_icon}"); + }} + + QTreeWidget#navigationTree::branch:open:has-children, + QTreeWidget#tocTree::branch:open:has-children {{ + image: url("{branch_open_icon}"); + }} + QSplitter#mainSplitter::handle {{ background: {splitter}; }} @@ -915,7 +1152,12 @@ class MainWindow(QMainWindow): }} """ ) - self._apply_window_title_bar_style(palette["chrome"], text) + self._apply_window_title_bar_style(chrome_bg, text) + self._apply_window_icon_style(chrome_bg, text) + if hasattr(self, "tree"): + self._refresh_tree_item_visuals() + if hasattr(self, "tabs"): + self._refresh_welcome_tab() def _apply_window_title_bar_style(self, background: str, foreground: str) -> None: if os.name != "nt": @@ -940,8 +1182,55 @@ class MainWindow(QMainWindow): except (AttributeError, OSError, ValueError): return + def _apply_window_icon_style(self, background: str, foreground: str) -> None: + if not self.base_window_icon_path.exists(): + return + source = QPixmap(str(self.base_window_icon_path)) + if source.isNull(): + return + + pixmap = QPixmap(64, 64) + pixmap.fill(Qt.GlobalColor.transparent) + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + fill = QColor(background) + painter.setBrush(fill) + painter.setPen(QPen(QColor(foreground).lighter(120), 2)) + painter.drawRoundedRect(4, 4, 56, 56, 12, 12) + painter.drawPixmap(10, 10, source.scaled(44, 44, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) + painter.end() + + icon = QIcon(pixmap) + self.setWindowIcon(icon) + app = QApplication.instance() + if app is not None: + app.setWindowIcon(icon) + def _on_tab_changed(self, index: int) -> None: widget = self.tabs.widget(index) + if widget is None: + return + if bool(widget.property("is_welcome")): + self.current_file = None + self.current_fragment = "" + self.setWindowTitle("MDHelper") + if hasattr(self, "status_label"): + self.status_label.setText("请选择文件夹或文件") + if hasattr(self, "toc_tree"): + self.toc_tree.clear() + self._update_actions() + return + + if isinstance(widget, RichMarkdownEditorDialog): + file_value = widget.property("current_file") or str(widget.save_target_path) + self.current_file = Path(str(file_value)).resolve() + self.current_fragment = "" + self.setWindowTitle(f"{self.current_file.name} - MDHelper") + self.status_label.setText(f"正在编辑:{self._display_path(self.current_file)}") + self._populate_toc_from_text(widget.source_text()) + self._update_actions() + return + if not isinstance(widget, ReaderView): return @@ -962,12 +1251,13 @@ class MainWindow(QMainWindow): self._update_actions() def _close_tab(self, index: int) -> None: - if self.tabs.count() <= 1: - return widget = self.tabs.widget(index) + if isinstance(widget, RichMarkdownEditorDialog) and not widget.confirm_close(): + return self.tabs.removeTab(index) if widget is not None: widget.deleteLater() + self._ensure_welcome_if_empty() def _render_local_file_page(self, path: Path) -> str: title = html.escape(path.name) @@ -1028,32 +1318,201 @@ class MainWindow(QMainWindow): return f"读取失败:{exc}" return path.read_text(encoding="utf-8", errors="replace") + def _tree_is_dark_theme(self) -> bool: + return self.theme == "dark" or self.theme_color in {"black", "dark_gray"} + + def _tree_folder_color(self) -> QColor: + return QColor("#e0a536" if self._tree_is_dark_theme() else "#9a6500") + + def _tree_file_color(self, path: Path) -> QColor: + extension = path.suffix.lower() + if extension in {".md", ".markdown", ".txt", ".rst"}: + color = "#77b7ff" if self._tree_is_dark_theme() else "#2563a8" + elif extension in {".html", ".htm", ".xhtml", ".css", ".js", ".ts", ".json", ".xml", ".yaml", ".yml"}: + color = "#80d6c2" if self._tree_is_dark_theme() else "#047866" + elif extension in {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".svg", ".ico"}: + color = "#d7a9ff" if self._tree_is_dark_theme() else "#7c3aae" + elif extension in {".mp3", ".wav", ".ogg", ".flac", ".m4a"}: + color = "#f7a8bd" if self._tree_is_dark_theme() else "#b8325a" + elif extension in {".mp4", ".webm", ".avi", ".mov", ".mkv"}: + color = "#ffb36b" if self._tree_is_dark_theme() else "#b85600" + elif extension in {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"}: + color = "#f28c8c" if self._tree_is_dark_theme() else "#b3261e" + elif extension in {".py", ".c", ".cpp", ".h", ".hpp", ".java", ".go", ".rs", ".cs"}: + color = "#97d679" if self._tree_is_dark_theme() else "#417b27" + else: + color = "#c7cdd7" if self._tree_is_dark_theme() else "#4b5563" + return QColor(color) + + def _is_supported_document_path(self, path: Path) -> bool: + return path.suffix.lower() in SUPPORTED_DOCUMENT_EXTENSIONS + + def _document_tree_label(self, entry: DocumentEntry) -> str: + if entry.path.suffix.lower() in {".md", ".markdown"} and self.document_tree_label_mode == "title": + return entry.title + return entry.path.name + + def _file_icon_label(self, path: Path) -> str: + extension = path.suffix.lower().lstrip(".") + labels = { + "md": "MD", + "markdown": "MD", + "html": "H", + "htm": "H", + "xhtml": "H", + "css": "C", + "js": "JS", + "ts": "TS", + "json": "{}", + "xml": "<>", + "yaml": "Y", + "yml": "Y", + "png": "I", + "jpg": "I", + "jpeg": "I", + "gif": "I", + "bmp": "I", + "webp": "I", + "svg": "S", + "ico": "I", + "mp3": "A", + "wav": "A", + "ogg": "A", + "flac": "A", + "m4a": "A", + "mp4": "V", + "webm": "V", + "avi": "V", + "mov": "V", + "mkv": "V", + "pdf": "P", + "doc": "W", + "docx": "W", + "xls": "X", + "xlsx": "X", + "ppt": "P", + "pptx": "P", + "py": "PY", + } + return labels.get(extension, extension[:2].upper() if extension else "F") + + def _tree_file_icon(self, path: Path) -> QIcon: + color = self._tree_file_color(path).name() + label = self._file_icon_label(path) + cache_key = (path.suffix.lower(), color) + if cache_key in self.file_tree_icon_cache: + return self.file_tree_icon_cache[cache_key] + + pixmap = QPixmap(18, 18) + pixmap.fill(Qt.GlobalColor.transparent) + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + fill = QColor(color) + painter.setPen(QPen(fill.darker(130), 1)) + painter.setBrush(fill) + painter.drawRoundedRect(3, 2, 12, 14, 2, 2) + painter.setPen(QPen(QColor("#ffffff"), 1)) + font = painter.font() + font.setBold(True) + font.setPointSize(5 if len(label) > 1 else 7) + painter.setFont(font) + painter.drawText(pixmap.rect().adjusted(1, 1, -1, -1), Qt.AlignmentFlag.AlignCenter, label) + painter.end() + + icon = QIcon(pixmap) + self.file_tree_icon_cache[cache_key] = icon + return icon + + def _tree_folder_icon(self) -> QIcon: + color = self._tree_folder_color().name() + if color in self.folder_tree_icon_cache: + return self.folder_tree_icon_cache[color] + + pixmap = QPixmap(18, 18) + pixmap.fill(Qt.GlobalColor.transparent) + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + fill = QColor(color) + painter.setPen(QPen(fill.darker(125), 1)) + painter.setBrush(fill.lighter(116)) + painter.drawRoundedRect(2, 5, 14, 10, 2, 2) + painter.setBrush(fill.lighter(128)) + painter.drawRoundedRect(3, 3, 7, 4, 1, 1) + painter.end() + + icon = QIcon(pixmap) + self.folder_tree_icon_cache[color] = icon + return icon + + def _style_folder_tree_item(self, item: QTreeWidgetItem) -> None: + item.setIcon(0, self._tree_folder_icon()) + item.setForeground(0, QBrush(self._tree_folder_color())) + + def _style_file_tree_item(self, item: QTreeWidgetItem, path: Path) -> None: + item.setIcon(0, self._tree_file_icon(path)) + item.setForeground(0, QBrush(self._tree_file_color(path))) + + def _refresh_tree_item_visuals(self) -> None: + def refresh_item(item: QTreeWidgetItem) -> None: + data = item.data(0, Qt.ItemDataRole.UserRole) + if data: + self._style_file_tree_item(item, Path(data)) + else: + self._style_folder_tree_item(item) + for child_index in range(item.childCount()): + refresh_item(item.child(child_index)) + + for index in range(self.tree.topLevelItemCount()): + refresh_item(self.tree.topLevelItem(index)) + + def _find_or_create_folder_item(self, parent_item: QTreeWidgetItem, name: str) -> QTreeWidgetItem: + for child_index in range(parent_item.childCount()): + child = parent_item.child(child_index) + if child.data(0, Qt.ItemDataRole.UserRole) is None and child.text(0) == name: + return child + + folder_item = QTreeWidgetItem([name]) + folder_item.setData(0, Qt.ItemDataRole.UserRole, None) + self._style_folder_tree_item(folder_item) + parent_item.addChild(folder_item) + return folder_item + + def _sort_tree_children(self, item: QTreeWidgetItem) -> None: + children = item.takeChildren() + for child in children: + self._sort_tree_children(child) + children.sort(key=lambda child: (bool(child.data(0, Qt.ItemDataRole.UserRole)), child.text(0).casefold())) + item.addChildren(children) + def _populate_tree(self) -> None: self.tree.clear() self.path_to_item.clear() - root_item = QTreeWidgetItem(["MDHelper"]) + root_label = self.project_root.name if self.has_project else "未选择文件夹" + root_item = QTreeWidgetItem([root_label or str(self.project_root)]) root_item.setData(0, Qt.ItemDataRole.UserRole, None) + root_item.setToolTip(0, str(self.project_root) if self.has_project else "请从“文件”菜单选择文件夹或文件") + self._style_folder_tree_item(root_item) self.tree.addTopLevelItem(root_item) - docs_item = QTreeWidgetItem(["docs"]) - docs_item.setData(0, Qt.ItemDataRole.UserRole, None) + if not self.has_project: + root_item.setExpanded(True) + return for entry in self.entries: - label = f"{entry.title} ({entry.relative_path})" + label = self._document_tree_label(entry) item = QTreeWidgetItem([label]) item.setToolTip(0, entry.relative_path) item.setData(0, Qt.ItemDataRole.UserRole, str(entry.path)) + self._style_file_tree_item(item, entry.path) self.path_to_item[entry.path] = item - if entry.relative_path.startswith("docs/"): - docs_item.addChild(item) - else: - root_item.addChild(item) + parent_item = root_item + for part in entry.relative_path.split("/")[:-1]: + parent_item = self._find_or_create_folder_item(parent_item, part) + parent_item.addChild(item) - if docs_item.childCount(): - root_item.addChild(docs_item) - - self.tree.expandAll() + self._sort_tree_children(root_item) + root_item.setExpanded(True) def open_document_from_link(self, path: Path, fragment: str = "") -> None: if not path.exists(): @@ -1061,16 +1520,278 @@ class MainWindow(QMainWindow): return self.open_document(path, fragment=fragment) + def prompt_open_project(self) -> None: + message = QMessageBox(self) + message.setIcon(QMessageBox.Icon.Information) + message.setWindowTitle("选择文档位置") + message.setText("请选择要阅读的帮助文档文件夹或 Markdown 文件。") + folder_button = message.addButton("选择文件夹", QMessageBox.ButtonRole.AcceptRole) + file_button = message.addButton("选择文件", QMessageBox.ButtonRole.ActionRole) + message.addButton("稍后选择", QMessageBox.ButtonRole.RejectRole) + message.exec() + + if message.clickedButton() == folder_button: + self.open_project_folder() + elif message.clickedButton() == file_button: + self.open_markdown_file() + + def open_project_folder(self) -> None: + start_dir = str(self.project_root if self.has_project else Path.home()) + folder = QFileDialog.getExistingDirectory(self, "打开文件夹", start_dir) + if not folder: + return + self.set_project_root(Path(folder), save=True) + self.status_label.setText(f"已打开文件夹:{self.project_root}") + def open_markdown_file(self) -> None: file_name, _ = QFileDialog.getOpenFileName( self, - "打开 Markdown 文件", - str(self.project_root), - "Markdown Files (*.md *.markdown);;All Files (*)", + "打开文件", + str(self.project_root if self.has_project else Path.home()), + "Supported Files (*.md *.markdown *.html *.htm *.xhtml);;All Files (*)", ) if file_name: - self._ensure_document_entry(Path(file_name).resolve()) - self.open_document(Path(file_name)) + path = Path(file_name).resolve() + self.set_project_root(path.parent, save=True) + if path.suffix.lower() in {".md", ".markdown"}: + self._ensure_document_entry(path) + self.open_document(path) + elif path.suffix.lower() in {".html", ".htm", ".xhtml"}: + self._ensure_document_entry(path) + self._open_webpage_file_now(path) + else: + self._open_local_file_now(path) + + def set_project_root(self, project_root: Path, save: bool = True) -> None: + project_root = project_root.resolve() + self.project_root = project_root + self.has_project = True + self.renderer = MarkdownRenderer(self.project_root) + self.entries = discover_documents(self.project_root) + self.search_index.rebuild(self.entries) + self.path_to_item.clear() + self._populate_tree() + self._filter_tree(self.search_box.text()) + self._update_watched_paths() + if save: + self.settings.setValue(LAST_PROJECT_ROOT_SETTING_KEY, str(self.project_root)) + + def edit_current_markdown(self) -> None: + path = self.current_file + if path is None or path.suffix.lower() not in {".md", ".markdown"}: + QMessageBox.information(self, "无法编辑", "当前标签页不是 Markdown 文档。") + return + + if not path.exists(): + QMessageBox.warning(self, "文件不存在", f"无法编辑:\n{path}") + return + + try: + source = self._read_markdown_source(path) + except UnicodeDecodeError as exc: + LOGGER.exception("Failed to decode Markdown source: %s", path) + QMessageBox.warning(self, "读取失败", f"无法按 UTF-8 读取文档:\n{path}\n\n{exc}") + return + except OSError as exc: + LOGGER.exception("Failed to read Markdown source: %s", path) + QMessageBox.warning(self, "读取失败", f"无法读取文档:\n{path}\n\n{exc}") + return + + disk_source = source + source = self._source_with_recovered_draft(path, source) + editor = RichMarkdownEditorDialog( + path=path, + source=source, + renderer=self.renderer, + 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, + original_source=disk_source, + file_signature=self._file_signature(path), + draft_callback=lambda draft_source, file_path=path: self._save_editor_draft(file_path, draft_source), + embedded=True, + parent=self, + ) + editor.setProperty("current_file", str(path)) + editor.setProperty("original_path", str(path)) + editor.editor.textChanged.connect(lambda widget=editor: self._on_editor_content_changed(widget)) + editor.save_requested.connect(lambda target, text, signature, widget=editor: self._save_editor_tab(widget, Path(target), text, signature)) + editor.close_requested.connect(lambda widget=editor: self._close_editor_tab(widget)) + editor.title_changed.connect(lambda title, widget=editor: self._update_tab_title(widget, title)) + current_index = self.tabs.currentIndex() + current_widget = self.tabs.currentWidget() + if isinstance(current_widget, ReaderView): + self.tabs.removeTab(current_index) + current_widget.deleteLater() + index = self.tabs.insertTab(current_index, editor, editor.windowTitle()) + else: + index = self.tabs.addTab(editor, editor.windowTitle()) + self.tabs.setCurrentIndex(index) + self.current_file = path + self.current_fragment = "" + self._populate_toc_from_text(editor.source_text()) + self.status_label.setText(f"正在编辑:{self._display_path(path)}") + + def _on_editor_content_changed(self, editor: RichMarkdownEditorDialog) -> None: + if self.tabs.currentWidget() is editor: + self._populate_toc_from_text(editor.source_text()) + + def _save_editor_tab( + self, + editor: RichMarkdownEditorDialog, + target_path: Path, + source: str, + expected_signature: tuple[int, int] | None, + ) -> None: + original_path_value = editor.property("original_path") + original_path = Path(str(original_path_value)).resolve() if original_path_value else editor.path.resolve() + target_path = target_path.resolve() + if target_path == original_path and source == self._read_markdown_source(original_path): + self._clear_editor_draft(original_path) + editor.mark_saved(target_path, source, self._file_signature(target_path)) + self.status_label.setText("编辑内容未变化") + return + + ok = self.save_markdown_source( + target_path, + source, + expected_signature=expected_signature if target_path == original_path else None, + original_path=original_path, + reload_current=False, + ) + if not ok: + return + + editor.setProperty("current_file", str(target_path)) + editor.setProperty("original_path", str(target_path)) + editor.mark_saved(target_path, source, self._file_signature(target_path)) + self._update_tab_title(editor, editor.windowTitle()) + self.current_file = target_path + if self.tabs.currentWidget() is editor: + self._populate_toc_from_text(editor.source_text()) + self.status_label.setText(f"已保存:{self._display_path(target_path)}") + + def _close_editor_tab(self, editor: RichMarkdownEditorDialog) -> None: + index = self.tabs.indexOf(editor) + if index >= 0: + self._close_tab(index) + + def _read_markdown_source(self, path: Path) -> str: + return path.read_text(encoding="utf-8") + + def _source_with_recovered_draft(self, path: Path, source: str) -> str: + draft = self.editor_drafts.get(str(path.resolve())) + draft_source = draft.get("source") if isinstance(draft, dict) else None + if not isinstance(draft_source, str) or draft_source == source: + return source + saved_at = str(draft.get("saved_at", "未知时间")) if isinstance(draft, dict) else "未知时间" + file_size = str(draft.get("file_size", "未知")) if isinstance(draft, dict) else "未知" + + choice = QMessageBox.question( + self, + "恢复草稿?", + f"检测到 {path.name} 有未保存草稿。\n\n草稿时间:{saved_at}\n文件大小:{file_size} 字节\n\n是否恢复草稿内容?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.Yes, + ) + if choice == QMessageBox.StandardButton.Yes: + return draft_source + + self._clear_editor_draft(path) + return source + + def _file_signature(self, path: Path) -> tuple[int, int] | None: + try: + stat = path.stat() + except OSError: + return None + return stat.st_mtime_ns, stat.st_size + + def _save_editor_draft(self, path: Path, source: str) -> None: + path = path.resolve() + try: + current_source = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + current_source = "" + + if source == current_source: + self._clear_editor_draft(path) + return + + signature = self._file_signature(path) + self.editor_drafts[str(path)] = { + "source": source, + "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"), + "file_mtime_ns": signature[0] if signature else 0, + "file_size": signature[1] if signature else 0, + } + self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, ensure_ascii=False)) + LOGGER.info("Markdown draft saved: %s", path) + + def _clear_editor_draft(self, path: Path) -> None: + self.editor_drafts.pop(str(path.resolve()), None) + self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, ensure_ascii=False)) + + def save_markdown_source( + self, + path: Path, + source: str, + expected_signature: tuple[int, int] | None = None, + original_path: Path | None = None, + reload_current: bool = True, + ) -> bool: + path = path.resolve() + if path.suffix.lower() not in {".md", ".markdown"}: + QMessageBox.warning(self, "保存失败", "只能保存 Markdown 文档。") + return False + + if expected_signature is not None and path.exists() and self._file_signature(path) != expected_signature: + choice = QMessageBox.warning( + self, + "文件已被外部修改", + f"保存前检测到磁盘文件已变化。\n\n继续保存会覆盖外部修改:\n{path}", + QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Cancel, + QMessageBox.StandardButton.Cancel, + ) + if choice != QMessageBox.StandardButton.Save: + self.status_label.setText("已取消保存,磁盘文件存在外部修改") + return False + + self.internal_save_paths.add(path) + try: + path.write_text(source, encoding="utf-8", newline="") + except OSError as exc: + self.internal_save_paths.discard(path) + LOGGER.exception("Failed to save Markdown source: %s", path) + QMessageBox.warning(self, "保存失败", f"无法写入文档:\n{path}\n\n{exc}") + return False + + LOGGER.info("Markdown source saved: %s", path) + self._clear_editor_draft(original_path or path) + if original_path is not None and original_path.resolve() != path: + self._clear_editor_draft(path) + self._refresh_after_markdown_save(path, reload_current=reload_current) + QTimer.singleShot(1000, lambda saved_path=path: self.internal_save_paths.discard(saved_path)) + self.status_label.setText(f"已保存:{self._display_path(path)}") + return True + + def _refresh_after_markdown_save(self, path: Path, reload_current: bool = True) -> None: + previous_current = self.current_file + previous_fragment = self.current_fragment + self.entries = discover_documents(self.project_root) + if path.exists() and all(entry.path != path for entry in self.entries): + self._ensure_document_entry(path) + else: + self.search_index.rebuild(self.entries) + self._populate_tree() + self._filter_tree(self.search_box.text()) + + if reload_current and previous_current is not None and previous_current == path: + self.open_document(path, fragment=previous_fragment, add_history=False) + else: + self._update_watched_paths() 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)) @@ -1184,16 +1905,21 @@ class MainWindow(QMainWindow): LOGGER.info("User canceled selecting application for: %s", path) return + self._open_with_application(path, program) + + def _open_with_application(self, path: Path, program: str) -> bool: 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}", - ) + return True + + QMessageBox.warning( + self, + "打开失败", + f"无法启动所选程序:\n{program}\n\n要打开的文件:\n{path}", + ) + return False def _open_with_saved_application(self, path: Path) -> bool: extension = path.suffix.lower() @@ -1235,6 +1961,73 @@ class MainWindow(QMainWindow): self.external_applications.pop(extension.lower(), None) self._save_preferences() + def manage_external_applications(self) -> None: + if not self.external_applications: + QMessageBox.information(self, "管理外部打开程序", "尚未记住任何文件类型的打开程序。") + return + + dialog = QDialog(self) + dialog.setWindowTitle("管理外部打开程序") + dialog.setMinimumSize(680, 360) + + layout = QVBoxLayout(dialog) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(10) + + app_tree = QTreeWidget() + app_tree.setRootIsDecorated(False) + app_tree.setAlternatingRowColors(True) + app_tree.setHeaderLabels(["扩展名", "程序"]) + for extension, program in sorted(self.external_applications.items()): + item = QTreeWidgetItem([extension, program]) + item.setData(0, Qt.ItemDataRole.UserRole, extension) + app_tree.addTopLevelItem(item) + app_tree.resizeColumnToContents(0) + layout.addWidget(app_tree, 1) + + button_layout = QHBoxLayout() + remove_button = QPushButton("删除选中") + clear_button = QPushButton("清空全部") + close_button = QPushButton("关闭") + button_layout.addWidget(remove_button) + button_layout.addWidget(clear_button) + button_layout.addStretch(1) + button_layout.addWidget(close_button) + layout.addLayout(button_layout) + + def remove_selected() -> None: + for item in app_tree.selectedItems(): + extension = str(item.data(0, Qt.ItemDataRole.UserRole)) + self.external_applications.pop(extension, None) + index = app_tree.indexOfTopLevelItem(item) + if index >= 0: + app_tree.takeTopLevelItem(index) + self._save_preferences() + self.status_label.setText("外部打开程序设置已更新") + if app_tree.topLevelItemCount() == 0: + dialog.accept() + + def clear_all() -> None: + answer = QMessageBox.question( + dialog, + "清空全部?", + "确定清空所有已记住的外部打开程序吗?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No, + ) + if answer != QMessageBox.StandardButton.Yes: + return + self.external_applications.clear() + app_tree.clear() + self._save_preferences() + self.status_label.setText("已清空外部打开程序设置") + dialog.accept() + + remove_button.clicked.connect(remove_selected) + clear_button.clicked.connect(clear_all) + close_button.clicked.connect(dialog.accept) + dialog.exec() + 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(): @@ -1330,12 +2123,20 @@ class MainWindow(QMainWindow): ) if not file_name: return - output_path = Path(file_name) + + output_path = self.export_pdf_to_path(Path(file_name)) + if output_path is None: + return + LOGGER.info("Exporting PDF: %s", output_path) + self.status_label.setText(f"正在导出 PDF:{output_path}") + + def export_pdf_to_path(self, output_path: Path) -> Path | None: + if self.current_file is None: + return None 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}") + return output_path def export_current_html(self) -> None: if self.current_file is None: @@ -1444,6 +2245,7 @@ class MainWindow(QMainWindow): self._apply_ui_font() self._update_theme_menu_state() self._apply_navigation_style() + self._populate_tree() self._filter_tree(self.search_box.text()) self.refresh_document() LOGGER.info("Configuration imported: %s", config_path) @@ -1474,10 +2276,12 @@ class MainWindow(QMainWindow): "ui_font_point_size": self.ui_font_point_size, "document_font_family": self.document_font_family, "document_font_size": self.document_font_size, + "document_tree_label_mode": self.document_tree_label_mode, "math_engine": self.math_engine, "auto_refresh": self.auto_refresh_enabled, "non_preview_action": self.non_preview_action, }, + "project_root": str(self.project_root) if self.has_project else "", "recent_files": [str(path) for path in self.recent_files], "bookmarks": self.bookmarks, "scroll_positions": self.scroll_positions, @@ -1488,26 +2292,15 @@ class MainWindow(QMainWindow): 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"}: + if theme_color in THEME_COLOR_VALUES: 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 + self.theme_background = self._normalized_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" + self._set_theme_color("black" if theme == "dark" else "white") math_engine = str(reader.get("math_engine", self.math_engine)) if math_engine in {"katex", "mathjax"}: @@ -1530,6 +2323,9 @@ class MainWindow(QMainWindow): except (TypeError, ValueError): pass self.document_font_family = str(reader.get("document_font_family", self.document_font_family)).strip() + tree_label_mode = str(reader.get("document_tree_label_mode", self.document_tree_label_mode)) + if tree_label_mode in {"title", "filename"}: + self.document_tree_label_mode = tree_label_mode 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)) @@ -1560,6 +2356,10 @@ class MainWindow(QMainWindow): if str(extension).startswith(".") and str(program) } + project_root = payload.get("project_root", "") + if isinstance(project_root, str) and project_root and Path(project_root).exists(): + self.set_project_root(Path(project_root), save=True) + def _is_int_like(self, value: object) -> bool: try: int(value) @@ -1576,6 +2376,8 @@ class MainWindow(QMainWindow): new_tab: bool = False, ) -> None: path = path.resolve() + if not self.has_project or not self._is_relative_to(path, self.project_root): + self.set_project_root(path.parent, save=True) self._save_current_scroll_position() try: html = self.renderer.render_file( @@ -1619,11 +2421,33 @@ class MainWindow(QMainWindow): LOGGER.info("Opened document: %s", path) def open_home(self) -> None: + if not self.has_project: + self.prompt_open_project() + return home = self.project_root / "sample.md" if home.exists(): self.open_document(home) + def _is_relative_to(self, path: Path, parent: Path) -> bool: + try: + path.resolve().relative_to(parent.resolve()) + except ValueError: + return False + return True + def refresh_document(self) -> None: + current = self.tabs.currentWidget() + if isinstance(current, RichMarkdownEditorDialog): + current.update_rendering_options( + 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, + ) + self.status_label.setText(f"编辑器显示已更新:{self._display_path(current.save_target_path)}") + return + if self.current_file is not None: if self.current_file.suffix.lower() in {".html", ".htm", ".xhtml"}: self.open_webpage_file(self.current_file) @@ -1689,7 +2513,7 @@ class MainWindow(QMainWindow): self.refresh_document() def set_theme_color_from_action(self, action: QAction) -> None: - self._set_theme_color(str(action.data() or "white")) + self._set_theme_color(str(action.data() or "colorful")) self._update_theme_menu_state() self._apply_navigation_style() self._save_preferences() @@ -1697,16 +2521,8 @@ class MainWindow(QMainWindow): 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 = self._normalized_theme_background(background) + if not self._theme_background_enabled(): background = "none" self.theme_background = background self._update_theme_menu_state() @@ -1738,6 +2554,29 @@ class MainWindow(QMainWindow): self._save_preferences() self.refresh_document() + def set_document_font_from_toolbar(self, font: QFont) -> None: + family = font.family().strip() + if not family or family == self.document_font_family: + return + self.document_font_family = family + self._update_theme_menu_state() + self._save_preferences() + self.refresh_document() + + def set_document_font_size_from_toolbar(self, text: str) -> None: + try: + size = int(text.strip()) + except (TypeError, ValueError): + return + size = max(12, min(size, 28)) + if size == self.document_font_size: + 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_document_font_size_from_action(self, action: QAction) -> None: try: size = int(action.data()) @@ -1800,7 +2639,7 @@ class MainWindow(QMainWindow): ) 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.theme_background = self._normalized_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 @@ -1902,27 +2741,90 @@ class MainWindow(QMainWindow): 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 not isinstance(current, ReaderView): + self.status_label.setText("当前标签页不是阅读页,无法按目录跳转") + return + + self.web_view = current + self.current_fragment = fragment + 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(" + "(() => {" + "const rawId = " f"{json.dumps(fragment)}" - ");" - "const target = document.getElementById(id);" - "if (target) { target.scrollIntoView({block: 'start'}); }" + ";" + "let id = rawId;" + "try { id = decodeURIComponent(rawId); } catch (error) {}" + "let attempts = 0;" + "const scrollToHeading = () => {" + " attempts += 1;" + " const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';" + " const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);" + " if (target) {" + " target.scrollIntoView({block: 'start', behavior: 'auto'});" + " const scroller = document.scrollingElement || document.documentElement || document.body;" + " scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);" + " if (window.history && window.history.replaceState) {" + " window.history.replaceState(null, '', `#${encodeURIComponent(id)}`);" + " }" + " window.dispatchEvent(new Event('scroll'));" + " return true;" + " }" + " if (attempts < 30) { window.setTimeout(scrollToHeading, 50); }" + " return false;" + "};" + "return scrollToHeading();" + "})();" ) - self.web_view.page().runJavaScript(script) + self.web_view.page().runJavaScript(script, self._on_anchor_scroll_result) + + def _on_anchor_scroll_result(self, ok: object) -> None: + if ok is False and self.current_fragment: + self.status_label.setText(f"未找到标题:#{self.current_fragment}") def _open_tree_item(self, item: QTreeWidgetItem) -> None: data = item.data(0, Qt.ItemDataRole.UserRole) if data: - self.open_document(Path(data)) + self.open_local_file(Path(data)) + + def _show_tree_context_menu(self, position: QPoint) -> None: + menu = QMenu(self) + label_group = QActionGroup(menu) + label_group.setExclusive(True) + + title_action = QAction("Markdown 显示文档标题", menu) + title_action.setCheckable(True) + title_action.setChecked(self.document_tree_label_mode == "title") + title_action.triggered.connect(lambda: self.set_document_tree_label_mode("title")) + label_group.addAction(title_action) + menu.addAction(title_action) + + filename_action = QAction("Markdown 显示文件名", menu) + filename_action.setCheckable(True) + filename_action.setChecked(self.document_tree_label_mode == "filename") + filename_action.triggered.connect(lambda: self.set_document_tree_label_mode("filename")) + label_group.addAction(filename_action) + menu.addAction(filename_action) + + menu.exec(self.tree.viewport().mapToGlobal(position)) + + def set_document_tree_label_mode(self, mode: str) -> None: + if mode not in {"title", "filename"} or mode == self.document_tree_label_mode: + return + self.document_tree_label_mode = mode + current_file = self.current_file + self._populate_tree() + self._filter_tree(self.search_box.text()) + if current_file is not None: + self._select_tree_item(current_file) + self._save_preferences() + label = "文档标题" if mode == "title" else "文件名" + self.status_label.setText(f"Markdown 文件树显示:{label}") def _filter_tree(self, query: str) -> None: visible_paths = {entry.path for entry in self.entries if self.search_index.matches_entry(entry, query)} @@ -1939,7 +2841,7 @@ class MainWindow(QMainWindow): 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) + item.setHidden(False if not query.strip() and item.parent() is None else not any_visible) return any_visible for index in range(self.tree.topLevelItemCount()): @@ -1968,6 +2870,10 @@ class MainWindow(QMainWindow): item = self.path_to_item.get(path) if item is None: return + parent = item.parent() + while parent is not None: + parent.setExpanded(True) + parent = parent.parent() self.tree.setCurrentItem(item) self.tree.scrollToItem(item) @@ -2001,6 +2907,9 @@ class MainWindow(QMainWindow): history = self._current_history() self.back_action.setEnabled(history.can_go_back) self.forward_action.setEnabled(history.can_go_forward) + if hasattr(self, "edit_current_action"): + can_edit = self.current_file is not None and self.current_file.suffix.lower() in {".md", ".markdown"} + self.edit_current_action.setEnabled(can_edit) def _tab_history(self, web_view: QWebEngineView) -> NavigationHistory: history = getattr(web_view, "navigation_history", None) @@ -2035,10 +2944,16 @@ class MainWindow(QMainWindow): history.replace_current(HistoryItem(path=item.path, fragment=item.fragment, scroll_y=max(0, scroll_y))) def _populate_toc(self, path: Path) -> None: + self._populate_toc_items(extract_headings(path)) + + def _populate_toc_from_text(self, source: str) -> None: + self._populate_toc_items(extract_headings_from_text(source)) + + def _populate_toc_items(self, headings: list[Heading]) -> None: self.toc_tree.clear() stack: list[tuple[int, QTreeWidgetItem]] = [] - for heading in extract_headings(path): + for heading in headings: item = QTreeWidgetItem([heading.title]) item.setData(0, Qt.ItemDataRole.UserRole, heading.slug) item.setToolTip(0, f"#{heading.slug}") @@ -2069,7 +2984,20 @@ class MainWindow(QMainWindow): def _open_toc_item(self, item: QTreeWidgetItem) -> None: slug = item.data(0, Qt.ItemDataRole.UserRole) if slug: + current = self.tabs.currentWidget() + if isinstance(current, RichMarkdownEditorDialog): + if current.scroll_to_heading(str(slug)): + self.current_fragment = str(slug) + current.setProperty("current_fragment", str(slug)) + self.status_label.setText(f"定位到源码:{item.text(0)}") + else: + self.status_label.setText(f"未找到标题:{item.text(0)}") + return + if isinstance(current, ReaderView): + self.current_fragment = str(slug) + current.setProperty("current_fragment", str(slug)) self.scroll_to_anchor(str(slug)) + self.status_label.setText(f"跳转到:{item.text(0)}") def _open_search_result(self, item: QTreeWidgetItem) -> None: data = item.data(0, Qt.ItemDataRole.UserRole) @@ -2083,6 +3011,8 @@ class MainWindow(QMainWindow): self.open_document(Path(data)) def _ensure_document_entry(self, path: Path) -> None: + if not self._is_supported_document_path(path): + return if any(entry.path == path for entry in self.entries): return @@ -2169,22 +3099,11 @@ class MainWindow(QMainWindow): 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_color = str(self.settings.value("reader/theme_color", "colorful")) + if self.theme_color not in THEME_COLOR_VALUES: + self.theme_color = "colorful" 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.theme_background = self._normalized_theme_background(str(self.settings.value("reader/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" @@ -2201,6 +3120,9 @@ class MainWindow(QMainWindow): except (TypeError, ValueError): self.ui_font_point_size = 0 self.document_font_family = str(self.settings.value("reader/document_font_family", "")).strip() + self.document_tree_label_mode = str(self.settings.value("tree/markdown_label_mode", "title")) + if self.document_tree_label_mode not in {"title", "filename"}: + self.document_tree_label_mode = "title" 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"}: @@ -2214,6 +3136,7 @@ class MainWindow(QMainWindow): 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, {}) + editor_drafts = self._load_json_setting(EDITOR_DRAFTS_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): @@ -2222,6 +3145,12 @@ class MainWindow(QMainWindow): for extension, program in external_applications.items() if str(extension).startswith(".") and str(program) } + if isinstance(editor_drafts, dict): + self.editor_drafts = { + str(path): draft + for path, draft in editor_drafts.items() + if isinstance(draft, dict) and isinstance(draft.get("source"), str) + } def _save_preferences(self) -> None: self.settings.setValue("reader/theme", self.theme) @@ -2233,8 +3162,11 @@ class MainWindow(QMainWindow): 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("tree/markdown_label_mode", self.document_tree_label_mode) self.settings.setValue("reader/auto_refresh", self.auto_refresh_enabled) self.settings.setValue("reader/non_preview_action", self.non_preview_action) + if self.has_project: + self.settings.setValue(LAST_PROJECT_ROOT_SETTING_KEY, str(self.project_root)) 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)) @@ -2242,18 +3174,22 @@ class MainWindow(QMainWindow): EXTERNAL_APPLICATIONS_SETTING_KEY, json.dumps(self.external_applications, ensure_ascii=False), ) + self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, 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: + def _restore_window_state(self) -> bool: + restored = False geometry = self.settings.value("window/geometry") if geometry is not None: self.restoreGeometry(geometry) + restored = True splitter_state = self.settings.value("window/splitter") if splitter_state is not None: self.splitter.restoreState(splitter_state) + return restored def _load_json_setting(self, key: str, fallback: object) -> object: value = self.settings.value(key, "") @@ -2267,6 +3203,8 @@ class MainWindow(QMainWindow): def _save_current_scroll_position(self) -> None: if self.current_file is None: return + if not isinstance(self.tabs.currentWidget(), ReaderView): + return path_key = str(self.current_file) def store_scroll(scroll_y: object) -> None: @@ -2279,7 +3217,7 @@ class MainWindow(QMainWindow): 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'}});" + script = f"(() => {{ window.scrollTo({{top: {max(0, scroll_y)}, behavior: 'instant'}}); }})();" self.web_view.page().runJavaScript(script) def _update_watched_paths(self) -> None: @@ -2290,6 +3228,9 @@ class MainWindow(QMainWindow): if watched_dirs: self.file_watcher.removePaths(watched_dirs) + if not self.has_project: + return + paths: set[Path] = set() directories: set[Path] = {self.project_root} @@ -2337,6 +3278,10 @@ class MainWindow(QMainWindow): if not self.auto_refresh_enabled: return changed = Path(changed_path).resolve() + if changed in self.internal_save_paths: + self.internal_save_paths.discard(changed) + self._update_watched_paths() + return 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): @@ -2344,7 +3289,7 @@ class MainWindow(QMainWindow): self._update_watched_paths() def _on_watched_directory_changed(self, changed_path: str) -> None: - if not self.auto_refresh_enabled: + if not self.auto_refresh_enabled or not self.has_project: return changed = Path(changed_path).resolve() docs_dir = (self.project_root / "docs").resolve() @@ -2361,6 +3306,8 @@ class MainWindow(QMainWindow): self.refresh_document() def _refresh_document_entries(self) -> None: + if not self.has_project: + return previous_current = self.current_file self.entries = discover_documents(self.project_root) self.search_index.rebuild(self.entries) @@ -2383,3 +3330,4 @@ class MainWindow(QMainWindow): def showEvent(self, event: QShowEvent) -> None: super().showEvent(event) QTimer.singleShot(0, self._apply_navigation_style) + diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py new file mode 100644 index 0000000..6cdf74f --- /dev/null +++ b/mdhelper/markdown_editor.py @@ -0,0 +1,810 @@ +from __future__ import annotations + +import os +import json +import re +from pathlib import Path +from typing import Callable + +from PySide6.QtCore import QRect, QSize, QTimer, QUrl, Qt, Signal +from PySide6.QtGui import ( + QAction, + QColor, + QFont, + QKeySequence, + QPainter, + QSyntaxHighlighter, + QTextCharFormat, + QTextCursor, + QTextDocument, + QTextFormat, +) +from PySide6.QtWebEngineCore import QWebEngineSettings +from PySide6.QtWebEngineWidgets import QWebEngineView +from PySide6.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QFileDialog, + QHBoxLayout, + QLabel, + QLineEdit, + QMenu, + QMessageBox, + QPlainTextEdit, + QPushButton, + QSplitter, + QTextEdit, + QToolBar, + QVBoxLayout, + QWidget, +) +from shiboken6 import isValid + +from .markdown_renderer import MarkdownRenderer +from .markdown_utils import slugify_heading + + +class LineNumberArea(QWidget): + def __init__(self, editor: "MarkdownSourceEditor") -> None: + super().__init__(editor) + self.editor = editor + + def sizeHint(self) -> QSize: + return QSize(self.editor.line_number_area_width(), 0) + + def paintEvent(self, event: object) -> None: + self.editor.line_number_area_paint_event(event) + + +class MarkdownSourceEditor(QPlainTextEdit): + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.line_number_background = QColor("#f3f5f8") + self.line_number_foreground = QColor("#7a8494") + self.current_line_background = QColor("#edf4ff") + self.line_number_area = LineNumberArea(self) + self.blockCountChanged.connect(self.update_line_number_area_width) + self.updateRequest.connect(self.update_line_number_area) + self.cursorPositionChanged.connect(self.highlight_current_line) + self.update_line_number_area_width(0) + self.highlight_current_line() + + def apply_theme(self, dark: bool) -> None: + if dark: + self.line_number_background = QColor("#22272e") + self.line_number_foreground = QColor("#8b949e") + self.current_line_background = QColor("#273447") + self.setStyleSheet( + "QPlainTextEdit { background: #1f242b; color: #dbe2ea; " + "selection-background-color: #2f6feb; selection-color: #ffffff; }" + ) + else: + self.line_number_background = QColor("#f3f5f8") + self.line_number_foreground = QColor("#7a8494") + self.current_line_background = QColor("#edf4ff") + self.setStyleSheet("") + self.line_number_area.update() + self.highlight_current_line() + + def line_number_area_width(self) -> int: + digits = max(2, len(str(max(1, self.blockCount())))) + return 12 + self.fontMetrics().horizontalAdvance("9") * digits + + def update_line_number_area_width(self, new_block_count: int) -> None: + del new_block_count + self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) + + def update_line_number_area(self, rect: QRect, dy: int) -> None: + if dy: + self.line_number_area.scroll(0, dy) + else: + self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) + + if rect.contains(self.viewport().rect()): + self.update_line_number_area_width(0) + + def resizeEvent(self, event: object) -> None: + super().resizeEvent(event) + content_rect = self.contentsRect() + self.line_number_area.setGeometry( + QRect(content_rect.left(), content_rect.top(), self.line_number_area_width(), content_rect.height()) + ) + + def line_number_area_paint_event(self, event: object) -> None: + painter = QPainter(self.line_number_area) + painter.fillRect(event.rect(), self.line_number_background) + + block = self.firstVisibleBlock() + block_number = block.blockNumber() + top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) + bottom = top + int(self.blockBoundingRect(block).height()) + + while block.isValid() and top <= event.rect().bottom(): + if block.isVisible() and bottom >= event.rect().top(): + painter.setPen(self.line_number_foreground) + painter.drawText( + 0, + top, + self.line_number_area.width() - 6, + self.fontMetrics().height(), + Qt.AlignmentFlag.AlignRight, + str(block_number + 1), + ) + + block = block.next() + top = bottom + bottom = top + int(self.blockBoundingRect(block).height()) + block_number += 1 + + def highlight_current_line(self) -> None: + selection = QTextEdit.ExtraSelection() + selection.format.setBackground(self.current_line_background) + selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True) + selection.cursor = self.textCursor() + selection.cursor.clearSelection() + self.setExtraSelections([selection]) + + +class MarkdownSyntaxHighlighter(QSyntaxHighlighter): + def __init__(self, document: object, dark: bool = False) -> None: + super().__init__(document) + self.dark = dark + self._rebuild_rules() + + def apply_theme(self, dark: bool) -> None: + self.dark = dark + self._rebuild_rules() + self.rehighlight() + + def _rebuild_rules(self) -> None: + if self.dark: + heading = "#79c0ff" + link = "#58a6ff" + strong = "#f0f6fc" + accent = "#d2a8ff" + code = "#ffa657" + media = "#7ee787" + quote = "#8b949e" + fence = "#ffab70" + block_code = "#c9d1d9" + else: + heading = "#1f6feb" + link = "#0969da" + strong = "#24292f" + accent = "#8250df" + code = "#bf3989" + media = "#1a7f37" + quote = "#6e7781" + fence = "#953800" + block_code = "#57606a" + + self.rules = [ + (re.compile(r"^#{1,6}\s+.+$"), self._format(heading, bold=True)), + (re.compile(r"^\s*[-*+]\s+"), self._format(link)), + (re.compile(r"^\s*\d+\.\s+"), self._format(link)), + (re.compile(r"\*\*[^*]+\*\*"), self._format(strong, bold=True)), + (re.compile(r"(?\s?.*$"), self._format(quote, italic=True)), + (re.compile(r"^\s{0,3}---+\s*$"), self._format(quote)), + ] + self.code_format = self._format(block_code) + self.fence_format = self._format(fence, bold=True) + + def _format(self, color: str, bold: bool = False, italic: bool = False, underline: bool = False) -> QTextCharFormat: + text_format = QTextCharFormat() + text_format.setForeground(QColor(color)) + if bold: + text_format.setFontWeight(QFont.Weight.Bold) + if italic: + text_format.setFontItalic(True) + if underline: + text_format.setFontUnderline(True) + return text_format + + def highlightBlock(self, text: str) -> None: + in_fence = self.previousBlockState() == 1 + if text.strip().startswith("```"): + self.setFormat(0, len(text), self.fence_format) + self.setCurrentBlockState(0 if in_fence else 1) + return + + if in_fence: + self.setFormat(0, len(text), self.code_format) + self.setCurrentBlockState(1) + return + + self.setCurrentBlockState(0) + for pattern, text_format in self.rules: + for match in pattern.finditer(text): + self.setFormat(match.start(), match.end() - match.start(), text_format) + + +class MarkdownEditorDialog(QDialog): + save_requested = Signal(object, str, object) + close_requested = Signal() + title_changed = Signal(str) + + def __init__( + self, + path: Path, + source: str, + renderer: MarkdownRenderer, + theme: str, + font_scale: float, + document_font_family: str, + document_font_size: int, + math_engine: str, + original_source: str | None = None, + file_signature: tuple[int, int] | None = None, + draft_callback: Callable[[str], None] | None = None, + embedded: bool = False, + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.embedded = embedded + if embedded: + self.setWindowFlag(Qt.WindowType.Widget, True) + self.path = path + self.save_target_path = path + self.renderer = renderer + self.theme = theme + self.font_scale = font_scale + self.document_font_family = document_font_family + self.document_font_size = document_font_size + self.math_engine = math_engine + self.file_signature = file_signature + self.draft_callback = draft_callback + self._preview_dirty = True + self._preview_scroll_y = 0 + self._preview_scroll_ratio = 0.0 + self._syncing_scroll = False + self._match_positions: list[int] = [] + self._current_match_index = -1 + self.setWindowTitle(f"编辑 Markdown - {path.name}") + self.setMinimumSize(1120, 720) + self._original_source = source if original_source is None else original_source + + layout = QVBoxLayout(self) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(8) + + self.path_label = QLabel(str(path)) + self.path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + if not embedded: + layout.addWidget(self.path_label) + + self.insert_toolbar = QToolBar("插入") + self.insert_toolbar.setMovable(False) + self._build_insert_toolbar() + layout.addWidget(self.insert_toolbar) + + control_layout = QHBoxLayout() + control_layout.setContentsMargins(0, 0, 0, 0) + control_layout.addWidget(QLabel("视图")) + self.view_mode_box = QComboBox() + self.view_mode_box.addItem("源码", "source") + self.view_mode_box.addItem("预览", "preview") + self.view_mode_box.addItem("分屏", "split") + self.view_mode_box.setCurrentIndex(2 if embedded else 0) + self.view_mode_box.currentIndexChanged.connect(self._apply_view_mode) + control_layout.addWidget(self.view_mode_box) + + self.editor_find_box = QLineEdit() + self.editor_find_box.setPlaceholderText("查找源码") + self.editor_find_box.returnPressed.connect(self.find_next_in_editor) + self.editor_find_box.textChanged.connect(self._rebuild_find_matches) + self.editor_replace_box = QLineEdit() + self.editor_replace_box.setPlaceholderText("替换为") + self.match_case_checkbox = QCheckBox("区分大小写") + self.match_case_checkbox.toggled.connect(self._rebuild_find_matches) + self.whole_word_checkbox = QCheckBox("全词") + self.whole_word_checkbox.toggled.connect(self._rebuild_find_matches) + self.editor_find_previous_button = QPushButton("上一个") + self.editor_find_previous_button.clicked.connect(self.find_previous_in_editor) + self.editor_find_next_button = QPushButton("下一个") + self.editor_find_next_button.clicked.connect(self.find_next_in_editor) + self.editor_replace_button = QPushButton("替换") + self.editor_replace_button.clicked.connect(self.replace_current_in_editor) + self.editor_replace_all_button = QPushButton("全部替换") + self.editor_replace_all_button.clicked.connect(self.replace_all_in_editor) + self.find_status_label = QLabel("0/0") + control_layout.addWidget(self.editor_find_box, 2) + control_layout.addWidget(self.editor_replace_box, 2) + control_layout.addWidget(self.match_case_checkbox) + control_layout.addWidget(self.whole_word_checkbox) + control_layout.addWidget(self.editor_find_previous_button) + control_layout.addWidget(self.editor_find_next_button) + control_layout.addWidget(self.editor_replace_button) + control_layout.addWidget(self.editor_replace_all_button) + control_layout.addWidget(self.find_status_label) + layout.addLayout(control_layout) + + self.preview_refresh_timer = QTimer(self) + self.preview_refresh_timer.setSingleShot(True) + self.preview_refresh_timer.setInterval(350) + self.preview_refresh_timer.timeout.connect(self._refresh_preview_with_scroll_capture) + self.draft_save_timer = QTimer(self) + self.draft_save_timer.setSingleShot(True) + self.draft_save_timer.setInterval(5000) + self.draft_save_timer.timeout.connect(self._auto_save_draft) + + self.splitter = QSplitter(Qt.Orientation.Horizontal) + self.editor = MarkdownSourceEditor() + self.editor.setPlainText(source) + self.editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth) + editor_font = QFont("Consolas") + editor_font.setStyleHint(QFont.StyleHint.Monospace) + self.editor.setFont(editor_font) + self._apply_editor_font() + self.highlighter = MarkdownSyntaxHighlighter(self.editor.document()) + self.editor.textChanged.connect(self._on_editor_text_changed) + self.editor.verticalScrollBar().valueChanged.connect(self._sync_preview_to_editor_scroll) + self.splitter.addWidget(self.editor) + + self.preview = QWebEngineView() + self.preview.loadFinished.connect(self._restore_preview_scroll) + self._configure_preview_settings(self.preview.settings()) + self.splitter.addWidget(self.preview) + self.splitter.setSizes([560, 560]) + layout.addWidget(self.splitter, 1) + + button_layout = QHBoxLayout() + button_layout.addStretch(1) + + self.redo_button = QPushButton("前进") + self.redo_button.setShortcut(QKeySequence.StandardKey.Redo) + self.redo_button.clicked.connect(self._redo_editor) + button_layout.addWidget(self.redo_button) + + self.undo_button = QPushButton("回退") + self.undo_button.setShortcut(QKeySequence.StandardKey.Undo) + self.undo_button.clicked.connect(self._undo_editor) + button_layout.addWidget(self.undo_button) + + self.save_button = QPushButton("保存") + self.save_button.setShortcut("Ctrl+S") + if embedded: + self.save_button.clicked.connect(self._emit_save_requested) + else: + self.save_button.clicked.connect(self.accept) + button_layout.addWidget(self.save_button) + + self.save_as_button = QPushButton("另存为") + self.save_as_button.clicked.connect(self._choose_save_as_path) + button_layout.addWidget(self.save_as_button) + + self.cancel_button = QPushButton("取消") + if embedded: + self.cancel_button.clicked.connect(self.close_requested.emit) + else: + self.cancel_button.clicked.connect(self.reject) + button_layout.addWidget(self.cancel_button) + + layout.addLayout(button_layout) + + self._install_shortcuts() + self.apply_theme(theme == "dark") + self._update_undo_redo_actions() + self._update_dirty_title() + self._rebuild_find_matches() + self._apply_view_mode() + + def source_text(self) -> str: + return self.editor.toPlainText() + + def has_unsaved_changes(self) -> bool: + return self.source_text() != self._original_source + + def apply_theme(self, dark: bool) -> None: + self.editor.apply_theme(dark) + self.highlighter.apply_theme(dark) + if dark: + self.setStyleSheet( + "QDialog { background: #1f242b; color: #dbe2ea; }" + "QLineEdit, QComboBox { background: #15191f; color: #dbe2ea; border: 1px solid #3a4553; padding: 4px; }" + "QToolBar { background: #22272e; border: 1px solid #3a4553; }" + "QPushButton { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; padding: 4px 8px; }" + ) + else: + self.setStyleSheet("") + + def _apply_editor_font(self) -> None: + font = self.editor.font() + font.setStyleHint(QFont.StyleHint.Monospace) + font.setPointSize(max(8, min(22, round(self.document_font_size * 0.75)))) + self.editor.setFont(font) + self.editor.update_line_number_area_width(0) + + def update_rendering_options( + self, + theme: str, + font_scale: float, + document_font_family: str, + document_font_size: int, + math_engine: str, + ) -> None: + self.theme = theme + self.font_scale = font_scale + self.document_font_family = document_font_family + self.document_font_size = document_font_size + self.math_engine = math_engine + self.apply_theme(theme == "dark") + self._apply_editor_font() + self._preview_dirty = True + if self.preview.isVisible(): + self._refresh_preview_with_scroll_capture() + + def _install_shortcuts(self) -> None: + find_action = QAction(self) + find_action.setShortcut(QKeySequence.StandardKey.Find) + find_action.triggered.connect(self.editor_find_box.setFocus) + self.addAction(find_action) + + replace_action = QAction(self) + replace_action.setShortcut(QKeySequence("Ctrl+H")) + replace_action.triggered.connect(self.editor_replace_box.setFocus) + self.addAction(replace_action) + + self.editor.undoAvailable.connect(lambda available: self.undo_button.setEnabled(available)) + self.editor.redoAvailable.connect(lambda available: self.redo_button.setEnabled(available)) + + def _build_insert_toolbar(self) -> None: + for label, template in ( + ("H1", "# {selection}"), + ("H2", "## {selection}"), + ("B", "**{selection}**"), + ("I", "*{selection}*"), + ("代码", "```\n{selection}\n```"), + ("表格", "| 列1 | 列2 |\n| --- | --- |\n| 内容 | 内容 |"), + ("链接", "[{selection}](target.md)"), + ("图片", "![{selection}](media/screenshot.png)"), + ("提示", "> [!NOTE]\n> {selection}"), + ("Mermaid", "```mermaid\ngraph TD\n A --> B\n```"), + ("公式", "$${selection}$$"), + ): + action = QAction(label, self) + action.setToolTip(label) + action.triggered.connect(lambda checked=False, item=template: self.insert_template(item)) + self.insert_toolbar.addAction(action) + + def insert_template(self, template: str) -> None: + cursor = self.editor.textCursor() + selection = cursor.selectedText().replace("\u2029", "\n") + replacement = template.format(selection=selection or "内容") + cursor.insertText(replacement) + self.editor.setTextCursor(cursor) + self.editor.setFocus() + + def scroll_to_heading(self, slug: str) -> bool: + target_line = self._heading_line_for_slug(slug) + if target_line is None: + return False + + block = self.editor.document().findBlockByNumber(target_line) + if not block.isValid(): + return False + + cursor = QTextCursor(block) + self.editor.setTextCursor(cursor) + self.editor.centerCursor() + self.editor.setFocus() + if self.preview.isVisible(): + self._scroll_preview_to_heading(slug) + return True + + def _heading_line_for_slug(self, target_slug: str) -> int | None: + seen: dict[str, int] = {} + in_fenced_block = False + + for line_number, line in enumerate(self.source_text().splitlines()): + stripped = line.strip() + if stripped.startswith("```") or stripped.startswith("~~~"): + in_fenced_block = not in_fenced_block + continue + if in_fenced_block: + continue + + match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped) + if not match: + continue + + slug = slugify_heading(match.group(2).strip()) + if not slug: + continue + count = seen.get(slug, 0) + seen[slug] = count + 1 + if count: + slug = f"{slug}-{count + 1}" + if slug == target_slug: + return line_number + + return None + + def _scroll_preview_to_heading(self, slug: str) -> None: + if not isValid(self) or not isValid(self.preview): + return + script = ( + "(() => {" + "const id = " + f"{json.dumps(slug)}" + ";" + "const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';" + "const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);" + "if (target) {" + " target.scrollIntoView({block: 'start', behavior: 'auto'});" + " const scroller = document.scrollingElement || document.documentElement || document.body;" + " scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);" + "}" + "})();" + ) + self.preview.page().runJavaScript(script) + + def _on_editor_text_changed(self) -> None: + self._schedule_preview_refresh() + if self.has_unsaved_changes(): + self.draft_save_timer.start() + self._update_dirty_title() + self._rebuild_find_matches() + self._update_undo_redo_actions() + + def _update_undo_redo_actions(self) -> None: + self.undo_button.setEnabled(self.editor.document().isUndoAvailable()) + self.redo_button.setEnabled(self.editor.document().isRedoAvailable()) + + def _undo_editor(self) -> None: + self.editor.undo() + self._update_undo_redo_actions() + + def _redo_editor(self) -> None: + self.editor.redo() + self._update_undo_redo_actions() + + def _update_dirty_title(self) -> None: + marker = "*" if self.has_unsaved_changes() else "" + title = f"{marker}编辑 Markdown - {self.save_target_path.name}" + self.setWindowTitle(title) + self.title_changed.emit(title) + self.path_label.setText(str(self.save_target_path)) + + def _auto_save_draft(self) -> None: + if self.has_unsaved_changes() and callable(self.draft_callback): + self.draft_callback(self.source_text()) + + def _find_flags(self) -> QTextDocument.FindFlag: + flags = QTextDocument.FindFlag(0) + if self.match_case_checkbox.isChecked(): + flags |= QTextDocument.FindFlag.FindCaseSensitively + if self.whole_word_checkbox.isChecked(): + flags |= QTextDocument.FindFlag.FindWholeWords + return flags + + def _rebuild_find_matches(self) -> None: + query = self.editor_find_box.text() + self._match_positions = [] + self._current_match_index = -1 + if not query: + self.find_status_label.setText("0/0") + return + + text = self.source_text() + flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE + pattern = re.escape(query) + if self.whole_word_checkbox.isChecked(): + pattern = r"\b" + pattern + r"\b" + self._match_positions = [match.start() for match in re.finditer(pattern, text, flags)] + cursor_pos = self.editor.textCursor().selectionStart() + for index, position in enumerate(self._match_positions): + if position >= cursor_pos: + self._current_match_index = index - 1 + break + else: + self._current_match_index = len(self._match_positions) - 1 + self._update_find_status() + + def _select_match(self, index: int) -> None: + if not self._match_positions: + self._update_find_status() + return + self._current_match_index = index % len(self._match_positions) + query = self.editor_find_box.text() + cursor = self.editor.textCursor() + cursor.setPosition(self._match_positions[self._current_match_index]) + cursor.setPosition(cursor.position() + len(query), QTextCursor.MoveMode.KeepAnchor) + self.editor.setTextCursor(cursor) + self.editor.ensureCursorVisible() + self._update_find_status() + + def _update_find_status(self) -> None: + total = len(self._match_positions) + current = self._current_match_index + 1 if total and self._current_match_index >= 0 else 0 + self.find_status_label.setText(f"{current}/{total}") + + def find_next_in_editor(self) -> None: + if not self.editor_find_box.text(): + return + if not self._match_positions: + self._rebuild_find_matches() + if self._match_positions: + self._select_match(self._current_match_index + 1) + + def find_previous_in_editor(self) -> None: + if not self.editor_find_box.text(): + return + if not self._match_positions: + self._rebuild_find_matches() + if self._match_positions: + self._select_match(self._current_match_index - 1) + + def replace_current_in_editor(self) -> None: + query = self.editor_find_box.text() + if not query: + return + + cursor = self.editor.textCursor() + selected = cursor.selectedText().replace("\u2029", "\n") + matches = selected == query if self.match_case_checkbox.isChecked() else selected.lower() == query.lower() + if cursor.hasSelection() and matches: + cursor.insertText(self.editor_replace_box.text()) + self._rebuild_find_matches() + return + self.find_next_in_editor() + + def replace_all_in_editor(self) -> None: + query = self.editor_find_box.text() + if not query: + return + + replacement = self.editor_replace_box.text() + flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE + pattern = re.escape(query) + if self.whole_word_checkbox.isChecked(): + pattern = r"\b" + pattern + r"\b" + self.editor.setPlainText(re.sub(pattern, replacement, self.source_text(), flags=flags)) + self._rebuild_find_matches() + + def _configure_preview_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 _apply_view_mode(self) -> None: + mode = str(self.view_mode_box.currentData() or "source") + self.editor.setVisible(mode in {"source", "split"}) + self.preview.setVisible(mode in {"preview", "split"}) + if mode in {"preview", "split"} and self._preview_dirty: + self._refresh_preview_now() + if mode == "split": + QTimer.singleShot(0, lambda: self._sync_preview_to_editor_scroll(self.editor.verticalScrollBar().value())) + + def _schedule_preview_refresh(self) -> None: + self._preview_dirty = True + mode = str(self.view_mode_box.currentData() or "source") + if mode in {"preview", "split"}: + self.preview_refresh_timer.start() + + def _refresh_preview_with_scroll_capture(self) -> None: + mode = str(self.view_mode_box.currentData() or "source") + if mode == "split": + self._preview_scroll_ratio = self._editor_scroll_ratio() + self._refresh_preview_now() + return + self.preview.page().runJavaScript("Math.max(0, window.scrollY || 0)", self._store_scroll_and_refresh_preview) + + def _store_scroll_and_refresh_preview(self, scroll_y: object) -> None: + if not isValid(self) or not isValid(self.preview): + return + try: + self._preview_scroll_y = max(0, int(float(scroll_y or 0))) + except (TypeError, ValueError): + self._preview_scroll_y = 0 + self._refresh_preview_now() + + def _refresh_preview_now(self) -> None: + if not isValid(self) or not isValid(self.preview): + return + html_content = self.renderer.render_source( + self.source_text(), + self.save_target_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, + ) + base_path = str(self.save_target_path.parent.resolve()) + os.sep + self.preview.setHtml(html_content, QUrl.fromLocalFile(base_path)) + self._preview_dirty = False + + def _restore_preview_scroll(self, ok: bool) -> None: + if not ok: + return + if str(self.view_mode_box.currentData() or "source") == "split": + self._scroll_preview_to_ratio(self._preview_scroll_ratio) + return + if self._preview_scroll_y > 0: + script = f"(() => {{ window.scrollTo({{top: {self._preview_scroll_y}, behavior: 'instant'}}); }})();" + self.preview.page().runJavaScript(script) + + def _editor_scroll_ratio(self) -> float: + maximum = max(1, self.editor.verticalScrollBar().maximum()) + return max(0.0, min(1.0, self.editor.verticalScrollBar().value() / maximum)) + + def _sync_preview_to_editor_scroll(self, value: int) -> None: + del value + if self._syncing_scroll or str(self.view_mode_box.currentData() or "source") != "split": + return + self._preview_scroll_ratio = self._editor_scroll_ratio() + self._scroll_preview_to_ratio(self._preview_scroll_ratio) + + def _scroll_preview_to_ratio(self, ratio: float) -> None: + if not isValid(self) or not isValid(self.preview): + return + script = ( + "(() => {" + "const ratio = %0.6f;" + "const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);" + "window.scrollTo({top: Math.round(maxY * ratio), behavior: 'instant'});" + "})();" + % ratio + ) + self._syncing_scroll = True + self.preview.page().runJavaScript(script, lambda result=None: self._clear_scroll_sync()) + + def _clear_scroll_sync(self) -> None: + self._syncing_scroll = False + + def _choose_save_as_path(self) -> None: + file_name, _ = QFileDialog.getSaveFileName( + self, + "另存为 Markdown", + str(self.save_target_path), + "Markdown Files (*.md *.markdown);;All Files (*)", + ) + if not file_name: + return + target = Path(file_name) + if target.suffix.lower() not in {".md", ".markdown"}: + target = target.with_suffix(".md") + self.save_target_path = target.resolve() + self._update_dirty_title() + if self.embedded: + self._emit_save_requested() + else: + self.accept() + + def accept(self) -> None: + super().accept() + + def _emit_save_requested(self) -> None: + self.save_requested.emit(self.save_target_path, self.source_text(), self.file_signature) + + def mark_saved(self, path: Path, source: str, file_signature: tuple[int, int] | None) -> None: + self.path = path + self.save_target_path = path + self.file_signature = file_signature + self._original_source = source + self._update_dirty_title() + + def confirm_close(self) -> bool: + if not self.has_unsaved_changes(): + return True + choice = QMessageBox.question( + self, + "关闭编辑标签?", + "当前编辑内容尚未保存,确定要关闭此编辑标签吗?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No, + ) + return choice == QMessageBox.StandardButton.Yes + + def reject(self) -> None: + if not self.confirm_close(): + return + super().reject() diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index 0a3cb5a..3c0d841 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -60,6 +60,27 @@ class MarkdownRenderer: math_engine=math_engine, ) + def render_source( + self, + source: str, + markdown_path: Path, + theme: str = "light", + font_scale: float = 1.0, + document_font_family: str = "", + document_font_size: int | None = None, + math_engine: str = "katex", + ) -> str: + body = self.markdown.render(source, {"path": str(markdown_path)}) + return self._wrap_html( + body=body, + title=markdown_path.name, + theme=theme, + font_scale=font_scale, + document_font_family=document_font_family, + document_font_size=document_font_size, + math_engine=math_engine, + ) + def wrap_body_for_display( self, body: str, diff --git a/mdhelper/resources/theme_bamboo.svg b/mdhelper/resources/theme_bamboo.svg new file mode 100644 index 0000000..acbb216 --- /dev/null +++ b/mdhelper/resources/theme_bamboo.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/mdhelper/resources/theme_brush.svg b/mdhelper/resources/theme_brush.svg new file mode 100644 index 0000000..cbe03d8 --- /dev/null +++ b/mdhelper/resources/theme_brush.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/mdhelper/resources/theme_chinese_knot.svg b/mdhelper/resources/theme_chinese_knot.svg new file mode 100644 index 0000000..ee5b30a --- /dev/null +++ b/mdhelper/resources/theme_chinese_knot.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/mdhelper/resources/theme_cloud.svg b/mdhelper/resources/theme_cloud.svg new file mode 100644 index 0000000..e707821 --- /dev/null +++ b/mdhelper/resources/theme_cloud.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/mdhelper/resources/theme_meander.svg b/mdhelper/resources/theme_meander.svg new file mode 100644 index 0000000..2ffcb68 --- /dev/null +++ b/mdhelper/resources/theme_meander.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/mdhelper/resources/theme_peony.svg b/mdhelper/resources/theme_peony.svg new file mode 100644 index 0000000..bb7f682 --- /dev/null +++ b/mdhelper/resources/theme_peony.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/mdhelper/resources/theme_ruyi.svg b/mdhelper/resources/theme_ruyi.svg new file mode 100644 index 0000000..964beb1 --- /dev/null +++ b/mdhelper/resources/theme_ruyi.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/mdhelper/resources/tree_closed.svg b/mdhelper/resources/tree_closed.svg new file mode 100644 index 0000000..6591109 --- /dev/null +++ b/mdhelper/resources/tree_closed.svg @@ -0,0 +1,3 @@ + + + diff --git a/mdhelper/resources/tree_open.svg b/mdhelper/resources/tree_open.svg new file mode 100644 index 0000000..3faad4a --- /dev/null +++ b/mdhelper/resources/tree_open.svg @@ -0,0 +1,3 @@ + + + diff --git a/mdhelper/search.py b/mdhelper/search.py index ec033ac..0e58b87 100644 --- a/mdhelper/search.py +++ b/mdhelper/search.py @@ -96,9 +96,11 @@ def search_entries(entries: list[DocumentEntry], query: str, limit: int = 80) -> def _read_text(entry: DocumentEntry) -> str: + if entry.path.suffix.lower() not in {".md", ".markdown", ".txt", ".html", ".htm", ".css", ".js", ".json", ".yaml", ".yml"}: + return "" try: return entry.path.read_text(encoding="utf-8") - except OSError: + except (OSError, UnicodeDecodeError): return "" diff --git a/mdhelper/settings_dialog.py b/mdhelper/settings_dialog.py index e65485a..c5ad296 100644 --- a/mdhelper/settings_dialog.py +++ b/mdhelper/settings_dialog.py @@ -30,24 +30,26 @@ class SettingsDialog(QDialog): self.setMinimumWidth(420) self.theme_color_combo = QComboBox() + self.theme_color_combo.addItem("彩色", "colorful") self.theme_color_combo.addItem("白色", "white") self.theme_color_combo.addItem("黑色", "black") self.theme_color_combo.addItem("深灰色", "dark_gray") - self.theme_color_combo.addItem("彩色", "colorful") self.theme_color_combo.setCurrentIndex(max(0, self.theme_color_combo.findData(preferences.theme_color))) + self.theme_color_combo.currentIndexChanged.connect(self._update_background_availability) self.theme_background_combo = QComboBox() self.theme_background_combo.addItem("无", "none") - self.theme_background_combo.addItem("春天", "spring") - self.theme_background_combo.addItem("稻草", "straw") - self.theme_background_combo.addItem("电路", "circuit") - self.theme_background_combo.addItem("年轮", "tree_rings") - self.theme_background_combo.addItem("几何图形", "geometry") - self.theme_background_combo.addItem("书法", "calligraphy") - self.theme_background_combo.addItem("水下", "underwater") + self.theme_background_combo.addItem("中国结", "chinese_knot") + self.theme_background_combo.addItem("祥云", "cloud") + self.theme_background_combo.addItem("如意", "ruyi") + self.theme_background_combo.addItem("毛笔", "brush") + self.theme_background_combo.addItem("牡丹", "peony") + self.theme_background_combo.addItem("竹", "bamboo") + self.theme_background_combo.addItem("回纹", "meander") self.theme_background_combo.setCurrentIndex( max(0, self.theme_background_combo.findData(preferences.theme_background)) ) + self._update_background_availability() self.font_scale_spin = QDoubleSpinBox() self.font_scale_spin.setRange(0.8, 1.6) @@ -81,11 +83,20 @@ class SettingsDialog(QDialog): def preferences(self) -> AppPreferences: theme_color = str(self.theme_color_combo.currentData()) + theme_background = str(self.theme_background_combo.currentData()) + if theme_color != "colorful": + theme_background = "none" return AppPreferences( theme="dark" if theme_color in {"black", "dark_gray"} else "light", theme_color=theme_color, - theme_background=str(self.theme_background_combo.currentData()), + theme_background=theme_background, font_scale=float(self.font_scale_spin.value()), auto_refresh=self.auto_refresh_checkbox.isChecked(), non_preview_action=str(self.non_preview_combo.currentData()), ) + + def _update_background_availability(self) -> None: + enabled = str(self.theme_color_combo.currentData()) == "colorful" + self.theme_background_combo.setEnabled(enabled) + if not enabled: + self.theme_background_combo.setCurrentIndex(max(0, self.theme_background_combo.findData("none"))) diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py index d2d3be4..40303a9 100644 --- a/tests/gui_smoke.py +++ b/tests/gui_smoke.py @@ -12,10 +12,12 @@ os.environ.setdefault("QTWEBENGINE_DISABLE_SANDBOX", "1") PROJECT_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(PROJECT_ROOT)) -from PySide6.QtCore import QTimer, QUrl -from PySide6.QtWidgets import QApplication +from PySide6.QtCore import QEventLoop, QTimer, QUrl, Qt +from PySide6.QtGui import QTextCursor +from PySide6.QtWidgets import QApplication, QMessageBox from mdhelper.main_window import MainWindow, ReaderView +from mdhelper.markdown_editor import MarkdownEditorDialog def main() -> int: @@ -27,12 +29,105 @@ def main() -> int: checks: list[str] = [] def verify() -> None: + empty_window = MainWindow(project_root=None, app_root=project_root) + if empty_window.has_project or empty_window.entries: + checks.append("empty_start_project") + if empty_window.tabs.count() != 1 or not bool(empty_window.tabs.currentWidget().property("is_welcome")): + checks.append("welcome_empty_start") + if empty_window.tree.topLevelItem(0).text(0) != "未选择文件夹": + checks.append("empty_start_tree") + empty_window.set_project_root(project_root, save=False) + if not empty_window.has_project or empty_window.project_root != project_root.resolve() or not empty_window.entries: + checks.append("set_project_root") + supported_suffixes = {".md", ".markdown", ".html", ".htm", ".xhtml"} + if any(entry.path.suffix.lower() not in supported_suffixes for entry in empty_window.entries): + checks.append("project_supported_files_only") + if not any(entry.path == (project_root / "sample.md").resolve() for entry in empty_window.entries): + checks.append("project_markdown_files") + if any(entry.path == (project_root / "requirements.txt").resolve() for entry in empty_window.entries): + checks.append("project_hidden_unsupported_files") + tree_root = empty_window.tree.topLevelItem(0) + if tree_root is None or not tree_root.isExpanded(): + checks.append("file_tree_root_expanded") + if tree_root is None or tree_root.icon(0).isNull(): + checks.append("file_tree_root_icon") + folder_item = None + file_item = None + if tree_root is not None: + pending = [tree_root.child(index) for index in range(tree_root.childCount())] + while pending: + candidate = pending.pop(0) + data = candidate.data(0, Qt.ItemDataRole.UserRole) + if data and file_item is None: + file_item = candidate + elif not data: + if folder_item is None and candidate.childCount() > 0: + folder_item = candidate + pending.extend(candidate.child(index) for index in range(candidate.childCount())) + if folder_item is None: + checks.append("file_tree_folder_item") + else: + if folder_item.isExpanded(): + checks.append("file_tree_subfolder_collapsed") + if folder_item.icon(0).isNull(): + checks.append("file_tree_folder_icon") + if file_item is None: + checks.append("file_tree_file_item") + elif file_item.icon(0).isNull(): + checks.append("file_tree_file_icon") + if folder_item is not None and file_item is not None: + folder_color = folder_item.foreground(0).color().name() + file_color = file_item.foreground(0).color().name() + if folder_color == file_color: + checks.append("file_tree_item_colors") + if tree_root is not None: + root_children = [tree_root.child(index) for index in range(tree_root.childCount())] + root_sort_keys = [ + (bool(child.data(0, Qt.ItemDataRole.UserRole)), child.text(0).casefold()) + for child in root_children + ] + if root_sort_keys != sorted(root_sort_keys): + checks.append("file_tree_folder_first_sorted") + empty_window.set_document_tree_label_mode("filename") + sample_item = empty_window.path_to_item.get((project_root / "sample.md").resolve()) + if sample_item is None or sample_item.text(0) != "sample.md": + checks.append("tree_label_filename_mode") + empty_window.set_document_tree_label_mode("title") + sample_item = empty_window.path_to_item.get((project_root / "sample.md").resolve()) + if sample_item is None or sample_item.text(0) == "sample.md": + checks.append("tree_label_title_mode") + empty_window._set_theme_color("black") + empty_window._apply_navigation_style() + theme_loop = QEventLoop() + QTimer.singleShot(500, theme_loop.quit) + theme_loop.exec() + welcome_view = empty_window.tabs.currentWidget() + if welcome_view is not None and bool(welcome_view.property("is_welcome")): + result: dict[str, str] = {} + + def store_theme(value: object) -> None: + result["theme"] = str(value) + theme_loop.quit() + + welcome_view.page().runJavaScript("document.documentElement.dataset.theme", store_theme) + QTimer.singleShot(1000, theme_loop.quit) + theme_loop.exec() + if result.get("theme") != "dark": + checks.append("welcome_theme_refresh") + empty_window.close() + window.find_box.setText("斐波那契") window.find_next() if window.current_file != (project_root / "sample.md").resolve(): checks.append("current_file") if window.tabs.count() < 1: checks.append("tabs") + if window._welcome_tab_index() >= 0: + checks.append("welcome_closed_for_document") + if window.windowIcon().isNull(): + checks.append("window_icon") + if app.windowIcon().isNull(): + checks.append("app_icon") if not isinstance(window.tabs.currentWidget(), ReaderView): checks.append("reader_view") if not window.export_pdf_action.isEnabled(): @@ -41,8 +136,92 @@ def main() -> int: checks.append("export_html_action") if hasattr(window, "theme_action"): checks.append("theme_toolbar_action") + if hasattr(window, "home_action"): + checks.append("home_toolbar_action") + if window.back_action.icon().isNull() or window.forward_action.icon().isNull(): + checks.append("navigation_toolbar_icons") + if window.open_action.icon().isNull() or window.refresh_action.icon().isNull(): + checks.append("file_toolbar_icons") + if not hasattr(window, "document_font_box") or not hasattr(window, "document_font_size_box"): + checks.append("toolbar_font_controls") + else: + previous_size = window.document_font_size + window.set_document_font_size_from_toolbar("18") + if window.document_font_size != 18: + checks.append("toolbar_font_size") + window.set_document_font_size_from_toolbar(str(previous_size)) if not hasattr(window, "theme_menu"): checks.append("theme_menu") + background_values = { + str(action.data()) + for action in window.theme_background_group.actions() + if action.data() is not None + } + expected_background_values = { + "none", + "chinese_knot", + "cloud", + "ruyi", + "brush", + "peony", + "bamboo", + "meander", + } + if background_values != expected_background_values: + checks.append("theme_background_options") + if window._normalized_theme_background("circuit") != "none": + checks.append("legacy_theme_background_migration") + window.theme_background = "peony" + window._set_theme_color("black") + window._update_theme_menu_state() + if window.theme_background != "none": + checks.append("background_requires_colorful") + peony_action = next((action for action in window.theme_background_group.actions() if action.data() == "peony"), None) + if peony_action is None or peony_action.isEnabled(): + checks.append("background_disabled_for_non_colorful") + window._set_theme_color("colorful") + window.set_theme_background_from_action(peony_action) + if window.theme_background != "peony": + checks.append("background_enabled_for_colorful") + if not hasattr(window, "manage_external_apps_action"): + checks.append("manage_external_apps_action") + if not window.edit_current_action.isEnabled(): + checks.append("edit_current_action") + toc_items = window.toc_tree.findItems("*", Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive) + toc_item = next((item for item in toc_items if item.data(0, Qt.ItemDataRole.UserRole)), None) + if toc_item is None: + checks.append("toc_items") + else: + target_slug = str(toc_item.data(0, Qt.ItemDataRole.UserRole)) + window._open_toc_item(toc_item) + if window.current_fragment != target_slug: + checks.append("toc_click_fragment") + second_toc_item = next( + (item for item in toc_items if item is not toc_item and item.data(0, Qt.ItemDataRole.UserRole)), + None, + ) + if second_toc_item is not None: + second_slug = str(second_toc_item.data(0, Qt.ItemDataRole.UserRole)) + window._open_toc_item(second_toc_item) + toc_loop = QEventLoop() + QTimer.singleShot(250, toc_loop.quit) + toc_loop.exec() + if window.current_fragment != second_slug: + checks.append("toc_second_click_fragment") + result: dict[str, float] = {} + + def store_scroll(value: object) -> None: + try: + result["scroll_y"] = float(value or 0) + except (TypeError, ValueError): + result["scroll_y"] = -1 + toc_loop.quit() + + window.web_view.page().runJavaScript("Math.max(0, window.scrollY || document.documentElement.scrollTop || 0)", store_scroll) + QTimer.singleShot(1000, toc_loop.quit) + toc_loop.exec() + if result.get("scroll_y", -1) < 0: + checks.append("toc_second_click_scroll") if window.search_index.search("斐波那契") == []: checks.append("search_index") if not window._is_current_page_anchor_url(QUrl("#2-表格示例")): @@ -53,6 +232,257 @@ def main() -> int: checks.append("base_anchor_url") if window._is_current_page_anchor_url(QUrl("mailto:user@example.com#message")): checks.append("external_fragment_url") + context_events: list[tuple[str, bool]] = [] + try: + window.web_view.open_link_requested.disconnect(window.open_link_url) + except RuntimeError: + pass + try: + window.web_view.open_link_requested.connect(lambda url, new_tab: context_events.append((url.toString(), new_tab))) + manual_context_url = QUrl.fromLocalFile(str((project_root / "docs" / "user_manual.md").resolve())) + if not window.web_view._handle_link_context_action(manual_context_url, False): + checks.append("context_menu_current_action") + if not window.web_view._handle_link_context_action(manual_context_url, True): + checks.append("context_menu_new_action") + if context_events[-2:] != [(manual_context_url.toString(), False), (manual_context_url.toString(), True)]: + checks.append("context_menu_signals") + finally: + window.web_view.open_link_requested.connect(window.open_link_url) + manual_url = QUrl.fromLocalFile(str((project_root / "docs" / "user_manual.md").resolve())) + window._open_link_url_now(manual_url, False) + if window.current_file != (project_root / "docs" / "user_manual.md").resolve(): + checks.append("local_link_current_tab") + tab_count = window.tabs.count() + window._open_link_url_now(manual_url, True) + if window.tabs.count() != tab_count + 1: + checks.append("local_link_new_tab") + if window.current_file != (project_root / "docs" / "user_manual.md").resolve(): + checks.append("local_link_new_tab_file") + window._close_tab(window.tabs.currentIndex()) + if window.tabs.count() == 1 and bool(window.tabs.currentWidget().property("is_welcome")): + checks.append("welcome_opened_with_other_doc") + window.open_document(project_root / "sample.md", add_history=False) + load_loop = QEventLoop() + window.web_view.loadFinished.connect(load_loop.quit) + QTimer.singleShot(5000, load_loop.quit) + load_loop.exec() + export_test_path = project_root / "__gui_smoke_export.html" + try: + window._write_exported_html(export_test_path, "Smoke") + if not export_test_path.exists() or "Smoke" not in export_test_path.read_text(encoding="utf-8"): + checks.append("export_html_write") + finally: + try: + export_test_path.unlink(missing_ok=True) + except OSError: + pass + pdf_test_path = project_root / "__gui_smoke_export.pdf" + try: + pdf_result: dict[str, object] = {} + + def on_pdf_finished(file_path: str, success: bool) -> None: + pdf_result["path"] = file_path + pdf_result["success"] = success + pdf_loop.quit() + + pdf_loop = QEventLoop() + try: + window.web_view.page().pdfPrintingFinished.disconnect(window._on_pdf_printing_finished) + except RuntimeError: + pass + window.web_view.page().pdfPrintingFinished.connect(on_pdf_finished) + window.export_pdf_to_path(pdf_test_path) + QTimer.singleShot(8000, pdf_loop.quit) + pdf_loop.exec() + window.web_view.page().pdfPrintingFinished.connect(window._on_pdf_printing_finished) + if not pdf_result.get("success") or not pdf_test_path.exists() or pdf_test_path.stat().st_size <= 0: + checks.append("export_pdf_write") + finally: + try: + pdf_test_path.unlink(missing_ok=True) + except OSError: + pass + window._remember_external_application(project_root / "media" / "demo.mp4", str(project_root / "fake_player.exe")) + if ".mp4" not in window.external_applications: + checks.append("external_app_remember") + window._forget_external_application(".mp4") + if ".mp4" in window.external_applications: + checks.append("external_app_forget") + started: list[tuple[str, Path]] = [] + original_start = window._start_external_application + window._start_external_application = lambda program, path: started.append((program, Path(path))) or True + try: + if not window._open_with_application(project_root / "media" / "demo.mp4", str(project_root / "fake_player.exe")): + checks.append("external_app_select") + if not started or started[-1][1] != (project_root / "media" / "demo.mp4").resolve(): + checks.append("external_app_select_target") + finally: + window._start_external_application = original_start + window._forget_external_application(".mp4") + editor_test_path = project_root / "__gui_smoke_editor__.md" + try: + editor_test_path.write_text("# Editor Smoke\n\n初始内容\n", encoding="utf-8") + window.open_document(editor_test_path, add_history=False) + window._save_editor_draft(editor_test_path, "# Draft\n\n草稿内容\n") + if str(editor_test_path.resolve()) not in window.editor_drafts: + checks.append("editor_draft_save") + draft = window.editor_drafts.get(str(editor_test_path.resolve()), {}) + if "saved_at" not in draft or "file_mtime_ns" not in draft or "file_size" not in draft: + checks.append("editor_draft_metadata") + if not window.save_markdown_source(editor_test_path, "# Editor Smoke Saved\n\n编辑保存命中\n"): + checks.append("editor_save") + if str(editor_test_path.resolve()) in window.editor_drafts: + checks.append("editor_draft_clear") + if window._read_markdown_source(editor_test_path) != "# Editor Smoke Saved\n\n编辑保存命中\n": + checks.append("editor_readback") + if window.search_index.search("编辑保存命中") == []: + checks.append("editor_search_index") + save_as_path = project_root / "__gui_smoke_editor_saved_as.md" + if not window.save_markdown_source(save_as_path, "# Saved As\n\n另存为命中\n", original_path=editor_test_path): + checks.append("editor_save_as") + if not save_as_path.exists() or window.search_index.search("另存为命中") == []: + checks.append("editor_save_as_index") + conflict_path = project_root / "__gui_smoke_conflict.md" + conflict_path.write_text("# Conflict\n\nold\n", encoding="utf-8") + signature = window._file_signature(conflict_path) + conflict_path.write_text("# Conflict\n\nexternal\n", encoding="utf-8") + original_warning = QMessageBox.warning + QMessageBox.warning = lambda *args, **kwargs: QMessageBox.StandardButton.Cancel + try: + if window.save_markdown_source(conflict_path, "# Conflict\n\noverwrite\n", expected_signature=signature): + checks.append("editor_conflict_cancel") + if "external" not in conflict_path.read_text(encoding="utf-8"): + checks.append("editor_conflict_preserve") + finally: + QMessageBox.warning = original_warning + dialog = MarkdownEditorDialog( + path=editor_test_path, + source="# Preview Smoke\n\n```mermaid\ngraph TD\n A --> B\n```", + renderer=window.renderer, + theme=window.theme, + font_scale=window.font_scale, + document_font_family=window.document_font_family, + document_font_size=window.document_font_size, + math_engine=window.math_engine, + parent=window, + ) + dialog.view_mode_box.setCurrentIndex(2) + if dialog.editor.isHidden() or dialog.preview.isHidden(): + checks.append("editor_split_mode") + dialog.editor.setPlainText("# Preview Smoke\n\n更新预览") + dialog._refresh_preview_now() + if dialog._preview_dirty: + checks.append("editor_preview_refresh") + dialog.editor.setPlainText("alpha beta alpha") + dialog.editor_find_box.setText("alpha") + dialog.find_next_in_editor() + if dialog.find_status_label.text() != "1/2": + checks.append("editor_find_count") + dialog.editor_replace_box.setText("gamma") + dialog.replace_current_in_editor() + if "gamma" not in dialog.source_text(): + checks.append("editor_replace") + dialog.editor.selectAll() + dialog.insert_template("**{selection}**") + if not dialog.source_text().startswith("**"): + checks.append("editor_insert_template") + dialog.close() + window.open_document(editor_test_path, add_history=False) + editor_tab_count = window.tabs.count() + window.edit_current_markdown() + editor_widget = window.tabs.currentWidget() + if window.tabs.count() != editor_tab_count or not isinstance(editor_widget, MarkdownEditorDialog): + checks.append("editor_tab_open") + else: + if editor_widget.view_mode_box.currentData() != "split": + checks.append("editor_tab_default_split") + if editor_widget.path_label.isVisible(): + checks.append("editor_path_label_visible") + old_editor_point_size = editor_widget.editor.font().pointSize() + window.set_document_font_size_from_toolbar("22") + if editor_widget.document_font_size != 22 or editor_widget.editor.font().pointSize() <= old_editor_point_size: + checks.append("editor_font_size_update") + window.set_document_font_size_from_toolbar("16") + if not hasattr(editor_widget, "undo_button") or not hasattr(editor_widget, "redo_button"): + checks.append("editor_undo_redo_buttons") + button_order = [ + editor_widget.redo_button.text(), + editor_widget.undo_button.text(), + editor_widget.save_button.text(), + editor_widget.save_as_button.text(), + editor_widget.cancel_button.text(), + ] + if button_order != ["前进", "回退", "保存", "另存为", "取消"]: + checks.append("editor_button_order") + toc_items_after_edit = window.toc_tree.findItems( + "*", + Qt.MatchFlag.MatchWildcard | Qt.MatchFlag.MatchRecursive, + ) + if not toc_items_after_edit: + checks.append("editor_toc_visible") + else: + target_slug = str(toc_items_after_edit[0].data(0, Qt.ItemDataRole.UserRole)) + window._open_toc_item(toc_items_after_edit[0]) + if window.current_fragment != target_slug: + checks.append("editor_toc_click") + second_edit_toc = next( + ( + item + for item in toc_items_after_edit + if item is not toc_items_after_edit[0] and item.data(0, Qt.ItemDataRole.UserRole) + ), + None, + ) + if second_edit_toc is not None: + second_edit_slug = str(second_edit_toc.data(0, Qt.ItemDataRole.UserRole)) + window._open_toc_item(second_edit_toc) + if window.current_fragment != second_edit_slug: + checks.append("editor_toc_second_click") + editor_widget.editor.setPlainText("\n".join(f"line {index}" for index in range(160))) + editor_widget.editor.verticalScrollBar().setValue(editor_widget.editor.verticalScrollBar().maximum()) + editor_widget._sync_preview_to_editor_scroll(editor_widget.editor.verticalScrollBar().value()) + if editor_widget._preview_scroll_ratio < 0.9: + checks.append("editor_preview_scroll_sync") + editor_widget.editor.setPlainText("undo baseline") + cursor = editor_widget.editor.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.End) + editor_widget.editor.setTextCursor(cursor) + editor_widget.editor.insertPlainText(" changed") + editor_widget.undo_button.click() + if editor_widget.source_text() != "undo baseline": + checks.append("editor_undo_button") + editor_widget.redo_button.click() + if editor_widget.source_text() != "undo baseline changed": + checks.append("editor_redo_button") + editor_widget.editor.setPlainText("# Editor Tab\n\n标签页编辑保存\n") + editor_widget._emit_save_requested() + if window.tabs.currentWidget() is not editor_widget: + checks.append("editor_tab_stays_open") + if "标签页编辑保存" not in editor_test_path.read_text(encoding="utf-8"): + checks.append("editor_tab_save") + tab_count_before_theme = window.tabs.count() + window._set_theme_color("black") + window.refresh_document() + if window.tabs.count() != tab_count_before_theme: + checks.append("editor_theme_new_tab") + if editor_widget.theme != "dark": + checks.append("editor_theme_update") + window._set_theme_color("white") + window.refresh_document() + window._close_tab(window.tabs.currentIndex()) + if window.tabs.count() == 0: + checks.append("welcome_after_close") + window.open_document(project_root / "sample.md", add_history=False) + finally: + for cleanup_path in ( + editor_test_path, + project_root / "__gui_smoke_editor_saved_as.md", + project_root / "__gui_smoke_conflict.md", + ): + try: + cleanup_path.unlink(missing_ok=True) + except OSError: + pass window.katex_action.trigger() if window.math_engine != "katex": checks.append("katex_action") @@ -66,15 +496,18 @@ def main() -> int: checks.append("config_external_applications") if snapshot.get("reader", {}).get("theme_background") is None: checks.append("config_theme_background") + if snapshot.get("reader", {}).get("document_tree_label_mode") not in {"title", "filename"}: + checks.append("config_tree_label_mode") window._apply_configuration( { "reader": { "theme_color": "dark_gray", - "theme_background": "circuit", + "theme_background": "peony", "math_engine": "katex", "font_scale": 1.2, "document_font_family": "Microsoft YaHei UI", "document_font_size": 18, + "document_tree_label_mode": "filename", "ui_font_family": "Microsoft YaHei UI", "ui_font_point_size": 10, }, @@ -86,10 +519,12 @@ def main() -> int: ) if window.theme != "dark" or window.theme_color != "dark_gray" or window.math_engine != "katex": checks.append("config_apply_reader") - if window.theme_background != "circuit": + if window.theme_background != "none": checks.append("config_apply_theme_background") if window.document_font_size != 18 or window.document_font_family != "Microsoft YaHei UI": checks.append("config_apply_document_font") + if window.document_tree_label_mode != "filename": + checks.append("config_apply_tree_label_mode") if window.ui_font_family != "Microsoft YaHei UI" or window.ui_font_point_size != 10: checks.append("config_apply_ui_font") if ".mp4" not in window.external_applications: diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..75cfe5f --- /dev/null +++ b/todo.md @@ -0,0 +1,146 @@ +# MDHelper TODO + +## 1. Markdown 编辑功能 + +- [x] 增加基础编辑模式:打开当前 `.md/.markdown` 源文件,使用 `QPlainTextEdit` 编辑。 +- [x] 支持快捷键:`Ctrl+E` 进入编辑,`Ctrl+S` 保存。 +- [x] 保存后刷新当前阅读页、右侧目录、左侧文档树和全文搜索索引。 +- [x] 避免保存触发 `QFileSystemWatcher` 后重复刷新或状态抖动。 + +风险与注意事项: + +- 内置保存和外部编辑器保存都会触发文件监听,需要区分“程序自己保存”和“外部变更”。 +- 当前多标签页可以打开同一个文件,保存后要明确哪些标签页刷新。 +- 编辑时关闭窗口或切换文件要防止未保存内容丢失。 +- 非 UTF-8 编码文件可能读取失败,需要给出友好的错误提示。 + +## 2. 分屏编辑与预览 + +- [x] 增加“源码 / 预览 / 分屏”视图模式。 +- [x] 编辑时使用防抖刷新预览,避免每次按键都完整渲染。 +- [x] 分屏模式下保持预览滚动位置尽量稳定。 + +风险与注意事项: + +- WebEngine 渲染较重,实时预览需要节流。 +- 标题 slug、Mermaid、公式和媒体资源都依赖完整渲染,局部刷新不一定可靠。 +- 分屏会改变主界面布局,需要和现有多标签、主题、目录栏协同。 + +## 3. 编辑体验增强 + +- [x] 增加 Markdown 语法高亮。 +- [x] 增加行号、当前行高亮、查找/替换。 +- [x] 增加未保存标记,并在关闭标签页/窗口时询问保存。 +- [x] 支持自动保存或恢复草稿。 + +风险与注意事项: + +- 自动保存可能覆盖用户不想保存的临时改动,默认应谨慎。 +- 查找/替换要区分“源码编辑器内查找”和“阅读页页内查找”。 +- 行号和大文件语法高亮可能影响性能。 + +## 4. 文件打开与链接策略继续完善 + +- [x] 本地非预览文件支持记住用户选择的打开程序,例如 `.mp4 -> VLC.exe`。 +- [x] 同类文件下次自动使用记住的程序打开。 +- [x] 提供管理已记住程序的入口。 + +风险与注意事项: + +- 记住的程序路径可能被移动或卸载,打开前需要校验。 +- 不应强行在标签页内展示所有媒体,系统默认程序或用户指定程序更稳。 + +## 5. GUI 自动化测试 + +- [x] 覆盖本地链接在本标签页/新标签页打开的路由。 +- [x] 补充右键菜单动作信号测试。 +- [x] 覆盖本地文件打开策略的程序记忆、HTML 导出辅助路径。 +- [x] 补充真实 PDF 导出和外部程序选择动作测试。 +- [x] 覆盖书签恢复、滚动位置恢复、主题切换、编辑保存刷新。 + +风险与注意事项: + +- Qt WebEngine 在无界面环境下偶发不稳定,测试要保留最小烟雾测试和可重复的等待条件。 +- 涉及系统默认程序的测试应避免真的启动外部播放器。 + +## 6. 发布与打包 + +- [ ] 功能稳定后再重新执行 PyInstaller 打包。 +- [x] 打包前确认 WebEngine、资源文件、媒体示例和日志路径正常。 +- [ ] 打包后运行 `dist/MDHelper.exe --check` 或等价检查。 + +风险与注意事项: + +- WebEngine 资源和离线 Mermaid/KaTeX/MathJax 文件容易漏打包。 +- 单文件 exe 首次启动会解压,启动日志路径要能写入。 + +## 7. Markdown 编辑器继续完善 + +- [x] 将编辑器类拆分到独立模块,降低主窗口复杂度。 +- [x] 将 Markdown 编辑器嵌入标签栏,默认以分屏模式打开。 +- [x] 点选“编辑当前 Markdown”时用编辑标签原位替换原阅读标签。 +- [x] 编辑器顶部不再单独显示文档路径,路径由标签标题表达。 +- [x] 编辑器控制栏合并“视图、查找源码、替换、大小写、全词”等控件。 +- [x] 保存前检测磁盘文件是否被外部修改,避免覆盖外部编辑。 +- [x] 增加“另存为”功能,并刷新文档树和搜索索引。 +- [x] 草稿记录补充保存时间、文件修改时间、文件大小等信息。 +- [x] 查找/替换增加命中数量、当前位置、区分大小写、全词匹配和 `Ctrl+H`。 +- [x] 分屏模式增加源码和预览的滚动同步。 +- [x] 增加插入工具栏:标题、加粗、斜体、代码块、表格、链接、图片、提示块、Mermaid、公式。 +- [x] 编辑器颜色跟随应用主题,深色主题下保持可读。 +- [x] 补充编辑器专项测试:外部修改冲突、另存为、查找替换、草稿元数据、插入模板。 +- [x] 补充编辑器标签页测试:默认分屏、标签内保存、保存后不关闭。 + +## 8. 目录跳转稳定性 + +- [x] 点击目录标题时仅在阅读标签页执行跳转,避免编辑标签页误用旧阅读页。 +- [x] 锚点跳转改为多次重试,兼容 WebEngine 页面尚未完全就绪的情况。 +- [x] 跳转时更新页面 hash 并触发滚动状态上报,提升目录高亮一致性。 +- [x] 编辑标签页中目录栏展示当前源码标题,并支持点击定位到源码标题。 + +## 9. 启动与项目目录 + +- [x] 默认启动不再自动打开内置示例文件夹和 `sample.md`。 +- [x] 首次无记录时提示用户选择文件夹或文件。 +- [x] 选择 Markdown 文件时自动把文件所在目录作为当前文件夹。 +- [x] 记录上次打开的文件夹,下次启动自动恢复该文件夹。 +- [x] 记录窗口大小和位置,下次启动按上次窗口几何恢复,不再启动后强制固定大小。 + +## 10. 欢迎页与文件树 + +- [x] 标签栏没有文档时自动显示只读欢迎标签。 +- [x] 打开任意文档时自动关闭欢迎标签。 +- [x] 所有文档标签关闭后自动恢复欢迎标签。 +- [x] 打开文件夹后左侧文档栏按目录结构展示当前文件夹下的文件。 +- [x] 从“打开文件”选择文件时,自动把文件所在目录作为当前文件夹,并打开该文件内容。 +- [x] 左侧文件树点击 Markdown/网页文件在标签页打开,其他文件沿用本地程序打开策略。 +- [x] 默认仅展开当前文件夹根节点,子文件夹保持折叠,减少大目录下的视觉噪音。 +- [x] 为文件夹和文件设置相近但不同的文字颜色,文件按类型显示图标,接近 VSCode 的文件树识别体验。 +- [x] 文件树仅展示 Markdown 和网页文档,文件夹优先并按名称排序。 +- [x] 文件树右键支持切换 Markdown 显示为文档标题或文件名。 +- [x] 优化文件夹折叠/展开箭头,提高目录层级可见性。 + +## 11. 工具栏与分屏预览 + +- [x] 编辑 Markdown 时,分屏预览按源码滚动比例跟随编辑区上下移动。 +- [x] 删除工具栏首页按钮,将后退、前进、打开、刷新改为图标按钮。 +- [x] 将工具栏 A-/A+ 改为文档字号下拉框,并增加文档字体下拉框。 +- [x] 编辑模式下调整文档字号时,同时调整预览窗口和源码编辑窗口字号。 +- [x] 编辑模式下在保存、另存为、取消前补充回退/前进按钮。 +- [x] 强化阅读/编辑模式目录连续点击跳转,避免首次正常后后续失效。 + +## 12. 主题背景 + +- [x] 默认主题颜色改为彩色。 +- [x] 删除旧主题背景选项,新增无、中国结、祥云、如意、毛笔、牡丹、竹、回纹。 +- [x] 为新增主题背景提供离线 SVG 纹样资源,并兼容旧配置中的背景值。 +- [x] 限制主题背景仅在主题颜色为彩色时可选,其他颜色自动使用“无”。 +- [x] 修改主题背景时同步刷新窗口图标和 MDHelper 标题栏颜色。 + +风险与注意事项: + +- 冲突检测要避免误判,也要避免静默覆盖外部工具已经保存的内容。 +- “另存为”后要同步文档树、最近文件、搜索索引、当前标签页标题和文件监听。 +- 草稿不能直接覆盖正式文件,只能在用户确认后恢复。 +- 分屏同步滚动只能做近似同步,Mermaid、公式和图片会让源码高度与预览高度不一致。 +- 插入工具栏要操作选区,不能破坏已有文本。