diff --git a/MDHelper.spec b/MDHelper.spec index 5e82009..dc84a36 100644 --- a/MDHelper.spec +++ b/MDHelper.spec @@ -19,7 +19,7 @@ a = Analysis( binaries=[], datas=datas, hiddenimports=[], - hookspath=[], + hookspath=[str(project_root / "hooks")], hooksconfig={}, runtime_hooks=[], excludes=[], diff --git a/hooks/hook-PySide6.QtQml.py b/hooks/hook-PySide6.QtQml.py new file mode 100644 index 0000000..ea7044a --- /dev/null +++ b/hooks/hook-PySide6.QtQml.py @@ -0,0 +1,4 @@ +from PyInstaller.utils.hooks.qt import add_qt6_dependencies + + +hiddenimports, binaries, datas = add_qt6_dependencies(__file__) diff --git a/mdhelper/app.py b/mdhelper/app.py index 5857636..f58b8f0 100644 --- a/mdhelper/app.py +++ b/mdhelper/app.py @@ -2,9 +2,20 @@ from __future__ import annotations import argparse import logging +import os import sys +import tempfile from pathlib import Path +os.environ.setdefault( + "QTWEBENGINE_CHROMIUM_FLAGS", + "--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --log-level=3", +) +os.environ.setdefault( + "QT_LOGGING_RULES", + "qt.multimedia.ffmpeg.*=false;qt.multimedia.*.debug=false;qt.multimedia.*.info=false", +) + from PySide6.QtCore import QSettings, Qt from PySide6.QtGui import QIcon from PySide6.QtWidgets import QApplication @@ -17,9 +28,9 @@ from .main_window import MainWindow def parse_arguments(argv: list[str]) -> argparse.Namespace: parser = argparse.ArgumentParser(description="MDHelper 本地 Markdown 帮助文档阅读器") - parser.add_argument("file", nargs="?", help="启动后打开的 Markdown、网页或本地文件") + parser.add_argument("path", nargs="?", help="启动后打开的文件或文件夹;可传相对文件夹名") parser.add_argument("--check", action="store_true", help="检查 sample.md 和 docs/ 中缺失的本地链接/媒体") - parser.add_argument("--project-root", default=None, help="项目根目录,默认使用 MDHelper 所在目录") + parser.add_argument("--project-root", "--folder", dest="project_root", default=None, help="项目根目录,默认使用最近打开的文件夹") return parser.parse_args(argv) @@ -33,18 +44,65 @@ def runtime_paths() -> tuple[Path, Path]: return root, root +def resolve_launch_path(value: str | None, search_roots: tuple[Path, ...]) -> Path | None: + if not value: + return None + + raw_path = Path(value).expanduser() + candidates = [raw_path] + if not raw_path.is_absolute(): + candidates.extend(root / raw_path for root in search_roots) + + for candidate in candidates: + if candidate.exists(): + return candidate.resolve() + return raw_path.resolve() + + +def project_and_initial_path(launch_path: Path | None, project_root: Path | None) -> tuple[Path | None, Path | None]: + if project_root is not None: + return project_root, launch_path if launch_path is not None and launch_path.is_file() else None + if launch_path is None: + return None, None + if launch_path.is_file(): + return launch_path.parent, launch_path + return launch_path, None + + +def configure_process_runtime(log_root: Path) -> Path: + runtime_root = Path(tempfile.gettempdir()) / "MDHelper" / "runtime" / str(os.getpid()) + user_data_dir = runtime_root / "webengine" + cache_dir = runtime_root / "cache" + user_data_dir.mkdir(parents=True, exist_ok=True) + cache_dir.mkdir(parents=True, exist_ok=True) + + flags = os.environ.get("QTWEBENGINE_CHROMIUM_FLAGS", "") + additions = [ + f"--user-data-dir={user_data_dir.as_posix()}", + f"--disk-cache-dir={cache_dir.as_posix()}", + ] + for addition in additions: + prefix = addition.split("=", 1)[0] + if prefix not in flags: + flags = f"{flags} {addition}".strip() + os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = flags + os.environ.setdefault("MDHELPER_PROCESS_RUNTIME_DIR", str(runtime_root)) + logging.getLogger(__name__).debug("Process runtime root: %s; log root: %s", runtime_root, log_root) + return runtime_root + + def main(argv: list[str] | None = None) -> int: args = parse_arguments(list(sys.argv[1:] if argv is None else argv)) content_root, log_root = runtime_paths() - cli_initial_path = Path(args.file).expanduser().resolve() if args.file else None - cli_project_root = Path(args.project_root).expanduser().resolve() if args.project_root else None - project_root = cli_project_root - if project_root is None and cli_initial_path is not None: - project_root = cli_initial_path.parent if cli_initial_path.is_file() else cli_initial_path + search_roots = (Path.cwd(), log_root, content_root) + cli_launch_path = resolve_launch_path(args.path, search_roots) + cli_project_root = resolve_launch_path(args.project_root, search_roots) + project_root, cli_initial_path = project_and_initial_path(cli_launch_path, cli_project_root) if args.check: return check_documents_main([str(project_root or content_root)]) QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True) + configure_process_runtime(log_root) setup_logging(log_root) app = QApplication([sys.argv[0]]) @@ -71,7 +129,7 @@ def main(argv: list[str] | None = None) -> int: 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, + initial_path=cli_initial_path, app_root=content_root, prompt_for_project=project_root is None, ) diff --git a/mdhelper/code_structure.py b/mdhelper/code_structure.py new file mode 100644 index 0000000..c517c2b --- /dev/null +++ b/mdhelper/code_structure.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import ast +import re +from pathlib import Path + +from .document_tree import CPP_EXTENSIONS, PYTHON_EXTENSIONS +from .markdown_utils import Heading +from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback + +_CPP_TYPE_RE = re.compile(r"^\s*(class|struct)\s+([A-Za-z_]\w*)\b") +_CPP_FUNCTION_RE = re.compile( + r"^\s*(?:template\s*<[^;{}]+>\s*)?(?:[A-Za-z_~][\w:<>~*&\s,]*\s+)?([A-Za-z_~][\w:]*)\s*\([^;{}]*\)\s*(?:const\s*)?(?:noexcept\s*)?(?:->\s*[^{};]+\s*)?(?:\{|$)" +) +_CPP_CONTROL_WORDS = {"if", "for", "while", "switch", "catch", "return", "sizeof"} + + +def extract_code_headings(path: Path, source: str | None = None) -> list[Heading]: + suffix = path.suffix.lower() + if source is None: + source = read_text_with_fallback(path, max_bytes=DEFAULT_TEXT_PREVIEW_BYTES) + if suffix in PYTHON_EXTENSIONS: + return _extract_python_headings(source) + if suffix in CPP_EXTENSIONS: + return _extract_cpp_headings(source) + return [] + + +def _extract_python_headings(source: str) -> list[Heading]: + try: + tree = ast.parse(source) + except SyntaxError: + return [] + + headings: list[Heading] = [] + + def walk(nodes: list[ast.stmt], level: int) -> None: + for node in nodes: + if isinstance(node, ast.ClassDef): + headings.append(Heading(level=min(level, 6), title=f"class {node.name}", slug=f"line-{node.lineno}")) + walk(node.body, min(level + 1, 6)) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def" + headings.append(Heading(level=min(level, 6), title=f"{prefix} {node.name}", slug=f"line-{node.lineno}")) + walk(node.body, min(level + 1, 6)) + + walk(list(tree.body), 1) + return headings + + +def _extract_cpp_headings(source: str) -> list[Heading]: + headings: list[Heading] = [] + pending_template = False + for lineno, line in enumerate(source.splitlines(), start=1): + stripped = line.strip() + if not stripped or stripped.startswith(("//", "#")): + continue + if stripped.startswith("template"): + pending_template = True + continue + + type_match = _CPP_TYPE_RE.match(line) + if type_match: + kind, name = type_match.groups() + headings.append(Heading(level=1, title=f"{kind} {name}", slug=f"line-{lineno}")) + pending_template = False + continue + + function_line = f"template <> {line}" if pending_template else line + func_match = _CPP_FUNCTION_RE.match(function_line) + if not func_match: + pending_template = False + continue + name = func_match.group(1).split("::")[-1] + if name in _CPP_CONTROL_WORDS: + pending_template = False + continue + headings.append(Heading(level=2, title=f"function {func_match.group(1)}", slug=f"line-{lineno}")) + pending_template = False + return headings diff --git a/mdhelper/document_tree.py b/mdhelper/document_tree.py index 90782e4..7cfff65 100644 --- a/mdhelper/document_tree.py +++ b/mdhelper/document_tree.py @@ -1,12 +1,26 @@ from __future__ import annotations +import os from dataclasses import dataclass from pathlib import Path +from typing import Iterator from .media import MARKDOWN_EXTENSIONS, WEBPAGE_EXTENSIONS -from .markdown_utils import extract_headings +from .markdown_utils import extract_headings_from_text +from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, is_within_size_limit, read_text_with_fallback -SUPPORTED_DOCUMENT_EXTENSIONS = MARKDOWN_EXTENSIONS | WEBPAGE_EXTENSIONS +PYTHON_EXTENSIONS = {".py", ".pyw", ".pyi"} +CPP_EXTENSIONS = {".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".hpp"} + +FILE_GROUP_EXTENSIONS = { + "markdown": MARKDOWN_EXTENSIONS | WEBPAGE_EXTENSIONS, + "python": PYTHON_EXTENSIONS, + "cpp": CPP_EXTENSIONS, +} +DEFAULT_DOCUMENT_FILE_GROUPS = ("markdown",) +SUPPORTED_DOCUMENT_EXTENSIONS = set().union(*FILE_GROUP_EXTENSIONS.values()) +CODE_DOCUMENT_EXTENSIONS = PYTHON_EXTENSIONS | CPP_EXTENSIONS +MAX_DISCOVERABLE_CODE_BYTES = DEFAULT_TEXT_PREVIEW_BYTES EXCLUDED_DIR_NAMES = { ".git", @@ -31,27 +45,109 @@ class DocumentEntry: relative_path: str +def normalized_document_file_groups(groups: object) -> tuple[str, ...]: + if isinstance(groups, str): + candidates = [part.strip() for part in groups.split(",")] + elif isinstance(groups, (list, tuple, set)): + candidates = [str(part).strip() for part in groups] + else: + candidates = list(DEFAULT_DOCUMENT_FILE_GROUPS) + + normalized: list[str] = [] + for group in candidates: + if group in FILE_GROUP_EXTENSIONS and group not in normalized: + normalized.append(group) + return tuple(normalized or DEFAULT_DOCUMENT_FILE_GROUPS) + + +def document_extensions_for_groups(groups: object = None) -> set[str]: + enabled_groups = normalized_document_file_groups(groups) + extensions: set[str] = set() + for group in enabled_groups: + extensions.update(FILE_GROUP_EXTENSIONS[group]) + return extensions + + +def is_code_document(path: Path) -> bool: + return path.suffix.lower() in CODE_DOCUMENT_EXTENSIONS + + +def code_language_for_path(path: Path) -> str: + suffix = path.suffix.lower() + if suffix in PYTHON_EXTENSIONS: + return "python" + if suffix in {".c", ".h"}: + return "c" + if suffix in CPP_EXTENSIONS: + return "cpp" + return "text" + + +def is_discoverable_document(path: Path, supported_extensions: set[str]) -> bool: + suffix = path.suffix.lower() + if suffix not in supported_extensions: + return False + if suffix in CODE_DOCUMENT_EXTENSIONS: + return is_within_size_limit(path, MAX_DISCOVERABLE_CODE_BYTES) + return True + + def first_heading(path: Path) -> str | None: if path.suffix.lower() not in {".md", ".markdown"}: return None - headings = extract_headings(path) + text = read_text_with_fallback(path, max_bytes=DEFAULT_TEXT_PREVIEW_BYTES) + if not text or text.startswith("读取失败:"): + return None + headings = extract_headings_from_text(text) return headings[0].title if headings else None -def discover_documents(project_root: Path) -> list[DocumentEntry]: - 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) - ] - +def discover_documents(project_root: Path, enabled_groups: object = None) -> list[DocumentEntry]: + root = project_root.resolve() + supported_extensions = document_extensions_for_groups(enabled_groups) entries: list[DocumentEntry] = [] - for path in candidates: + + for path in _iter_project_files(root): + if not is_discoverable_document(path, supported_extensions): + continue + try: + relative_path = path.relative_to(root).as_posix() + except ValueError: + continue resolved = path.resolve() title = first_heading(resolved) or resolved.stem.replace("_", " ").title() - relative_path = resolved.relative_to(project_root).as_posix() entries.append(DocumentEntry(path=resolved, title=title, relative_path=relative_path)) return entries + + +def _iter_project_files(root: Path) -> Iterator[Path]: + stack = [root] + while stack: + directory = stack.pop() + try: + with os.scandir(directory) as scanner: + dirs: list[tuple[str, Path]] = [] + files: list[tuple[str, Path]] = [] + for entry in scanner: + name = entry.name + if _is_excluded_name(name): + continue + try: + if entry.is_dir(follow_symlinks=False): + dirs.append((name.casefold(), Path(entry.path))) + elif entry.is_file(follow_symlinks=False): + files.append((name.casefold(), Path(entry.path))) + except OSError: + continue + except OSError: + continue + + for _, path in sorted(files): + yield path + for _, path in reversed(sorted(dirs)): + stack.append(path) + + +def _is_excluded_name(name: str) -> bool: + return name.startswith(".") or name in EXCLUDED_DIR_NAMES diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py new file mode 100644 index 0000000..6cfb228 --- /dev/null +++ b/mdhelper/docx_exporter.py @@ -0,0 +1,432 @@ +from __future__ import annotations + +import html +import subprocess +import tempfile +import zipfile +from dataclasses import dataclass +from pathlib import Path +from xml.sax.saxutils import escape + +from markdown_it import MarkdownIt +from markdown_it.token import Token + + +WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" +DOCX_EXPORT_ENGINES = { + "pandoc": "Pandoc(推荐,保真度较高)", + "python-docx": "python-docx(纯 Python)", + "builtin": "内置基础导出", +} + + +class DocxExportError(RuntimeError): + pass + + +def export_markdown_to_docx( + source: str, + output_path: Path, + engine: str = "builtin", + source_path: Path | None = None, +) -> Path: + if engine == "pandoc": + return export_markdown_to_docx_pandoc(source, output_path, source_path=source_path) + if engine == "python-docx": + return export_markdown_to_docx_python_docx(source, output_path) + return export_markdown_to_docx_builtin(source, output_path) + + +def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: + if output_path.suffix.lower() != ".docx": + output_path = output_path.with_suffix(".docx") + + blocks = _markdown_blocks(source) + document_xml = _document_xml(blocks) + output_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as package: + package.writestr("[Content_Types].xml", CONTENT_TYPES_XML) + package.writestr("_rels/.rels", PACKAGE_RELS_XML) + package.writestr("word/document.xml", document_xml) + package.writestr("word/styles.xml", STYLES_XML) + package.writestr("word/settings.xml", SETTINGS_XML) + return output_path + + +def export_markdown_to_docx_pandoc(source: str, output_path: Path, source_path: Path | None = None) -> Path: + if output_path.suffix.lower() != ".docx": + output_path = output_path.with_suffix(".docx") + output_path.parent.mkdir(parents=True, exist_ok=True) + + temporary_path: Path | None = None + input_path = source_path if source_path is not None and source_path.exists() else None + if input_path is None: + with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as handle: + handle.write(source) + temporary_path = Path(handle.name) + input_path = temporary_path + + command = ["pandoc", str(input_path), "-o", str(output_path), "--standalone"] + try: + result = subprocess.run( + command, + cwd=str(input_path.parent), + capture_output=True, + text=True, + timeout=120, + check=False, + ) + except FileNotFoundError as exc: + raise DocxExportError("未找到 pandoc,请确认 pandoc 已安装并加入 PATH。") from exc + except subprocess.TimeoutExpired as exc: + raise DocxExportError("pandoc 导出超时。") from exc + finally: + if temporary_path is not None: + try: + temporary_path.unlink(missing_ok=True) + except OSError: + pass + + if result.returncode != 0: + detail = (result.stderr or result.stdout or "pandoc 返回错误。").strip() + raise DocxExportError(detail) + return output_path + + +def export_markdown_to_docx_python_docx(source: str, output_path: Path) -> Path: + if output_path.suffix.lower() != ".docx": + output_path = output_path.with_suffix(".docx") + try: + from docx import Document + from docx.oxml.ns import qn + from docx.shared import Pt + except ImportError as exc: + raise DocxExportError("未找到 python-docx,请先安装 python-docx。") from exc + + document = Document() + normal = document.styles["Normal"] + normal.font.name = "Microsoft YaHei" + normal.font.size = Pt(11) + normal.element.rPr.rFonts.set(qn("w:eastAsia"), "Microsoft YaHei") + + for block in _markdown_blocks(source): + if isinstance(block, TableBlock): + _add_python_docx_table(document, block) + continue + _add_python_docx_paragraph(document, block) + + output_path.parent.mkdir(parents=True, exist_ok=True) + document.save(str(output_path)) + return output_path + + +def _markdown_blocks(source: str) -> list[ParagraphBlock | TableBlock]: + markdown = MarkdownIt("commonmark", {"html": True}).enable(["table", "strikethrough"]) + return _DocxBuilder(markdown.parse(source)).build() + + +def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: + style = f"Heading {block.style.removeprefix('Heading')}" if block.style.startswith("Heading") else None + if block.list_kind == "bullet": + style = "List Bullet" + elif block.list_kind == "number": + style = "List Number" + elif block.style == "Code": + style = None + + paragraph = document.add_paragraph(style=style) + if block.quote_depth: + paragraph.paragraph_format.left_indent = _docx_inches(0.35) + for text, run_style in block.runs: + parts = text.split("\n") + for part_index, part in enumerate(parts): + if part_index: + paragraph.add_run().add_break() + run = paragraph.add_run(part) + run.bold = bool(run_style.get("bold")) + run.italic = bool(run_style.get("italic")) + if run_style.get("code") or block.style == "Code": + run.font.name = "Consolas" + run.font.size = _docx_pt(10) + + +def _add_python_docx_table(document: object, block: TableBlock) -> None: + if not block.rows: + return + column_count = max(len(row) for row in block.rows) + table = document.add_table(rows=len(block.rows), cols=column_count) + table.style = "Table Grid" + for row_index, row in enumerate(block.rows): + for col_index in range(column_count): + cell = table.cell(row_index, col_index) + runs = row[col_index] if col_index < len(row) else [("", {})] + paragraph = cell.paragraphs[0] + for text, run_style in runs: + run = paragraph.add_run(text) + run.bold = bool(run_style.get("bold") or row_index == 0) + run.italic = bool(run_style.get("italic")) + if run_style.get("code"): + run.font.name = "Consolas" + run.font.size = _docx_pt(10) + + +def _docx_pt(value: int) -> object: + from docx.shared import Pt + + return Pt(value) + + +def _docx_inches(value: float) -> object: + from docx.shared import Inches + + return Inches(value) + + +@dataclass +class ParagraphBlock: + runs: list[tuple[str, dict[str, bool]]] + style: str = "Normal" + list_kind: str = "" + quote_depth: int = 0 + + +@dataclass +class TableBlock: + rows: list[list[list[tuple[str, dict[str, bool]]]]] + + +class _DocxBuilder: + def __init__(self, tokens: list[Token]) -> None: + self.tokens = tokens + self.blocks: list[ParagraphBlock | TableBlock] = [] + self.index = 0 + self.list_stack: list[str] = [] + self.quote_depth = 0 + + def build(self) -> list[ParagraphBlock | TableBlock]: + while self.index < len(self.tokens): + token = self.tokens[self.index] + if token.type == "heading_open": + level = min(max(int(token.tag[1:]), 1), 6) if token.tag.startswith("h") else 1 + self._add_next_inline(f"Heading{level}") + continue + if token.type == "paragraph_open": + style = "Quote" if self.quote_depth else "Normal" + self._add_next_inline(style, list_kind=self.list_stack[-1] if self.list_stack else "") + continue + if token.type in {"fence", "code_block"}: + for line in token.content.rstrip("\n").splitlines() or [""]: + self.blocks.append(ParagraphBlock([(line, {"code": True})], style="Code")) + elif token.type == "blockquote_open": + self.quote_depth += 1 + elif token.type == "blockquote_close": + self.quote_depth = max(0, self.quote_depth - 1) + elif token.type == "bullet_list_open": + self.list_stack.append("bullet") + elif token.type == "ordered_list_open": + self.list_stack.append("number") + elif token.type in {"bullet_list_close", "ordered_list_close"} and self.list_stack: + self.list_stack.pop() + elif token.type == "table_open": + self.blocks.append(self._collect_table()) + continue + elif token.type == "hr": + self.blocks.append(ParagraphBlock([("_" * 30, {})])) + self.index += 1 + return self.blocks + + def _add_next_inline(self, style: str, list_kind: str = "") -> None: + inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None + runs = _inline_runs(inline.children if inline is not None else None) + self.blocks.append(ParagraphBlock(runs, style=style, list_kind=list_kind, quote_depth=self.quote_depth)) + self.index += 3 + + def _collect_table(self) -> TableBlock: + rows: list[list[list[tuple[str, dict[str, bool]]]]] = [] + current_row: list[list[tuple[str, dict[str, bool]]]] | None = None + while self.index < len(self.tokens): + token = self.tokens[self.index] + if token.type == "tr_open": + current_row = [] + elif token.type == "tr_close" and current_row is not None: + rows.append(current_row) + current_row = None + elif token.type in {"th_open", "td_open"} and current_row is not None: + inline = self.tokens[self.index + 1] if self.index + 1 < len(self.tokens) else None + cell_runs = _inline_runs(inline.children if inline is not None else None) + current_row.append(cell_runs) + elif token.type == "table_close": + self.index += 1 + break + self.index += 1 + return TableBlock(rows) + + +def _inline_runs(children: list[Token] | None) -> list[tuple[str, dict[str, bool]]]: + if not children: + return [("", {})] + + runs: list[tuple[str, dict[str, bool]]] = [] + style_stack: list[str] = [] + for child in children: + if child.type == "strong_open": + style_stack.append("bold") + elif child.type == "strong_close": + _pop_style(style_stack, "bold") + elif child.type == "em_open": + style_stack.append("italic") + elif child.type == "em_close": + _pop_style(style_stack, "italic") + elif child.type == "code_inline": + runs.append((child.content, {"code": True})) + elif child.type in {"text", "html_inline"}: + text = html.unescape(child.content) if child.type == "html_inline" else child.content + runs.append((text, {"bold": "bold" in style_stack, "italic": "italic" in style_stack})) + elif child.type in {"softbreak", "hardbreak"}: + runs.append(("\n", {})) + elif child.children: + runs.extend(_inline_runs(child.children)) + return runs or [("", {})] + + +def _pop_style(style_stack: list[str], value: str) -> None: + for index in range(len(style_stack) - 1, -1, -1): + if style_stack[index] == value: + del style_stack[index] + return + + +def _document_xml(blocks: list[ParagraphBlock | TableBlock]) -> str: + body = "\n".join(_block_xml(block) for block in blocks) + return f""" + + + {body} + + + + + + +""" + + +def _block_xml(block: ParagraphBlock | TableBlock) -> str: + if isinstance(block, TableBlock): + return _table_xml(block) + return _paragraph_xml(block) + + +def _paragraph_xml(block: ParagraphBlock) -> str: + props = [f''] if block.style != "Normal" else [] + if block.list_kind: + bullet = "•" if block.list_kind == "bullet" else "1." + block = ParagraphBlock([(bullet + " ", {"bold": True}), *block.runs], style=block.style, quote_depth=block.quote_depth) + props.append('') + if block.quote_depth: + props.append('') + ppr = f"{''.join(props)}" if props else "" + return f"{ppr}{''.join(_run_xml(text, style) for text, style in block.runs)}" + + +def _run_xml(text: str, style: dict[str, bool]) -> str: + if text == "\n": + return "" + props = [] + if style.get("bold"): + props.append("") + if style.get("italic"): + props.append("") + if style.get("code"): + props.append('') + rpr = f"{''.join(props)}" if props else "" + preserve = ' xml:space="preserve"' if text[:1].isspace() or text[-1:].isspace() else "" + return f"{rpr}{escape(text)}" + + +def _table_xml(block: TableBlock) -> str: + rows = [] + for row in block.rows: + cells = [] + for cell in row: + cells.append(f"{_paragraph_xml(ParagraphBlock(cell))}") + rows.append(f"{''.join(cells)}") + return ( + '' + '' + '' + '' + '' + '' + '' + f"{''.join(rows)}" + ) + + +CONTENT_TYPES_XML = """ + + + + + + + +""" + +PACKAGE_RELS_XML = """ + + + +""" + +SETTINGS_XML = f""" + + + +""" + +STYLES_XML = f""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" diff --git a/mdhelper/logging_config.py b/mdhelper/logging_config.py index a2675f7..1bd9ed1 100644 --- a/mdhelper/logging_config.py +++ b/mdhelper/logging_config.py @@ -1,7 +1,9 @@ from __future__ import annotations import logging +import os import sys +import tempfile from logging.handlers import RotatingFileHandler from pathlib import Path from types import TracebackType @@ -9,11 +11,51 @@ from types import TracebackType from PySide6.QtCore import qInstallMessageHandler -def setup_logging(project_root: Path) -> Path: - log_dir = project_root / "logs" - log_dir.mkdir(exist_ok=True) - log_path = log_dir / "mdhelper.log" +def _create_file_handler(project_root: Path, formatter: logging.Formatter) -> tuple[RotatingFileHandler, Path]: + errors: list[OSError] = [] + for log_dir in _log_dir_candidates(project_root): + try: + log_dir.mkdir(parents=True, exist_ok=True) + log_path = log_dir / "mdhelper.log" + handler = RotatingFileHandler( + log_path, + maxBytes=1_000_000, + backupCount=3, + encoding="utf-8", + ) + handler.setFormatter(formatter) + return handler, log_path + except OSError as exc: + errors.append(exc) + raise OSError(f"无法创建日志文件,已尝试 {len(errors)} 个位置。") + + +def _log_dir_candidates(project_root: Path) -> list[Path]: + candidates: list[Path] = [] + configured = os.environ.get("MDHELPER_LOG_DIR") + if configured: + candidates.append(Path(configured).expanduser()) + local_app_data = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") + if local_app_data: + candidates.append(Path(local_app_data) / "MDHelper" / "logs") + candidates.extend( + [ + Path.home() / ".mdhelper" / "logs", + project_root / "logs", + Path(tempfile.gettempdir()) / "MDHelper" / "logs", + ] + ) + + unique: list[Path] = [] + for candidate in candidates: + resolved_key = str(candidate) + if resolved_key not in {str(item) for item in unique}: + unique.append(candidate) + return unique + + +def setup_logging(project_root: Path) -> Path: root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) root_logger.handlers.clear() @@ -23,13 +65,7 @@ def setup_logging(project_root: Path) -> Path: datefmt="%Y-%m-%d %H:%M:%S", ) - file_handler = RotatingFileHandler( - log_path, - maxBytes=1_000_000, - backupCount=3, - encoding="utf-8", - ) - file_handler.setFormatter(formatter) + file_handler, log_path = _create_file_handler(project_root, formatter) root_logger.addHandler(file_handler) console_handler = logging.StreamHandler() diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index a36e5b1..ea97c36 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -8,10 +8,14 @@ import os import re import shutil import ctypes +import zipfile +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.policy import default as email_default_policy from pathlib import Path from urllib.parse import unquote, urlsplit -from PySide6.QtCore import QFileSystemWatcher, QObject, QPoint, QProcess, QSettings, QSignalBlocker, QTimer, QUrl, Qt, Signal, Slot +from PySide6.QtCore import QFileSystemWatcher, QObject, QPoint, QProcess, QSettings, QSignalBlocker, QSize, QTimer, QUrl, Qt, Signal, Slot from PySide6.QtGui import ( QAction, QActionGroup, @@ -50,6 +54,7 @@ from PySide6.QtWidgets import ( QStatusBar, QStyledItemDelegate, QStyle, + QTabBar, QTabWidget, QTreeWidget, QTreeWidgetItem, @@ -60,7 +65,18 @@ from PySide6.QtWidgets import ( from .bookmark_dialog import BookmarkManagerDialog from . import __version__ -from .document_tree import DocumentEntry, SUPPORTED_DOCUMENT_EXTENSIONS, discover_documents, first_heading +from .code_structure import extract_code_headings +from .document_tree import ( + DEFAULT_DOCUMENT_FILE_GROUPS, + DocumentEntry, + code_language_for_path, + discover_documents, + document_extensions_for_groups, + first_heading, + is_code_document, + normalized_document_file_groups, +) +from .docx_exporter import DOCX_EXPORT_ENGINES, DocxExportError, export_markdown_to_docx from .history import HistoryItem, NavigationHistory from .markdown_utils import Heading, extract_headings, extract_headings_from_text from .markdown_editor import MarkdownEditorDialog as RichMarkdownEditorDialog @@ -68,6 +84,8 @@ from .markdown_renderer import MarkdownRenderer from .media import is_markdown_url, is_qt_video_player_url, is_webpage_url, media_kind, media_mime_type from .search import SearchIndex from .settings_dialog import AppPreferences, SettingsDialog +from .style_dialog import DocumentStyleEditorDialog, build_document_style_css +from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback BOOKMARKS_SETTING_KEY = "bookmarks/items" @@ -75,8 +93,106 @@ 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" +CUSTOM_DOCUMENT_STYLES_SETTING_KEY = "reader/custom_document_styles" LOGGER = logging.getLogger(__name__) THEME_COLOR_VALUES = {"white", "black", "dark_gray", "colorful"} +WHEEL_SCROLL_SPEED_MIN = 0.5 +WHEEL_SCROLL_SPEED_MAX = 3.0 +DOCUMENT_STYLE_PRESETS = { + "default": { + "name": "默认阅读", + "css": "", + }, + "compact": { + "name": "紧凑参考", + "css": """ +.reader { + max-width: 1120px; + padding: 24px 34px 44px; +} +body { + line-height: 1.58; +} +h1 { + font-size: 1.78em; +} +h2 { + margin-top: 1.3em; +} +p, +li { + margin: 0.42em 0; +} +""".strip(), + }, + "serif": { + "name": "经典书卷", + "css": """ +:root { + --reader-font-family: Georgia, "Times New Roman", "SimSun", "Songti SC", serif; +} +.reader { + max-width: 860px; + padding: 42px 54px 64px; +} +body { + line-height: 1.82; +} +h1, +h2, +h3 { + font-family: Georgia, "Times New Roman", "Microsoft YaHei UI", serif; +} +blockquote { + border-left-width: 3px; +} +""".strip(), + }, + "wide": { + "name": "宽屏技术文档", + "css": """ +.reader { + max-width: 1240px; + padding: 30px 48px 56px; +} +body { + line-height: 1.65; +} +pre, +code, +kbd, +samp { + font-size: 0.95em; +} +table { + font-size: 0.95em; +} +""".strip(), + }, + "focus": { + "name": "专注笔记", + "css": """ +.reader { + max-width: 760px; + padding: 48px 46px 70px; +} +body { + line-height: 1.78; +} +h1 { + text-align: center; + border-bottom: 0; +} +h2 { + margin-top: 1.8em; +} +hr { + margin: 2.2em auto; + max-width: 180px; +} +""".strip(), + }, +} THEME_BACKGROUND_OPTIONS = ( ("无", "none"), ("中国结", "chinese_knot"), @@ -88,6 +204,8 @@ THEME_BACKGROUND_OPTIONS = ( ("回纹", "meander"), ) THEME_BACKGROUND_VALUES = {value for _, value in THEME_BACKGROUND_OPTIONS} +AUTO_REFRESH_MODES = {"off", "current", "resources", "all"} +AUTO_REFRESH_DELAY_VALUES = {800, 1000, 1500} LEGACY_THEME_BACKGROUND_VALUES = { "spring", "straw", @@ -159,6 +277,16 @@ class ReaderBridge(QObject): class ReaderView(QWebEngineView): open_link_requested = Signal(QUrl, bool) + def set_wheel_scroll_speed(self, speed: float) -> None: + try: + normalized = max(WHEEL_SCROLL_SPEED_MIN, min(WHEEL_SCROLL_SPEED_MAX, float(speed))) + except (TypeError, ValueError): + normalized = 1.0 + self.setProperty("wheel_scroll_speed", normalized) + self.page().runJavaScript( + f"document.documentElement.dataset.wheelScrollSpeed = '{normalized:.1f}';" + ) + def contextMenuEvent(self, event: object) -> None: request = self.lastContextMenuRequest() link_url = request.linkUrl() @@ -364,16 +492,20 @@ class MainWindow(QMainWindow): 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) if self.has_project else [] - self.search_index = SearchIndex(self.entries) self.settings = QSettings("MDHelper", "MDHelper") + self.document_file_groups = DEFAULT_DOCUMENT_FILE_GROUPS + self.renderer = MarkdownRenderer(self.project_root) + self.entries: list[DocumentEntry] = ( + discover_documents(self.project_root, self.document_file_groups) if self.has_project else [] + ) + self.search_index = SearchIndex(self.entries) self.current_file: Path | None = None self.current_fragment = "" self.pending_fragment = "" self.pending_find_text = "" self.pending_scroll_y: int | None = None self.font_scale = 1.0 + self.wheel_scroll_speed = 1.0 self.theme = "light" self.theme_color = "colorful" self.theme_background = "none" @@ -381,9 +513,13 @@ class MainWindow(QMainWindow): self.ui_font_point_size = 0 self.document_font_family = "" self.document_font_size = 16 + self.document_style_id = "default" + self.custom_document_styles: dict[str, dict[str, object]] = {} self.document_tree_label_mode = "title" self.math_engine = "katex" self.auto_refresh_enabled = True + self.auto_refresh_mode = "all" + self.auto_refresh_delay_ms = 1000 self.non_preview_action = "ask" self.recent_files: list[Path] = [] self.bookmarks: list[dict[str, str]] = [] @@ -394,18 +530,22 @@ class MainWindow(QMainWindow): 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.watched_file_signatures: dict[Path, tuple[int, int] | None] = {} + self.pending_changed_files: set[Path] = set() + self.pending_directory_refresh = False + self.document_entries_signature = self._document_entries_signature(self.entries) self.file_watcher = QFileSystemWatcher(self) self.file_watcher.fileChanged.connect(self._on_watched_file_changed) self.file_watcher.directoryChanged.connect(self._on_watched_directory_changed) self.refresh_timer = QTimer(self) self.refresh_timer.setSingleShot(True) - self.refresh_timer.setInterval(250) + self.refresh_timer.setInterval(self.auto_refresh_delay_ms) self.refresh_timer.timeout.connect(self._auto_refresh_current_document) self.tree_refresh_timer = QTimer(self) self.tree_refresh_timer.setSingleShot(True) - self.tree_refresh_timer.setInterval(350) + self.tree_refresh_timer.setInterval(self.auto_refresh_delay_ms) self.tree_refresh_timer.timeout.connect(self._refresh_document_entries) self.scroll_capture_timer = QTimer(self) @@ -413,6 +553,11 @@ class MainWindow(QMainWindow): self.scroll_capture_timer.timeout.connect(self._save_current_scroll_position) self._load_preferences() + if self.has_project: + self.entries = discover_documents(self.project_root, self.document_file_groups) + self.document_entries_signature = self._document_entries_signature(self.entries) + self.search_index.rebuild(self.entries) + self._apply_auto_refresh_timing() self.setWindowTitle("MDHelper") icon_path = self.base_window_icon_path if icon_path.exists(): @@ -451,12 +596,38 @@ class MainWindow(QMainWindow): pixmap = getattr(QStyle.StandardPixmap, standard_name, fallback) return self.style().standardIcon(pixmap) + def _panel_symbol_icon(self, symbol: str, color: str) -> QIcon: + pixmap = QPixmap(18, 18) + pixmap.fill(Qt.GlobalColor.transparent) + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + pen = QPen(QColor(color), 2) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + painter.setPen(pen) + + if symbol == "search": + painter.drawEllipse(4, 4, 8, 8) + painter.drawLine(11, 11, 15, 15) + elif symbol == "previous": + painter.drawLine(9, 3, 9, 15) + painter.drawLine(9, 3, 4, 8) + painter.drawLine(9, 3, 14, 8) + elif symbol == "next": + painter.drawLine(9, 3, 9, 15) + painter.drawLine(9, 15, 4, 10) + painter.drawLine(9, 15, 14, 10) + + painter.end() + return QIcon(pixmap) + def _build_ui(self) -> None: file_menu = self.menuBar().addMenu("文件") edit_menu = self.menuBar().addMenu("编辑") bookmarks_menu_root = self.menuBar().addMenu("书签") self.tools_menu = self.menuBar().addMenu("工具") self.theme_menu = self.menuBar().addMenu("主题") + self.style_menu = self.menuBar().addMenu("样式") self.about_menu = self.menuBar().addMenu("关于") self.back_action = QAction("后退", self) @@ -495,6 +666,14 @@ class MainWindow(QMainWindow): self.export_html_action.triggered.connect(self.export_current_html) file_menu.addAction(self.export_html_action) + self.export_docx_action = QAction("导出 DOCX", self) + self.export_docx_action.triggered.connect(self.export_current_docx) + file_menu.addAction(self.export_docx_action) + + self.export_mhtml_action = QAction("导出 MHTML", self) + self.export_mhtml_action.triggered.connect(self.export_current_mhtml) + file_menu.addAction(self.export_mhtml_action) + self.export_config_action = QAction("导出配置", self) self.export_config_action.triggered.connect(self.export_configuration) file_menu.addAction(self.export_config_action) @@ -565,6 +744,7 @@ class MainWindow(QMainWindow): self.about_menu.addAction(self.about_action) self._build_theme_menu() + self._build_style_menu() self.add_bookmark_action = QAction("添加书签", self) self.add_bookmark_action.setShortcut("Ctrl+D") @@ -583,6 +763,8 @@ class MainWindow(QMainWindow): self.find_result_label = QLabel("") self.find_result_label.setObjectName("panelSubTitle") self.find_result_label.setMinimumWidth(50) + self.find_result_label.setAlignment(Qt.AlignmentFlag.AlignRight) + self.find_result_label.hide() self.tree = QTreeWidget() self.tree.setObjectName("navigationTree") @@ -603,25 +785,37 @@ class MainWindow(QMainWindow): search_controls.setContentsMargins(0, 0, 0, 0) search_controls.setSpacing(6) self.panel_open_folder_button = QPushButton() - self.panel_open_folder_button.setObjectName("panelIconButton") + self.panel_open_folder_button.setObjectName("panelSearchButton") self.panel_open_folder_button.setIcon(self._standard_icon("SP_DirOpenIcon", QStyle.StandardPixmap.SP_DirOpenIcon)) + self.panel_open_folder_button.setIconSize(QSize(16, 16)) self.panel_open_folder_button.setToolTip("打开文件夹") self.panel_open_folder_button.clicked.connect(self.open_project_folder) - self.find_current_button = QPushButton("搜索") + self.panel_refresh_button = QPushButton() + self.panel_refresh_button.setObjectName("panelSearchButton") + self.panel_refresh_button.setIcon(self._standard_icon("SP_BrowserReload", QStyle.StandardPixmap.SP_BrowserReload)) + self.panel_refresh_button.setIconSize(QSize(16, 16)) + self.panel_refresh_button.setToolTip("刷新当前文档和文档列表") + self.panel_refresh_button.clicked.connect(self.refresh_project_view) + self.find_current_button = QPushButton() self.find_current_button.setObjectName("panelSearchButton") + self.find_current_button.setIconSize(QSize(16, 16)) + self.find_current_button.setToolTip("在当前页搜索") self.find_current_button.clicked.connect(self.find_next) - self.find_previous_button = QPushButton("上一个") + self.find_previous_button = QPushButton() self.find_previous_button.setObjectName("panelSearchButton") + self.find_previous_button.setIconSize(QSize(16, 16)) + self.find_previous_button.setToolTip("上一个匹配项") self.find_previous_button.clicked.connect(self.find_previous) - self.find_next_button = QPushButton("下一个") + self.find_next_button = QPushButton() self.find_next_button.setObjectName("panelSearchButton") + self.find_next_button.setIconSize(QSize(16, 16)) + self.find_next_button.setToolTip("下一个匹配项") self.find_next_button.clicked.connect(self.find_next) - search_controls.addWidget(self.panel_open_folder_button) - search_controls.addWidget(self.find_current_button) - search_controls.addWidget(self.find_previous_button) - search_controls.addWidget(self.find_next_button) - search_controls.addWidget(self.find_result_label) - search_controls.addStretch(1) + search_controls.addWidget(self.panel_open_folder_button, 1) + search_controls.addWidget(self.panel_refresh_button, 1) + search_controls.addWidget(self.find_current_button, 1) + search_controls.addWidget(self.find_previous_button, 1) + search_controls.addWidget(self.find_next_button, 1) self.search_results_label = QLabel("搜索结果") self.search_results_label.setObjectName("panelSubTitle") @@ -644,13 +838,24 @@ class MainWindow(QMainWindow): left_layout.addWidget(self._panel_title("文档", "本地帮助文件")) left_layout.addLayout(search_controls) left_layout.addWidget(self.search_box) + left_layout.addWidget(self.find_result_label) left_layout.addWidget(self.search_results_label) left_layout.addWidget(self.search_results) left_layout.addWidget(self.tree) + tab_bar = QTabBar() + tab_bar.setMovable(True) + tab_bar.setExpanding(False) + tab_bar.setUsesScrollButtons(True) + tab_bar.setElideMode(Qt.TextElideMode.ElideRight) + if hasattr(tab_bar, "setChangeCurrentOnDrag"): + tab_bar.setChangeCurrentOnDrag(False) + self.tabs = QTabWidget() + self.tabs.setTabBar(tab_bar) self.tabs.setDocumentMode(True) self.tabs.setTabsClosable(True) + self.tabs.setMovable(True) self.tabs.currentChanged.connect(self._on_tab_changed) self.tabs.tabCloseRequested.connect(self._close_tab) self.web_view = self._create_reader_view() @@ -694,6 +899,7 @@ class MainWindow(QMainWindow): status.addPermanentWidget(self.reading_progress) self._update_theme_menu_state() self._update_math_engine_actions() + self._apply_auto_refresh_timing() self._apply_ui_font() self._apply_navigation_style() self._update_recent_menu() @@ -750,6 +956,61 @@ class MainWindow(QMainWindow): self.document_font_size_menu.addAction(self.custom_document_font_size_action) self.document_font_size_group.triggered.connect(self.set_document_font_size_from_action) + def _build_style_menu(self) -> None: + self.style_menu.clear() + self.document_style_group = QActionGroup(self) + self.document_style_group.setExclusive(True) + + built_in_label = QAction("内置样式", self) + built_in_label.setEnabled(False) + self.style_menu.addAction(built_in_label) + for style_id, style in DOCUMENT_STYLE_PRESETS.items(): + action = QAction(str(style["name"]), self) + action.setCheckable(True) + action.setData(style_id) + self.document_style_group.addAction(action) + self.style_menu.addAction(action) + + self.style_menu.addSeparator() + custom_label = QAction("自定义样式", self) + custom_label.setEnabled(False) + self.style_menu.addAction(custom_label) + if self.custom_document_styles: + for style_id, style in sorted(self.custom_document_styles.items(), key=lambda item: item[1].get("name", item[0])): + action = QAction(str(style.get("name") or style_id), self) + action.setCheckable(True) + action.setData(style_id) + self.document_style_group.addAction(action) + self.style_menu.addAction(action) + else: + empty_action = QAction("无自定义样式", self) + empty_action.setEnabled(False) + self.style_menu.addAction(empty_action) + + self.style_menu.addSeparator() + self.new_custom_style_action = QAction("新建自定义样式...", self) + self.new_custom_style_action.triggered.connect(self.create_custom_document_style) + self.style_menu.addAction(self.new_custom_style_action) + + self.edit_custom_style_action = QAction("编辑当前自定义样式...", self) + self.edit_custom_style_action.triggered.connect(self.edit_current_custom_document_style) + self.style_menu.addAction(self.edit_custom_style_action) + + self.delete_custom_style_action = QAction("删除当前自定义样式", self) + self.delete_custom_style_action.triggered.connect(self.delete_current_custom_document_style) + self.style_menu.addAction(self.delete_custom_style_action) + + self.import_style_action = QAction("导入样式文件...", self) + self.import_style_action.triggered.connect(self.import_document_style) + self.style_menu.addAction(self.import_style_action) + + self.export_style_action = QAction("导出当前样式...", self) + self.export_style_action.triggered.connect(self.export_current_document_style) + self.style_menu.addAction(self.export_style_action) + + self.document_style_group.triggered.connect(self.set_document_style_from_action) + self._update_style_menu_state() + def _configure_web_settings(self, settings: QWebEngineSettings) -> None: attributes = QWebEngineSettings.WebAttribute settings.setAttribute(attributes.LocalContentCanAccessFileUrls, True) @@ -777,9 +1038,16 @@ class MainWindow(QMainWindow): web_view.setPage(page) page.setWebChannel(web_view.reader_channel) self._configure_web_settings(page.settings()) + web_view.set_wheel_scroll_speed(self.wheel_scroll_speed) web_view.loadFinished.connect(self._on_load_finished) return web_view + def _apply_wheel_scroll_speed_to_tabs(self) -> None: + for index in range(self.tabs.count()): + widget = self.tabs.widget(index) + if isinstance(widget, ReaderView): + widget.set_wheel_scroll_speed(self.wheel_scroll_speed) + def _prepare_target_tab(self, new_tab: bool, title: str) -> ReaderView: self._close_welcome_tab() if new_tab: @@ -847,8 +1115,10 @@ class MainWindow(QMainWindow): "欢迎", theme=self.theme, font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, ) @@ -928,6 +1198,13 @@ class MainWindow(QMainWindow): tree.setTextElideMode(Qt.TextElideMode.ElideRight) tree.setItemDelegate(CompactTreeDelegate(tree)) + def _normalized_wheel_scroll_speed(self, value: object) -> float: + try: + speed = float(value) + except (TypeError, ValueError): + return 1.0 + return max(WHEEL_SCROLL_SPEED_MIN, min(WHEEL_SCROLL_SPEED_MAX, speed)) + def _reader_theme_for_color(self, theme_color: str) -> str: return "dark" if theme_color in {"black", "dark_gray"} else "light" @@ -968,6 +1245,48 @@ class MainWindow(QMainWindow): def _theme_background_label(self) -> str: return dict(THEME_BACKGROUND_OPTIONS).get(self.theme_background, "无") + def _document_style_label(self, style_id: str | None = None) -> str: + style_id = style_id or self.document_style_id + if style_id in DOCUMENT_STYLE_PRESETS: + return str(DOCUMENT_STYLE_PRESETS[style_id]["name"]) + style = self.custom_document_styles.get(style_id, {}) + return str(style.get("name") or "自定义样式") + + def _document_style_css(self, style_id: str | None = None) -> str: + style_id = style_id or self.document_style_id + if style_id in DOCUMENT_STYLE_PRESETS: + return str(DOCUMENT_STYLE_PRESETS[style_id]["css"]) + style = self.custom_document_styles.get(style_id, {}) + if isinstance(style.get("rules"), dict) or "extra_css" in style: + return build_document_style_css( + style.get("rules") if isinstance(style.get("rules"), dict) else {}, + str(style.get("extra_css") or ""), + ) + return str(style.get("css") or "") + + def _set_document_style(self, style_id: str) -> None: + if style_id not in DOCUMENT_STYLE_PRESETS and style_id not in self.custom_document_styles: + style_id = "default" + if style_id == self.document_style_id: + self._update_style_menu_state() + return + self.document_style_id = style_id + self._update_style_menu_state() + self._save_preferences() + self.refresh_all_tab_appearances() + self.status_label.setText(f"文档样式已切换:{self._document_style_label()}") + + def _update_style_menu_state(self) -> None: + if self.document_style_id not in DOCUMENT_STYLE_PRESETS and self.document_style_id not in self.custom_document_styles: + self.document_style_id = "default" + if hasattr(self, "document_style_group"): + for action in self.document_style_group.actions(): + action.setChecked(action.data() == self.document_style_id) + if hasattr(self, "edit_custom_style_action"): + self.edit_custom_style_action.setEnabled(self.document_style_id in self.custom_document_styles) + if hasattr(self, "delete_custom_style_action"): + self.delete_custom_style_action.setEnabled(self.document_style_id in self.custom_document_styles) + def _update_theme_menu_state(self) -> None: if hasattr(self, "theme_color_group"): for action in self.theme_color_group.actions(): @@ -1102,6 +1421,9 @@ class MainWindow(QMainWindow): branch_closed_icon = self._stylesheet_url(self.resources_dir / "tree_closed.svg") branch_open_icon = self._stylesheet_url(self.resources_dir / "tree_open.svg") search_box_height = max(22, round(self.fontMetrics().height() * 1.5)) + progress_bg = palette["surface"] + progress_chunk = palette["selected"] + progress_text = palette["text"] pattern_style = "" chrome_pattern_style = "" if pattern_file: @@ -1134,15 +1456,15 @@ class MainWindow(QMainWindow): }} QProgressBar {{ - color: {text}; - background: {surface}; + color: {progress_text}; + background: {progress_bg}; border: 1px solid {border}; border-radius: 5px; text-align: center; }} QProgressBar::chunk {{ - background: {focus}; + background: {progress_chunk}; border-radius: 4px; }} @@ -1317,8 +1639,9 @@ class MainWindow(QMainWindow): }} QPushButton#panelSearchButton {{ + min-width: 0; min-height: 24px; - padding: 2px 8px; + padding: 2px; color: {text}; background: {surface}; border: 1px solid {border}; @@ -1410,6 +1733,10 @@ class MainWindow(QMainWindow): ) self._apply_window_title_bar_style(chrome_bg, text) self._apply_window_icon_style(chrome_bg, text) + if hasattr(self, "find_current_button"): + self.find_current_button.setIcon(self._panel_symbol_icon("search", text)) + self.find_previous_button.setIcon(self._panel_symbol_icon("previous", text)) + self.find_next_button.setIcon(self._panel_symbol_icon("next", text)) if hasattr(self, "tree"): self._refresh_tree_item_visuals() if hasattr(self, "tabs"): @@ -1509,7 +1836,9 @@ class MainWindow(QMainWindow): self.current_fragment = str(fragment_value) self.setWindowTitle(f"{self.current_file.name} - MDHelper") self.status_label.setText(self._display_path(self.current_file)) - if self.current_file.suffix.lower() in {".md", ".markdown"} and self.current_file.exists(): + if self.current_file.exists() and ( + self.current_file.suffix.lower() in {".md", ".markdown"} or is_code_document(self.current_file) + ): self._select_tree_item(self.current_file) self._populate_toc(self.current_file) else: @@ -1563,13 +1892,15 @@ class MainWindow(QMainWindow): title=path.name, theme=self.theme, font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, ) def _is_text_file(self, path: Path) -> bool: - if path.suffix.lower() in {".txt", ".log", ".csv", ".tsv", ".json", ".xml", ".html", ".htm", ".py", ".c", ".cpp", ".h", ".hpp"}: + if path.suffix.lower() in {".txt", ".log", ".csv", ".tsv", ".json", ".xml", ".html", ".htm", ".py", ".pyw", ".pyi", ".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".hpp"}: return True try: chunk = path.read_bytes()[:2048] @@ -1578,14 +1909,7 @@ class MainWindow(QMainWindow): return b"\x00" not in chunk def _read_text_preview(self, path: Path) -> str: - for encoding in ("utf-8", "utf-8-sig", "gbk"): - try: - return path.read_text(encoding=encoding) - except UnicodeDecodeError: - continue - except OSError as exc: - return f"读取失败:{exc}" - return path.read_text(encoding="utf-8", errors="replace") + return read_text_with_fallback(path, max_bytes=DEFAULT_TEXT_PREVIEW_BYTES) def _tree_is_dark_theme(self) -> bool: return self.theme == "dark" or self.theme_color in {"black", "dark_gray"} @@ -1607,14 +1931,14 @@ class MainWindow(QMainWindow): 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"}: + elif extension in {".py", ".pyw", ".pyi", ".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".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 + return path.suffix.lower() in document_extensions_for_groups(self.document_file_groups) def _document_tree_label(self, entry: DocumentEntry) -> str: if entry.path.suffix.lower() in {".md", ".markdown"} and self.document_tree_label_mode == "title": @@ -1662,6 +1986,16 @@ class MainWindow(QMainWindow): "ppt": "P", "pptx": "P", "py": "PY", + "pyw": "PY", + "pyi": "PY", + "c": "C", + "cc": "C++", + "cxx": "C++", + "cpp": "C++", + "h": "H", + "hh": "H++", + "hxx": "H++", + "hpp": "H++", } return labels.get(extension, extension[:2].upper() if extension else "F") @@ -1734,7 +2068,7 @@ class MainWindow(QMainWindow): 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: + def _find_or_create_folder_item(self, parent_item: QTreeWidgetItem, name: str, folder_path: Path | None = None) -> 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: @@ -1742,6 +2076,8 @@ class MainWindow(QMainWindow): folder_item = QTreeWidgetItem([name]) folder_item.setData(0, Qt.ItemDataRole.UserRole, None) + if folder_path is not None: + folder_item.setToolTip(0, str(folder_path)) self._style_folder_tree_item(folder_item) parent_item.addChild(folder_item) return folder_item @@ -1753,7 +2089,33 @@ class MainWindow(QMainWindow): children.sort(key=lambda child: (bool(child.data(0, Qt.ItemDataRole.UserRole)), child.text(0).casefold())) item.addChildren(children) + def _expanded_tree_keys(self) -> set[str]: + keys: set[str] = set() + + def visit(item: QTreeWidgetItem) -> None: + if item.isExpanded() and item.data(0, Qt.ItemDataRole.UserRole) is None: + keys.add(item.toolTip(0) or item.text(0)) + for child_index in range(item.childCount()): + visit(item.child(child_index)) + + for index in range(self.tree.topLevelItemCount()): + visit(self.tree.topLevelItem(index)) + return keys + + def _restore_tree_expanded_keys(self, keys: set[str]) -> None: + def visit(item: QTreeWidgetItem) -> None: + key = item.toolTip(0) or item.text(0) + if item.parent() is None or key in keys: + item.setExpanded(True) + for child_index in range(item.childCount()): + visit(item.child(child_index)) + + for index in range(self.tree.topLevelItemCount()): + visit(self.tree.topLevelItem(index)) + def _populate_tree(self) -> None: + expanded_keys = self._expanded_tree_keys() + selected_path = self.current_file self.tree.clear() self.path_to_item.clear() @@ -1776,12 +2138,17 @@ class MainWindow(QMainWindow): self._style_file_tree_item(item, entry.path) self.path_to_item[entry.path] = item parent_item = root_item + folder_path = self.project_root for part in entry.relative_path.split("/")[:-1]: - parent_item = self._find_or_create_folder_item(parent_item, part) + folder_path = folder_path / part + parent_item = self._find_or_create_folder_item(parent_item, part, folder_path) parent_item.addChild(item) self._sort_tree_children(root_item) root_item.setExpanded(True) + self._restore_tree_expanded_keys(expanded_keys) + if selected_path is not None: + self._select_tree_item(selected_path) def open_document_from_link(self, path: Path, fragment: str = "") -> None: if not path.exists(): @@ -1827,6 +2194,7 @@ class MainWindow(QMainWindow): self.project_root = self.app_root self.renderer = MarkdownRenderer(self.project_root) self.entries = [] + self.document_entries_signature = self._document_entries_signature(self.entries) self.search_index = SearchIndex(self.entries) self.path_to_item.clear() self.current_file = None @@ -1852,12 +2220,12 @@ class MainWindow(QMainWindow): self, "打开文件", str(self.project_root if self.has_project else Path.home()), - "Supported Files (*.md *.markdown *.html *.htm *.xhtml);;All Files (*)", + "Supported Files (*.md *.markdown *.html *.htm *.xhtml *.py *.pyw *.pyi *.c *.cc *.cxx *.cpp *.h *.hh *.hxx *.hpp);;All Files (*)", ) if file_name: path = Path(file_name).resolve() self.set_project_root(path.parent, save=True) - if path.suffix.lower() in {".md", ".markdown"}: + if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path): self._ensure_document_entry(path) self.open_document(path) elif path.suffix.lower() in {".html", ".htm", ".xhtml"}: @@ -1871,7 +2239,8 @@ class MainWindow(QMainWindow): self.project_root = project_root self.has_project = True self.renderer = MarkdownRenderer(self.project_root) - self.entries = discover_documents(self.project_root) + self.entries = discover_documents(self.project_root, self.document_file_groups) + self.document_entries_signature = self._document_entries_signature(self.entries) self.search_index.rebuild(self.entries) self.path_to_item.clear() self._populate_tree() @@ -1911,6 +2280,7 @@ class MainWindow(QMainWindow): font_scale=self.font_scale, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, original_source=disk_source, file_signature=self._file_signature(path), @@ -2084,7 +2454,8 @@ class MainWindow(QMainWindow): 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) + self.entries = discover_documents(self.project_root, self.document_file_groups) + self.document_entries_signature = self._document_entries_signature(self.entries) if path.exists() and all(entry.path != path for entry in self.entries): self._ensure_document_entry(path) else: @@ -2111,7 +2482,7 @@ class MainWindow(QMainWindow): if open_mode == "mdhelper-open=external": self._confirm_open_with_local_app_now(path) return - if is_markdown_url(url.toString()): + if is_markdown_url(url.toString()) or is_code_document(path): self.open_document(path, fragment=url.fragment(), new_tab=new_tab) elif is_qt_video_player_url(url.toString()): self._open_video_file_now(path, new_tab=new_tab or open_mode == "mdhelper-open=player-new-tab") @@ -2462,7 +2833,7 @@ class MainWindow(QMainWindow): QMessageBox.warning(self, "文件不存在", f"无法打开:\n{path}") return - if path.suffix.lower() in {".md", ".markdown"}: + if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path): self.open_document(path, new_tab=new_tab) return @@ -2531,11 +2902,13 @@ class MainWindow(QMainWindow): self.current_file, theme=self.theme, font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, ) - except OSError as exc: + except (OSError, UnicodeDecodeError) as exc: LOGGER.exception("Failed to render HTML export: %s", self.current_file) QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}") return @@ -2556,6 +2929,113 @@ class MainWindow(QMainWindow): LOGGER.info("HTML exported: %s", output_path) self.status_label.setText(f"HTML 已导出:{output_path}") + def export_current_docx(self) -> None: + if self.current_file is None: + return + labels = list(DOCX_EXPORT_ENGINES.values()) + label_to_engine = {label: engine for engine, label in DOCX_EXPORT_ENGINES.items()} + selected_label, accepted = QInputDialog.getItem( + self, + "选择 DOCX 导出方式", + "导出方式", + labels, + 0, + False, + ) + if not accepted: + return + engine = label_to_engine.get(selected_label, "pandoc") + default_name = self.current_file.with_suffix(".docx").name + file_name, _ = QFileDialog.getSaveFileName( + self, + "导出当前文档为 DOCX", + str(self.project_root / default_name), + "Word Documents (*.docx)", + ) + if not file_name: + return + self.export_docx_to_path(Path(file_name), engine=engine) + + def export_docx_to_path(self, output_path: Path, engine: str = "builtin") -> Path | None: + if self.current_file is None: + return None + if self.current_file.suffix.lower() not in {".md", ".markdown"}: + QMessageBox.warning(self, "导出失败", "DOCX 导出当前仅支持 Markdown 文档。") + return None + if output_path.suffix.lower() != ".docx": + output_path = output_path.with_suffix(".docx") + try: + source = self.current_file.read_text(encoding="utf-8") + export_markdown_to_docx(source, output_path, engine=engine, source_path=self.current_file) + except (OSError, zipfile.BadZipFile, DocxExportError) as exc: + LOGGER.exception("Failed to export DOCX: %s", output_path) + QMessageBox.warning(self, "导出失败", f"无法写入 DOCX 文件:\n{output_path}\n\n{exc}") + return None + + engine_label = DOCX_EXPORT_ENGINES.get(engine, DOCX_EXPORT_ENGINES["builtin"]) + LOGGER.info("DOCX exported via %s: %s", engine, output_path) + self.status_label.setText(f"DOCX 已导出({engine_label}):{output_path}") + return output_path + + def export_current_mhtml(self) -> None: + if self.current_file is None: + return + default_name = self.current_file.with_suffix(".mhtml").name + file_name, _ = QFileDialog.getSaveFileName( + self, + "导出当前页面为 MHTML", + str(self.project_root / default_name), + "MHTML Files (*.mhtml *.mht)", + ) + if not file_name: + return + self.export_mhtml_to_path(Path(file_name)) + + def export_mhtml_to_path(self, output_path: Path) -> Path | None: + if self.current_file is None: + return None + if output_path.suffix.lower() not in {".mhtml", ".mht"}: + output_path = output_path.with_suffix(".mhtml") + if self.current_file.suffix.lower() in {".md", ".markdown"}: + try: + content = self.renderer.render_file( + self.current_file, + theme=self.theme, + font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, + document_font_family=self.document_font_family, + document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), + math_engine=self.math_engine, + ) + except (OSError, UnicodeDecodeError) as exc: + LOGGER.exception("Failed to render MHTML export: %s", self.current_file) + QMessageBox.warning(self, "导出失败", f"无法渲染当前文档:\n{self.current_file}\n\n{exc}") + return None + self._write_exported_mhtml(output_path, content) + else: + self.web_view.page().toHtml(lambda content, target=output_path: self._write_exported_mhtml(target, content)) + LOGGER.info("Exporting MHTML: %s", output_path) + self.status_label.setText(f"正在导出 MHTML:{output_path}") + return output_path + + def _write_exported_mhtml(self, output_path: Path, content: str) -> None: + if output_path.suffix.lower() not in {".mhtml", ".mht"}: + output_path = output_path.with_suffix(".mhtml") + output_path.parent.mkdir(parents=True, exist_ok=True) + message = MIMEMultipart("related", type="text/html") + message["Subject"] = self.current_file.name if self.current_file is not None else output_path.stem + message["MIME-Version"] = "1.0" + message.attach(MIMEText(content, "html", "utf-8")) + try: + output_path.write_text(message.as_string(policy=email_default_policy), encoding="utf-8") + except OSError as exc: + LOGGER.exception("Failed to export MHTML: %s", output_path) + QMessageBox.warning(self, "导出失败", f"无法写入 MHTML 文件:\n{output_path}\n\n{exc}") + return + LOGGER.info("MHTML exported: %s", output_path) + self.status_label.setText(f"MHTML 已导出:{output_path}") + def export_configuration(self) -> None: default_path = self.project_root / "mdhelper_config.json" file_name, _ = QFileDialog.getSaveFileName( @@ -2611,6 +3091,8 @@ class MainWindow(QMainWindow): self._update_recent_menu() self._update_bookmarks_menu() self._update_math_engine_actions() + self._build_style_menu() + self._apply_auto_refresh_timing() self._apply_ui_font() self._update_theme_menu_state() self._apply_navigation_style() @@ -2641,14 +3123,20 @@ class MainWindow(QMainWindow): "theme_color": self.theme_color, "theme_background": self.theme_background, "font_scale": self.font_scale, + "wheel_scroll_speed": self.wheel_scroll_speed, "ui_font_family": self.ui_font_family, "ui_font_point_size": self.ui_font_point_size, "document_font_family": self.document_font_family, "document_font_size": self.document_font_size, + "document_style_id": self.document_style_id, + "custom_document_styles": self.custom_document_styles, "document_tree_label_mode": self.document_tree_label_mode, "math_engine": self.math_engine, "auto_refresh": self.auto_refresh_enabled, + "auto_refresh_mode": self.auto_refresh_mode, + "auto_refresh_delay_ms": self.auto_refresh_delay_ms, "non_preview_action": self.non_preview_action, + "document_file_groups": list(self.document_file_groups), }, "project_root": str(self.project_root) if self.has_project else "", "recent_files": [str(path) for path in self.recent_files], @@ -2679,6 +3167,9 @@ class MainWindow(QMainWindow): self.font_scale = max(0.8, min(1.6, float(reader.get("font_scale", self.font_scale)))) except (TypeError, ValueError): pass + self.wheel_scroll_speed = self._normalized_wheel_scroll_speed( + reader.get("wheel_scroll_speed", self.wheel_scroll_speed) + ) self.document_font_size = max(12, min(28, round(self.font_scale * 16))) try: self.document_font_size = max(12, min(28, int(reader.get("document_font_size", self.document_font_size)))) @@ -2692,11 +3183,34 @@ class MainWindow(QMainWindow): except (TypeError, ValueError): pass self.document_font_family = str(reader.get("document_font_family", self.document_font_family)).strip() + document_file_groups = reader.get("document_file_groups", self.document_file_groups) + self.document_file_groups = normalized_document_file_groups(document_file_groups) + + custom_styles = reader.get("custom_document_styles", self.custom_document_styles) + if isinstance(custom_styles, dict): + self.custom_document_styles = self._normalize_custom_document_styles(custom_styles) + style_id = str(reader.get("document_style_id", self.document_style_id)) + if style_id in DOCUMENT_STYLE_PRESETS or style_id in self.custom_document_styles: + self.document_style_id = style_id + else: + self.document_style_id = "default" 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)) + auto_refresh_mode = str(reader.get("auto_refresh_mode", self.auto_refresh_mode)) + if auto_refresh_mode in AUTO_REFRESH_MODES: + self.auto_refresh_mode = auto_refresh_mode + self.auto_refresh_enabled = auto_refresh_mode != "off" + elif not self.auto_refresh_enabled: + self.auto_refresh_mode = "off" + try: + delay = int(reader.get("auto_refresh_delay_ms", self.auto_refresh_delay_ms)) + if delay in AUTO_REFRESH_DELAY_VALUES: + self.auto_refresh_delay_ms = delay + except (TypeError, ValueError): + pass non_preview_action = str(reader.get("non_preview_action", self.non_preview_action)) if non_preview_action in {"ask", "open", "block"}: self.non_preview_action = non_preview_action @@ -2749,14 +3263,11 @@ class MainWindow(QMainWindow): self.set_project_root(path.parent, save=True) self._save_current_scroll_position() try: - html = self.renderer.render_file( - path, - theme=self.theme, - font_scale=self.font_scale, - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - math_engine=self.math_engine, - ) + html = self._render_document_file(path) + except UnicodeDecodeError as exc: + LOGGER.exception("Failed to decode document: %s", path) + QMessageBox.warning(self, "读取失败", f"无法按 UTF-8 读取 Markdown 文档:\n{path}\n\n{exc}") + return except OSError as exc: LOGGER.exception("Failed to read document: %s", path) QMessageBox.critical(self, "读取失败", f"无法读取文档:\n{path}\n\n{exc}") @@ -2804,6 +3315,36 @@ class MainWindow(QMainWindow): return False return True + def _render_document_file(self, path: Path) -> str: + if is_code_document(path): + return self.renderer.render_code_source( + self._read_text_preview(path), + path, + language=code_language_for_path(path), + theme=self.theme, + font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, + document_font_family=self.document_font_family, + document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), + math_engine=self.math_engine, + ) + + return self.renderer.render_file( + path, + theme=self.theme, + font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, + document_font_family=self.document_font_family, + document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), + math_engine=self.math_engine, + ) + + def refresh_project_view(self) -> None: + self._refresh_document_entries(force=True) + self.refresh_document() + def refresh_document(self) -> None: current = self.tabs.currentWidget() if isinstance(current, RichMarkdownEditorDialog): @@ -2812,6 +3353,7 @@ class MainWindow(QMainWindow): font_scale=self.font_scale, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, ) self.status_label.setText(f"编辑器显示已更新:{self._display_path(current.save_target_path)}") @@ -2826,7 +3368,7 @@ class MainWindow(QMainWindow): self.open_webpage_file(self.current_file) return - if self.current_file.suffix.lower() not in {".md", ".markdown"}: + if self.current_file.suffix.lower() not in {".md", ".markdown"} and not is_code_document(self.current_file): if media_kind(self.current_file.as_uri()) in {"image", "gif", "audio", "video"}: self._open_preview_file_now(self.current_file) else: @@ -2868,6 +3410,7 @@ class MainWindow(QMainWindow): font_scale=self.font_scale, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self._document_style_css(), math_engine=self.math_engine, ) return @@ -2886,17 +3429,10 @@ class MainWindow(QMainWindow): if not path.exists(): return - if path.suffix.lower() in {".md", ".markdown"}: + if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path): try: - page_html = self.renderer.render_file( - path, - theme=self.theme, - font_scale=self.font_scale, - document_font_family=self.document_font_family, - document_font_size=self.document_font_size, - math_engine=self.math_engine, - ) - except OSError: + page_html = self._render_document_file(path) + except (OSError, UnicodeDecodeError): LOGGER.exception("Failed to refresh tab appearance: %s", path) return base_path = str(path.parent.resolve()) + os.sep @@ -2969,6 +3505,173 @@ class MainWindow(QMainWindow): self._save_preferences() self.refresh_all_tab_appearances() + def set_document_style_from_action(self, action: QAction) -> None: + self._set_document_style(str(action.data() or "default")) + + def create_custom_document_style(self) -> None: + dialog = DocumentStyleEditorDialog(default_name="自定义样式", parent=self) + dialog.apply_theme(self.theme_color) + if dialog.exec() != QDialog.DialogCode.Accepted: + return + payload = dialog.style_payload() + name = str(payload["name"]) + style_id = self._unique_custom_style_id(name) + self.custom_document_styles[style_id] = self._normalize_document_style_payload(payload) + self.document_style_id = style_id + self._build_style_menu() + self._save_preferences() + self.refresh_all_tab_appearances() + self.status_label.setText(f"自定义样式已创建:{name}") + + def edit_current_custom_document_style(self) -> None: + style = self.custom_document_styles.get(self.document_style_id) + if not style: + QMessageBox.information(self, "编辑样式", "请先选择一个自定义样式。") + return + dialog = DocumentStyleEditorDialog(style, parent=self) + dialog.apply_theme(self.theme_color) + if dialog.exec() != QDialog.DialogCode.Accepted: + return + payload = dialog.style_payload() + name = str(payload["name"]) + self.custom_document_styles[self.document_style_id] = self._normalize_document_style_payload(payload) + self._build_style_menu() + self._save_preferences() + self.refresh_all_tab_appearances() + self.status_label.setText(f"自定义样式已更新:{name}") + + def delete_current_custom_document_style(self) -> None: + style_id = self.document_style_id + style = self.custom_document_styles.get(style_id) + if not style: + QMessageBox.information(self, "删除样式", "内置样式不能删除,请先选择一个自定义样式。") + return + name = str(style.get("name") or "自定义样式") + choice = QMessageBox.question( + self, + "删除样式", + f"确定删除自定义样式“{name}”吗?", + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, + QMessageBox.StandardButton.No, + ) + if choice != QMessageBox.StandardButton.Yes: + return + self.custom_document_styles.pop(style_id, None) + self.document_style_id = "default" + self._build_style_menu() + self._save_preferences() + self.refresh_all_tab_appearances() + self.status_label.setText(f"自定义样式已删除:{name}") + + def import_document_style(self) -> None: + file_name, _ = QFileDialog.getOpenFileName( + self, + "导入样式文件", + str(self.project_root), + "MDHelper Style Files (*.mdhelper-style *.json);;All Files (*)", + ) + if not file_name: + return + try: + style_id = self._import_document_style_file(Path(file_name)) + except (OSError, json.JSONDecodeError, ValueError) as exc: + QMessageBox.warning(self, "导入失败", f"无法导入样式文件:\n{file_name}\n\n{exc}") + return + self.document_style_id = style_id + self._build_style_menu() + self._save_preferences() + self.refresh_all_tab_appearances() + self.status_label.setText(f"样式已导入:{self._document_style_label(style_id)}") + + def export_current_document_style(self) -> None: + default_name = f"{self._safe_style_name(self._document_style_label())}.mdhelper-style" + file_name, _ = QFileDialog.getSaveFileName( + self, + "导出当前样式", + str(self.project_root / default_name), + "MDHelper Style Files (*.mdhelper-style);;JSON Files (*.json)", + ) + if not file_name: + return + output_path = Path(file_name) + if output_path.suffix.lower() not in {".mdhelper-style", ".json"}: + output_path = output_path.with_suffix(".mdhelper-style") + try: + self._write_document_style_file(output_path, self.document_style_id) + except OSError as exc: + QMessageBox.warning(self, "导出失败", f"无法写入样式文件:\n{output_path}\n\n{exc}") + return + self.status_label.setText(f"样式已导出:{output_path}") + + def _style_payload_for_id(self, style_id: str) -> dict[str, object]: + if style_id in DOCUMENT_STYLE_PRESETS: + style = DOCUMENT_STYLE_PRESETS[style_id] + else: + style = self.custom_document_styles.get(style_id) + if not style: + raise ValueError("样式不存在。") + payload: dict[str, object] = { + "app": "MDHelper", + "type": "document_style", + "name": str(style.get("name") or "自定义样式"), + "css": self._document_style_css(style_id), + } + if isinstance(style.get("rules"), dict): + payload["rules"] = style["rules"] + if "extra_css" in style: + payload["extra_css"] = str(style.get("extra_css") or "") + return payload + + def _write_document_style_file(self, output_path: Path, style_id: str) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(self._style_payload_for_id(style_id), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + + def _import_document_style_file(self, style_path: Path) -> str: + payload = json.loads(style_path.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + raise ValueError("样式文件格式不正确。") + name = str(payload.get("name") or style_path.stem).strip() + if not name: + raise ValueError("样式文件需要包含 name。") + style_id = self._unique_custom_style_id(name) + self.custom_document_styles[style_id] = self._normalize_document_style_payload(payload, fallback_name=name) + return style_id + + def _unique_custom_style_id(self, name: str) -> str: + base = self._safe_style_name(name) or "custom" + style_id = f"custom:{base}" + suffix = 2 + while style_id in self.custom_document_styles or style_id in DOCUMENT_STYLE_PRESETS: + style_id = f"custom:{base}-{suffix}" + suffix += 1 + return style_id + + def _safe_style_name(self, name: str) -> str: + safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff._-]+", "-", name.strip()).strip("-._") + return safe or "style" + + def _normalize_document_style_payload( + self, + payload: dict[str, object], + fallback_name: str = "自定义样式", + ) -> dict[str, object]: + name = str(payload.get("name") or fallback_name).strip() or "自定义样式" + rules = payload.get("rules") + normalized_rules = rules if isinstance(rules, dict) else {} + extra_css = str(payload.get("extra_css") or "").strip() + css = build_document_style_css(normalized_rules, extra_css) + if not css: + css = str(payload.get("css") or "").strip() + style: dict[str, object] = {"name": name, "css": css} + if normalized_rules: + style["rules"] = normalized_rules + if extra_css: + style["extra_css"] = extra_css + return style + def choose_interface_font(self) -> None: current = QApplication.instance().font() if QApplication.instance() is not None else QFont() font, accepted = QFontDialog.getFont(current, self, "选择界面字体") @@ -3063,8 +3766,12 @@ class MainWindow(QMainWindow): theme_color=self.theme_color, theme_background=self.theme_background, font_scale=self.font_scale, + wheel_scroll_speed=self.wheel_scroll_speed, auto_refresh=self.auto_refresh_enabled, + auto_refresh_mode=self.auto_refresh_mode, + auto_refresh_delay_ms=self.auto_refresh_delay_ms, non_preview_action=self.non_preview_action, + document_file_groups=self.document_file_groups, ), self, ) @@ -3078,16 +3785,27 @@ class MainWindow(QMainWindow): or preferences.theme_background != self.theme_background ) font_changed = abs(preferences.font_scale - self.font_scale) > 0.001 + wheel_changed = abs(preferences.wheel_scroll_speed - self.wheel_scroll_speed) > 0.001 self._set_theme_color(preferences.theme_color) self.theme_background = self._normalized_theme_background(preferences.theme_background) self.font_scale = preferences.font_scale + self.wheel_scroll_speed = self._normalized_wheel_scroll_speed(preferences.wheel_scroll_speed) self.document_font_size = max(12, min(28, round(self.font_scale * 16))) self.auto_refresh_enabled = preferences.auto_refresh + self.auto_refresh_mode = preferences.auto_refresh_mode + self.auto_refresh_delay_ms = preferences.auto_refresh_delay_ms + file_groups_changed = preferences.document_file_groups != self.document_file_groups self.non_preview_action = preferences.non_preview_action + self.document_file_groups = preferences.document_file_groups + if file_groups_changed: + self._refresh_document_entries(force=True) + self._apply_auto_refresh_timing() self._update_theme_menu_state() self._apply_navigation_style() self._save_preferences() + if wheel_changed: + self._apply_wheel_scroll_speed_to_tabs() if theme_changed or font_changed: self.refresh_document() LOGGER.info("Updated preferences: %s", preferences) @@ -3114,6 +3832,7 @@ class MainWindow(QMainWindow): text = self.search_box.text() if not text: self.find_result_label.clear() + self.find_result_label.hide() return flags = QWebEnginePage.FindFlag(0) if backward: @@ -3131,6 +3850,7 @@ class MainWindow(QMainWindow): self.find_result_label.setText("0/0") else: self.find_result_label.setText(f"{active}/{total}") + self.find_result_label.show() def clear_recent_files(self) -> None: self.recent_files.clear() @@ -3411,6 +4131,9 @@ 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: + if is_code_document(path): + self._populate_toc_items(extract_code_headings(path, self._read_text_preview(path))) + return self._populate_toc_items(extract_headings(path)) def _populate_toc_from_text(self, source: str) -> None: @@ -3487,6 +4210,7 @@ class MainWindow(QMainWindow): relative_path = str(path) self.entries.append(DocumentEntry(path=path, title=title, relative_path=relative_path)) + self.document_entries_signature = self._document_entries_signature(self.entries) self.search_index.rebuild(self.entries) self._populate_tree() self._filter_tree(self.search_box.text()) @@ -3572,6 +4296,9 @@ class MainWindow(QMainWindow): if self.math_engine not in {"katex", "mathjax"}: self.math_engine = "katex" self.font_scale = float(self.settings.value("reader/font_scale", 1.0)) + self.wheel_scroll_speed = self._normalized_wheel_scroll_speed( + self.settings.value("reader/wheel_scroll_speed", 1.0) + ) self.document_font_size = max(12, min(28, round(self.font_scale * 16))) try: self.document_font_size = max(12, min(28, int(self.settings.value("reader/document_font_size", self.document_font_size)))) @@ -3584,10 +4311,29 @@ 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_style_id = str(self.settings.value("reader/document_style_id", "default")) + custom_styles = self._load_json_setting(CUSTOM_DOCUMENT_STYLES_SETTING_KEY, {}) + self.custom_document_styles = self._normalize_custom_document_styles(custom_styles) + if self.document_style_id not in DOCUMENT_STYLE_PRESETS and self.document_style_id not in self.custom_document_styles: + self.document_style_id = "default" + self.document_file_groups = normalized_document_file_groups( + self._load_json_setting("reader/document_file_groups", list(DEFAULT_DOCUMENT_FILE_GROUPS)) + ) 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.auto_refresh_mode = str(self.settings.value("reader/auto_refresh_mode", "all" if self.auto_refresh_enabled else "off")) + if self.auto_refresh_mode not in AUTO_REFRESH_MODES: + self.auto_refresh_mode = "all" if self.auto_refresh_enabled else "off" + if self.auto_refresh_mode == "off": + self.auto_refresh_enabled = False + try: + self.auto_refresh_delay_ms = int(self.settings.value("reader/auto_refresh_delay_ms", 1000)) + except (TypeError, ValueError): + self.auto_refresh_delay_ms = 1000 + if self.auto_refresh_delay_ms not in AUTO_REFRESH_DELAY_VALUES: + self.auto_refresh_delay_ms = 1000 self.non_preview_action = str(self.settings.value("reader/non_preview_action", "ask")) if self.non_preview_action not in {"ask", "open", "block"}: self.non_preview_action = "ask" @@ -3616,19 +4362,38 @@ class MainWindow(QMainWindow): if isinstance(draft, dict) and isinstance(draft.get("source"), str) } + def _apply_auto_refresh_timing(self) -> None: + if hasattr(self, "refresh_timer"): + self.refresh_timer.setInterval(self.auto_refresh_delay_ms) + if hasattr(self, "tree_refresh_timer"): + self.tree_refresh_timer.setInterval(self.auto_refresh_delay_ms) + if not self.auto_refresh_enabled or self.auto_refresh_mode == "off": + if hasattr(self, "refresh_timer"): + self.refresh_timer.stop() + if hasattr(self, "tree_refresh_timer"): + self.tree_refresh_timer.stop() + self.pending_changed_files.clear() + self.pending_directory_refresh = False + def _save_preferences(self) -> None: self.settings.setValue("reader/theme", self.theme) self.settings.setValue("reader/theme_color", self.theme_color) self.settings.setValue("reader/theme_background", self.theme_background) self.settings.setValue("reader/math_engine", self.math_engine) self.settings.setValue("reader/font_scale", self.font_scale) + self.settings.setValue("reader/wheel_scroll_speed", self.wheel_scroll_speed) self.settings.setValue("reader/ui_font_family", self.ui_font_family) self.settings.setValue("reader/ui_font_point_size", self.ui_font_point_size) self.settings.setValue("reader/document_font_family", self.document_font_family) self.settings.setValue("reader/document_font_size", self.document_font_size) + self.settings.setValue("reader/document_style_id", self.document_style_id) + self.settings.setValue(CUSTOM_DOCUMENT_STYLES_SETTING_KEY, json.dumps(self.custom_document_styles, ensure_ascii=False)) 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/auto_refresh_mode", self.auto_refresh_mode) + self.settings.setValue("reader/auto_refresh_delay_ms", self.auto_refresh_delay_ms) self.settings.setValue("reader/non_preview_action", self.non_preview_action) + self.settings.setValue("reader/document_file_groups", json.dumps(list(self.document_file_groups), ensure_ascii=False)) 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]) @@ -3664,6 +4429,22 @@ class MainWindow(QMainWindow): except json.JSONDecodeError: return fallback + def _normalize_custom_document_styles(self, value: object) -> dict[str, dict[str, object]]: + if not isinstance(value, dict): + return {} + styles: dict[str, dict[str, object]] = {} + for style_id, style in value.items(): + if not isinstance(style, dict): + continue + normalized_style = self._normalize_document_style_payload(style) + if not str(normalized_style.get("name") or "").strip(): + continue + normalized_id = str(style_id) + if not normalized_id.startswith("custom:"): + normalized_id = self._unique_custom_style_id(str(normalized_style.get("name") or "自定义样式")) + styles[normalized_id] = normalized_style + return styles + def _save_current_scroll_position(self) -> None: if self.current_file is None: return @@ -3692,35 +4473,161 @@ class MainWindow(QMainWindow): if watched_dirs: self.file_watcher.removePaths(watched_dirs) - if not self.has_project: + if not self.has_project or not self.auto_refresh_enabled or self.auto_refresh_mode == "off": return paths: set[Path] = set() - directories: set[Path] = {self.project_root} + directories: set[Path] = set() docs_dir = self.project_root / "docs" media_dir = self.project_root / "media" - if docs_dir.exists(): + if self._auto_refresh_allows("directory"): + directories.add(self.project_root) + if self._auto_refresh_allows("directory") and docs_dir.exists(): directories.add(docs_dir) - if media_dir.exists(): + if self._auto_refresh_allows("resource") and media_dir.exists(): directories.add(media_dir) sample = self.project_root / "sample.md" if sample.exists(): paths.add(sample.resolve()) + open_paths = self._open_tab_file_paths() if self.current_file is not None: - paths.add(self.current_file) - directories.add(self.current_file.parent) - paths.update(self._referenced_local_paths(self.current_file)) + open_paths.add(self.current_file) - file_paths = [str(path) for path in paths if path.exists() and path.is_file()] + for open_path in open_paths: + paths.add(open_path) + if ( + self._auto_refresh_allows("current") + or self._auto_refresh_allows("resource") + or self._auto_refresh_allows("directory") + ): + directories.add(open_path.parent) + if self._auto_refresh_allows("resource") and open_path.suffix.lower() in {".md", ".markdown"}: + paths.update(self._referenced_local_paths(open_path)) + + normalized_paths = {path.resolve() for path in paths if path.exists() and path.is_file()} + self.watched_file_signatures = { + path: self.watched_file_signatures.get(path, self._file_signature(path)) + for path in normalized_paths + } + file_paths = [str(path) for path in normalized_paths] dir_paths = [str(path) for path in directories if path.exists() and path.is_dir()] if file_paths: self.file_watcher.addPaths(file_paths) if dir_paths: self.file_watcher.addPaths(dir_paths) + def _document_entries_signature(self, entries: list[DocumentEntry]) -> tuple[tuple[str, str], ...]: + return tuple(sorted((str(entry.path), entry.title) for entry in entries)) + + def _watched_file_really_changed(self, path: Path) -> bool: + had_previous = path in self.watched_file_signatures + previous = self.watched_file_signatures.get(path) + current = self._file_signature(path) + self.watched_file_signatures[path] = current + if not had_previous: + return False + return previous != current + + def _auto_refresh_allows(self, target: str) -> bool: + if not self.auto_refresh_enabled or self.auto_refresh_mode == "off": + return False + if target == "current": + return self.auto_refresh_mode in {"current", "resources", "all"} + if target == "resource": + return self.auto_refresh_mode in {"resources", "all"} + if target == "directory": + return self.auto_refresh_mode == "all" + return False + + def _open_tab_file_paths(self) -> set[Path]: + paths: set[Path] = set() + if not hasattr(self, "tabs"): + return paths + for index in range(self.tabs.count()): + widget = self.tabs.widget(index) + if widget is None or bool(widget.property("is_welcome")): + continue + file_value = widget.property("current_file") + if not file_value: + continue + try: + paths.add(Path(str(file_value)).resolve()) + except OSError: + continue + return paths + + def _reader_tabs_for_path(self, path: Path) -> list[ReaderView]: + path = path.resolve() + tabs: list[ReaderView] = [] + for index in range(self.tabs.count()): + widget = self.tabs.widget(index) + if not isinstance(widget, ReaderView) or bool(widget.property("is_welcome")): + continue + file_value = widget.property("current_file") + if not file_value: + continue + try: + tab_path = Path(str(file_value)).resolve() + except OSError: + continue + if tab_path == path: + tabs.append(widget) + return tabs + + def _open_document_reference_paths(self, document_paths: set[Path]) -> dict[Path, set[Path]]: + if not self._auto_refresh_allows("resource"): + return {} + return { + path: self._referenced_local_paths(path) + for path in document_paths + if path.suffix.lower() in {".md", ".markdown"} and path.exists() + } + + def _documents_affected_by_changed_paths( + self, + changed_paths: set[Path], + open_paths: set[Path] | None = None, + reference_paths_by_document: dict[Path, set[Path]] | None = None, + ) -> set[Path]: + if not changed_paths: + return set() + active_open_paths = open_paths or self._open_tab_file_paths() + references = ( + reference_paths_by_document + if reference_paths_by_document is not None + else self._open_document_reference_paths(active_open_paths) + ) + affected = active_open_paths & changed_paths + if self._auto_refresh_allows("resource"): + for document_path, reference_paths in references.items(): + if reference_paths & changed_paths: + affected.add(document_path) + return affected + + def _refresh_open_document_tabs(self, document_paths: set[Path]) -> None: + if not document_paths: + self._update_watched_paths() + return + + current = self.tabs.currentWidget() + current_path = self.current_file.resolve() if self.current_file is not None else None + refreshed_current = False + for path in sorted(document_paths, key=lambda item: str(item)): + if current_path is not None and path == current_path: + self.refresh_document() + refreshed_current = True + continue + for reader_tab in self._reader_tabs_for_path(path): + if reader_tab is current: + continue + self._refresh_tab_appearance(reader_tab) + + if not refreshed_current: + self._update_watched_paths() + def _referenced_local_paths(self, markdown_path: Path) -> set[Path]: try: source = markdown_path.read_text(encoding="utf-8") @@ -3739,47 +4646,102 @@ class MainWindow(QMainWindow): return paths def _on_watched_file_changed(self, changed_path: str) -> None: - if not self.auto_refresh_enabled: + if not self.auto_refresh_enabled or self.auto_refresh_mode == "off": 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: + if not self._watched_file_really_changed(changed): + self._update_watched_paths() + return + self.pending_changed_files.add(changed) + if self._documents_affected_by_changed_paths({changed}): self.refresh_timer.start() - elif self.current_file is not None and changed in self._referenced_local_paths(self.current_file): - self.refresh_timer.start() - self._update_watched_paths() + elif self._auto_refresh_allows("directory") and self._is_supported_document_path(changed): + self.pending_directory_refresh = True + self.tree_refresh_timer.start() def _on_watched_directory_changed(self, changed_path: str) -> None: - if not self.auto_refresh_enabled or not self.has_project: + if not self.auto_refresh_enabled or self.auto_refresh_mode == "off" or not self.has_project: return changed = Path(changed_path).resolve() docs_dir = (self.project_root / "docs").resolve() - if changed in {self.project_root, docs_dir}: + if self._auto_refresh_allows("directory") and changed in {self.project_root, docs_dir}: + self.pending_directory_refresh = True self.tree_refresh_timer.start() + open_paths = self._open_tab_file_paths() if self.current_file is not None: - media_dir = (self.project_root / "media").resolve() - if changed in {self.current_file.parent.resolve(), media_dir}: - self.refresh_timer.start() - self._update_watched_paths() + open_paths.add(self.current_file) + watched_content_dirs = {path.parent.resolve() for path in open_paths} + if self._auto_refresh_allows("resource"): + watched_content_dirs.add((self.project_root / "media").resolve()) + if changed in watched_content_dirs: + self.refresh_timer.start() def _auto_refresh_current_document(self) -> None: + open_paths = {path for path in self._open_tab_file_paths() if path.exists()} if self.current_file is not None and self.current_file.exists(): - self.refresh_document() + open_paths.add(self.current_file) - def _refresh_document_entries(self) -> None: + if not open_paths: + self.pending_changed_files.clear() + self._update_watched_paths() + return + + reference_paths_by_document = self._open_document_reference_paths(open_paths) + refresh_paths = set(open_paths) + for reference_paths in reference_paths_by_document.values(): + refresh_paths.update(reference_paths) + + signature_changed_paths = { + path + for path in refresh_paths + if path.exists() and self._watched_file_really_changed(path) + } + changed_paths = { + path.resolve() + for path in self.pending_changed_files + if path.exists() + } | signature_changed_paths + affected_documents = self._documents_affected_by_changed_paths( + changed_paths, + open_paths=open_paths, + reference_paths_by_document=reference_paths_by_document, + ) + self.pending_changed_files.clear() + if affected_documents: + self._refresh_open_document_tabs(affected_documents) + if ( + self._auto_refresh_allows("directory") + and any(self._is_supported_document_path(path) for path in affected_documents) + ): + self._refresh_document_entries() + else: + self._update_watched_paths() + + def _refresh_document_entries(self, force: bool = False) -> None: if not self.has_project: return previous_current = self.current_file - self.entries = discover_documents(self.project_root) + entries = discover_documents(self.project_root, self.document_file_groups) + signature = self._document_entries_signature(entries) + if not force and not self.pending_directory_refresh and signature == self.document_entries_signature: + self._update_watched_paths() + return + + self.pending_directory_refresh = False + self.document_entries_signature = signature + self.entries = entries self.search_index.rebuild(self.entries) - if ( + should_preserve_current = ( previous_current is not None and previous_current.exists() + and self._is_supported_document_path(previous_current) and all(entry.path != previous_current for entry in self.entries) - ): + ) + if should_preserve_current: self._ensure_document_entry(previous_current) else: self._populate_tree() diff --git a/mdhelper/markdown_editor.py b/mdhelper/markdown_editor.py index 6cdf74f..a502b70 100644 --- a/mdhelper/markdown_editor.py +++ b/mdhelper/markdown_editor.py @@ -45,6 +45,9 @@ from .markdown_renderer import MarkdownRenderer from .markdown_utils import slugify_heading +MAX_SYNTAX_HIGHLIGHT_CHARS = 1_000_000 + + class LineNumberArea(QWidget): def __init__(self, editor: "MarkdownSourceEditor") -> None: super().__init__(editor) @@ -237,7 +240,8 @@ class MarkdownEditorDialog(QDialog): font_scale: float, document_font_family: str, document_font_size: int, - math_engine: str, + document_style_css: str = "", + math_engine: str = "katex", original_source: str | None = None, file_signature: tuple[int, int] | None = None, draft_callback: Callable[[str], None] | None = None, @@ -255,6 +259,7 @@ class MarkdownEditorDialog(QDialog): self.font_scale = font_scale self.document_font_family = document_font_family self.document_font_size = document_font_size + self.document_style_css = document_style_css self.math_engine = math_engine self.file_signature = file_signature self.draft_callback = draft_callback @@ -340,7 +345,11 @@ class MarkdownEditorDialog(QDialog): editor_font.setStyleHint(QFont.StyleHint.Monospace) self.editor.setFont(editor_font) self._apply_editor_font() - self.highlighter = MarkdownSyntaxHighlighter(self.editor.document()) + self.highlighter = ( + MarkdownSyntaxHighlighter(self.editor.document()) + if len(source) <= MAX_SYNTAX_HIGHLIGHT_CHARS + else None + ) 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) @@ -401,7 +410,8 @@ class MarkdownEditorDialog(QDialog): def apply_theme(self, dark: bool) -> None: self.editor.apply_theme(dark) - self.highlighter.apply_theme(dark) + if self.highlighter is not None: + self.highlighter.apply_theme(dark) if dark: self.setStyleSheet( "QDialog { background: #1f242b; color: #dbe2ea; }" @@ -425,12 +435,14 @@ class MarkdownEditorDialog(QDialog): font_scale: float, document_font_family: str, document_font_size: int, - math_engine: str, + document_style_css: str = "", + math_engine: str = "katex", ) -> None: self.theme = theme self.font_scale = font_scale self.document_font_family = document_font_family self.document_font_size = document_font_size + self.document_style_css = document_style_css self.math_engine = math_engine self.apply_theme(theme == "dark") self._apply_editor_font() @@ -716,6 +728,7 @@ class MarkdownEditorDialog(QDialog): font_scale=self.font_scale, document_font_family=self.document_font_family, document_font_size=self.document_font_size, + document_style_css=self.document_style_css, math_engine=self.math_engine, ) base_path = str(self.save_target_path.parent.resolve()) + os.sep diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index c2e059a..097b4aa 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -9,8 +9,9 @@ from urllib.parse import unquote, urlsplit from markdown_it import MarkdownIt from markdown_it.token import Token from pygments import highlight -from pygments.formatters import HtmlFormatter -from pygments.lexers import TextLexer, get_lexer_by_name +from pygments.formatters.html import HtmlFormatter +from pygments.lexers import get_lexer_by_name +from pygments.lexers.special import TextLexer from pygments.util import ClassNotFound from .markdown_utils import slugify_heading @@ -44,8 +45,10 @@ class MarkdownRenderer: markdown_path: Path, theme: str = "light", font_scale: float = 1.0, + wheel_scroll_speed: float = 1.0, document_font_family: str = "", document_font_size: int | None = None, + document_style_css: str = "", math_engine: str = "katex", ) -> str: source = markdown_path.read_text(encoding="utf-8") @@ -55,8 +58,10 @@ class MarkdownRenderer: title=markdown_path.name, theme=theme, font_scale=font_scale, + wheel_scroll_speed=wheel_scroll_speed, document_font_family=document_font_family, document_font_size=document_font_size, + document_style_css=document_style_css, math_engine=math_engine, ) @@ -66,8 +71,10 @@ class MarkdownRenderer: markdown_path: Path, theme: str = "light", font_scale: float = 1.0, + wheel_scroll_speed: float = 1.0, document_font_family: str = "", document_font_size: int | None = None, + document_style_css: str = "", math_engine: str = "katex", ) -> str: body = self.markdown.render(source, {"path": str(markdown_path)}) @@ -76,8 +83,46 @@ class MarkdownRenderer: title=markdown_path.name, theme=theme, font_scale=font_scale, + wheel_scroll_speed=wheel_scroll_speed, document_font_family=document_font_family, document_font_size=document_font_size, + document_style_css=document_style_css, + math_engine=math_engine, + ) + + def render_code_source( + self, + source: str, + code_path: Path, + language: str = "text", + theme: str = "light", + font_scale: float = 1.0, + wheel_scroll_speed: float = 1.0, + document_font_family: str = "", + document_font_size: int | None = None, + document_style_css: str = "", + math_engine: str = "katex", + ) -> str: + label = html.escape(language or code_path.suffix.lstrip(".") or "text") + language_class = f" language-{html.escape(language)}" if language else "" + highlighted = self._highlight_code(source, language, line_anchors=True) + title = html.escape(code_path.name) + body = ( + f"

{title}

" + '
' + f'
{label}
' + f'
{highlighted}
' + "
" + ) + return self._wrap_html( + body=body, + title=code_path.name, + theme=theme, + font_scale=font_scale, + wheel_scroll_speed=wheel_scroll_speed, + document_font_family=document_font_family, + document_font_size=document_font_size, + document_style_css=document_style_css, math_engine=math_engine, ) @@ -87,8 +132,10 @@ class MarkdownRenderer: title: str, theme: str = "light", font_scale: float = 1.0, + wheel_scroll_speed: float = 1.0, document_font_family: str = "", document_font_size: int | None = None, + document_style_css: str = "", math_engine: str = "katex", ) -> str: return self._wrap_html( @@ -96,8 +143,10 @@ class MarkdownRenderer: title=title, theme=theme, font_scale=font_scale, + wheel_scroll_speed=wheel_scroll_speed, document_font_family=document_font_family, document_font_size=document_font_size, + document_style_css=document_style_css, math_engine=math_engine, ) @@ -263,16 +312,25 @@ class MarkdownRenderer: uri = f"{uri}#{parsed.fragment}" return uri - def _highlight_code(self, code: str, language: str) -> str: + def _highlight_code(self, code: str, language: str, line_anchors: bool = False) -> str: normalized = language.lower() if normalized in {"pseudocode", "pseudo"}: - return self._highlight_pseudocode(code) + highlighted = self._highlight_pseudocode(code) + return self._add_line_anchors(highlighted) if line_anchors else highlighted try: lexer = get_lexer_by_name(normalized) if normalized else TextLexer() except ClassNotFound: lexer = TextLexer() - return highlight(code, lexer, self.formatter) + highlighted = highlight(code, lexer, self.formatter) + return self._add_line_anchors(highlighted) if line_anchors else highlighted + + def _add_line_anchors(self, highlighted: str) -> str: + lines = highlighted.splitlines(keepends=True) + return "".join( + f'{line}' + for index, line in enumerate(lines, start=1) + ) def _highlight_pseudocode(self, code: str) -> str: escaped = html.escape(code) @@ -437,8 +495,10 @@ class MarkdownRenderer: title: str, theme: str, font_scale: float, + wheel_scroll_speed: float, document_font_family: str, document_font_size: int | None, + document_style_css: str, math_engine: str, ) -> str: css = (self.resources_dir / "reader.css").read_text(encoding="utf-8") @@ -449,13 +509,17 @@ class MarkdownRenderer: escaped_title = html.escape(title) escaped_theme = html.escape(theme, quote=True) escaped_math_engine = html.escape(self._normalized_math_engine(math_engine), quote=True) + try: + normalized_wheel_speed = max(0.5, min(3.0, float(wheel_scroll_speed))) + except (TypeError, ValueError): + normalized_wheel_speed = 1.0 fallback_font_size = int(round(max(0.8, min(font_scale, 1.6)) * 16)) font_size = max(12, min(int(document_font_size or fallback_font_size), 28)) font_family = self._css_font_family(document_font_family) escaped_font_family = html.escape(font_family, quote=False) return f""" - + @@ -467,6 +531,7 @@ class MarkdownRenderer: }} {pygments_css} {css} + {document_style_css} {math_assets["css"]} diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css index 04e9050..d78e200 100644 --- a/mdhelper/resources/reader.css +++ b/mdhelper/resources/reader.css @@ -325,44 +325,224 @@ html[data-theme="dark"] td code { .code-block { position: relative; margin: 1.2em 0; - border: 1px solid #d8dee8; + border: 1px solid #d4d4d4; border-radius: 8px; overflow: hidden; - background: #f7f9fc; + background: #ffffff; } html[data-theme="dark"] .code-block { - border-color: #384252; - background: #171b22; + border-color: #3c3c3c; + background: #1e1e1e; } .code-title { padding: 0.42em 0.76em; - border-bottom: 1px solid #d8dee8; - background: #edf1f6; - color: #53606f; + border-bottom: 1px solid #d4d4d4; + background: #f3f3f3; + color: #616161; font-size: 0.82em; font-weight: 650; } html[data-theme="dark"] .code-title { - border-bottom-color: #384252; - background: #242b36; - color: #b7c0cc; + border-bottom-color: #3c3c3c; + background: #252526; + color: #cccccc; } pre.highlight { margin: 0; padding: 1em; overflow-x: auto; + background: #ffffff; + color: #000000; +} + +html[data-theme="dark"] pre.highlight { + background: #1e1e1e; + color: #d4d4d4; +} + +pre.highlight code { + display: block; + min-width: max-content; +} + +.highlight .c, +.highlight .cm, +.highlight .c1, +.highlight .cs { + color: #008000; + font-style: italic; +} + +.highlight .k, +.highlight .kc, +.highlight .kd, +.highlight .kn, +.highlight .kp, +.highlight .kr, +.highlight .ow { + color: #0000ff; + font-weight: 400; +} + +.highlight .kt, +.highlight .nc, +.highlight .nn { + color: #267f99; +} + +.highlight .s, +.highlight .sa, +.highlight .sb, +.highlight .sc, +.highlight .dl, +.highlight .sd, +.highlight .s1, +.highlight .s2, +.highlight .se, +.highlight .sh, +.highlight .si, +.highlight .sx, +.highlight .sr, +.highlight .ss { + color: #a31515; +} + +.highlight .m, +.highlight .mb, +.highlight .mf, +.highlight .mh, +.highlight .mi, +.highlight .mo, +.highlight .il { + color: #098658; +} + +.highlight .nf, +.highlight .fm, +.highlight .nb, +.highlight .bp { + color: #795e26; +} + +.highlight .na, +.highlight .nv, +.highlight .vc, +.highlight .vg, +.highlight .vi, +.highlight .vm { + color: #001080; +} + +.highlight .nd, +.highlight .ne, +.highlight .nl { + color: #af00db; +} + +.highlight .o, +.highlight .p { + color: #000000; +} + +.highlight .err { background: transparent; + color: #a31515; +} + +html[data-theme="dark"] .highlight .c, +html[data-theme="dark"] .highlight .cm, +html[data-theme="dark"] .highlight .c1, +html[data-theme="dark"] .highlight .cs { + color: #6a9955; +} + +html[data-theme="dark"] .highlight .k, +html[data-theme="dark"] .highlight .kc, +html[data-theme="dark"] .highlight .kd, +html[data-theme="dark"] .highlight .kn, +html[data-theme="dark"] .highlight .kp, +html[data-theme="dark"] .highlight .kr, +html[data-theme="dark"] .highlight .ow { + color: #569cd6; +} + +html[data-theme="dark"] .highlight .kt, +html[data-theme="dark"] .highlight .nc, +html[data-theme="dark"] .highlight .nn { + color: #4ec9b0; +} + +html[data-theme="dark"] .highlight .s, +html[data-theme="dark"] .highlight .sa, +html[data-theme="dark"] .highlight .sb, +html[data-theme="dark"] .highlight .sc, +html[data-theme="dark"] .highlight .dl, +html[data-theme="dark"] .highlight .sd, +html[data-theme="dark"] .highlight .s1, +html[data-theme="dark"] .highlight .s2, +html[data-theme="dark"] .highlight .se, +html[data-theme="dark"] .highlight .sh, +html[data-theme="dark"] .highlight .si, +html[data-theme="dark"] .highlight .sx, +html[data-theme="dark"] .highlight .sr, +html[data-theme="dark"] .highlight .ss { + color: #ce9178; +} + +html[data-theme="dark"] .highlight .m, +html[data-theme="dark"] .highlight .mb, +html[data-theme="dark"] .highlight .mf, +html[data-theme="dark"] .highlight .mh, +html[data-theme="dark"] .highlight .mi, +html[data-theme="dark"] .highlight .mo, +html[data-theme="dark"] .highlight .il { + color: #b5cea8; +} + +html[data-theme="dark"] .highlight .nf, +html[data-theme="dark"] .highlight .fm, +html[data-theme="dark"] .highlight .nb, +html[data-theme="dark"] .highlight .bp { + color: #dcdcaa; +} + +html[data-theme="dark"] .highlight .na, +html[data-theme="dark"] .highlight .nv, +html[data-theme="dark"] .highlight .vc, +html[data-theme="dark"] .highlight .vg, +html[data-theme="dark"] .highlight .vi, +html[data-theme="dark"] .highlight .vm { + color: #9cdcfe; +} + +html[data-theme="dark"] .highlight .nd, +html[data-theme="dark"] .highlight .ne, +html[data-theme="dark"] .highlight .nl { + color: #c586c0; +} + +html[data-theme="dark"] .highlight .o, +html[data-theme="dark"] .highlight .p { + color: #d4d4d4; +} + +html[data-theme="dark"] .highlight .err { + color: #f48771; } .code-line { - display: inline-block; + box-sizing: border-box; + display: block; min-width: 100%; + width: max-content; + min-height: 1.5em; padding-left: 3.4em; position: relative; + white-space: pre; } .code-line::before { @@ -370,13 +550,13 @@ pre.highlight { position: absolute; left: 0; width: 2.5em; - color: #8a95a5; + color: #858585; text-align: right; user-select: none; } html[data-theme="dark"] .code-line::before { - color: #748094; + color: #858585; } .code-block.is-collapsible.is-collapsed pre.highlight { @@ -392,11 +572,11 @@ html[data-theme="dark"] .code-line::before { bottom: 0; height: 3.2em; pointer-events: none; - background: linear-gradient(rgb(247 249 252 / 0), #f7f9fc); + background: linear-gradient(rgb(255 255 255 / 0), #ffffff); } html[data-theme="dark"] .code-block.is-collapsible.is-collapsed::after { - background: linear-gradient(rgb(23 27 34 / 0), #171b22); + background: linear-gradient(rgb(30 30 30 / 0), #1e1e1e); } .plain-file-view { @@ -526,10 +706,14 @@ html[data-theme="dark"] .copy-code-button:hover { } .pseudo-keyword { - color: #7b3ff2; + color: #0000ff; font-weight: 700; } +html[data-theme="dark"] .pseudo-keyword { + color: #569cd6; +} + img { max-width: 100%; height: auto; diff --git a/mdhelper/resources/reader.js b/mdhelper/resources/reader.js index b4fa26f..bee6cec 100644 --- a/mdhelper/resources/reader.js +++ b/mdhelper/resources/reader.js @@ -71,16 +71,16 @@ document.addEventListener("DOMContentLoaded", () => { code.dataset.lineNumbered = "true"; const htmlLines = code.innerHTML.replace(/\n$/, "").split("\n"); code.innerHTML = htmlLines - .map((line, index) => `${line || " "}`) - .join("\n"); + .map((line, index) => `${line || " "}`) + .join(""); } if (lines.length > 18) { - block.classList.add("is-collapsible", "is-collapsed"); + block.classList.add("is-collapsible"); const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "toggle-code-button"; - toggle.textContent = "展开"; + toggle.textContent = "收起"; toggle.addEventListener("click", () => { const collapsed = block.classList.toggle("is-collapsed"); toggle.textContent = collapsed ? "展开" : "收起"; @@ -358,6 +358,88 @@ document.addEventListener("DOMContentLoaded", () => { } }; + const configuredWheelSpeed = () => { + const speed = Number(document.documentElement.dataset.wheelScrollSpeed || "1"); + if (!Number.isFinite(speed)) { + return 1; + } + return Math.max(0.5, Math.min(3, speed)); + }; + + const normalizedWheelDelta = (event) => { + const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16 : window.innerHeight; + if (event.deltaMode === WheelEvent.DOM_DELTA_PIXEL) { + return { x: event.deltaX, y: event.deltaY }; + } + return { x: event.deltaX * unit, y: event.deltaY * unit }; + }; + + const canScrollFurther = (element, deltaX, deltaY) => { + if (!element) { + return false; + } + const vertical = Math.abs(deltaY) >= Math.abs(deltaX); + if (vertical) { + if (deltaY < 0) { + return element.scrollTop > 0; + } + return element.scrollTop + element.clientHeight < element.scrollHeight - 1; + } + if (deltaX < 0) { + return element.scrollLeft > 0; + } + return element.scrollLeft + element.clientWidth < element.scrollWidth - 1; + }; + + const nearestWheelScroller = (target, deltaX, deltaY) => { + let node = target instanceof Element ? target : target?.parentElement; + const vertical = Math.abs(deltaY) >= Math.abs(deltaX); + while (node && node !== document.body && node !== document.documentElement) { + const style = window.getComputedStyle(node); + const canScrollY = + vertical && + /(auto|scroll)/.test(style.overflowY) && + node.scrollHeight > node.clientHeight + 1; + const canScrollX = + !vertical && + /(auto|scroll)/.test(style.overflowX) && + node.scrollWidth > node.clientWidth + 1; + if ((canScrollY || canScrollX) && canScrollFurther(node, deltaX, deltaY)) { + return node; + } + node = node.parentElement; + } + return document.scrollingElement || document.documentElement; + }; + + document.addEventListener( + "wheel", + (event) => { + const speed = configuredWheelSpeed(); + if (Math.abs(speed - 1) < 0.01 || event.ctrlKey || event.metaKey || event.defaultPrevented) { + return; + } + const delta = normalizedWheelDelta(event); + const scroller = nearestWheelScroller(event.target, delta.x, delta.y); + if (!scroller) { + return; + } + event.preventDefault(); + scroller.scrollBy({ + left: delta.x * speed, + top: delta.y * speed, + behavior: "auto", + }); + if ( + scroller === document.scrollingElement || + scroller === document.documentElement || + scroller === document.body + ) { + scheduleReport(); + } + }, + { passive: false } + ); if (window.qt && window.qt.webChannelTransport) { new QWebChannel(window.qt.webChannelTransport, (channel) => { bridge = channel.objects.mdhelperBridge; diff --git a/mdhelper/search.py b/mdhelper/search.py index 0e58b87..4006ce7 100644 --- a/mdhelper/search.py +++ b/mdhelper/search.py @@ -1,8 +1,10 @@ from __future__ import annotations from dataclasses import dataclass +from pathlib import Path -from .document_tree import DocumentEntry +from .document_tree import CODE_DOCUMENT_EXTENSIONS, DocumentEntry +from .text_io import DEFAULT_SEARCH_INDEX_BYTES, is_within_size_limit, read_text_with_fallback @dataclass(frozen=True) @@ -15,23 +17,29 @@ class SearchMatch: class SearchIndex: def __init__(self, entries: list[DocumentEntry] | None = None) -> None: - self._records: list[tuple[DocumentEntry, str, str, str]] = [] + self._records: list[tuple[DocumentEntry, str, str]] = [] + self._body_cache: dict[Path, tuple[int, int, str]] = {} if entries: self.rebuild(entries) def rebuild(self, entries: list[DocumentEntry]) -> None: - self._records = [(entry, entry.title, entry.relative_path, _read_text(entry)) for entry in entries] + self._records = [(entry, entry.title, entry.relative_path) for entry in entries] + current_paths = {entry.path for entry in entries} + self._body_cache = {path: value for path, value in self._body_cache.items() if path in current_paths} def matches_entry(self, entry: DocumentEntry, query: str) -> bool: normalized = query.strip().casefold() if not normalized: return True - for indexed_entry, title, relative_path, body in self._records: + for indexed_entry, title, relative_path in self._records: if indexed_entry.path == entry.path: - haystack = self._haystack(title, relative_path, body) - return normalized in haystack.casefold() - return normalized in self._haystack(entry.title, entry.relative_path, _read_text(entry)).casefold() + if normalized in self._haystack(title, relative_path, "").casefold(): + return True + return normalized in self._body_for(indexed_entry).casefold() + if normalized in self._haystack(entry.title, entry.relative_path, "").casefold(): + return True + return normalized in self._body_for(entry).casefold() def search(self, query: str, limit: int = 80) -> list[SearchMatch]: normalized = query.strip().casefold() @@ -39,8 +47,10 @@ class SearchIndex: return [] matches: list[SearchMatch] = [] - for entry, title, relative_path, body in self._records: - result = _match_details(title, relative_path, body, normalized) + for entry, title, relative_path in self._records: + result = _match_details(title, relative_path, "", normalized) + if result is None: + result = _match_details(title, relative_path, self._body_for(entry), normalized) if result is None: continue @@ -60,6 +70,17 @@ class SearchIndex: def _haystack(self, title: str, relative_path: str, body: str) -> str: return f"{title}\n{relative_path}\n{body}" + def _body_for(self, entry: DocumentEntry) -> str: + signature = _file_signature(entry.path) + if signature is None: + return "" + cached = self._body_cache.get(entry.path) + if cached is not None and cached[:2] == signature: + return cached[2] + body = _read_text(entry) + self._body_cache[entry.path] = (*signature, body) + return body + def matches_entry(entry: DocumentEntry, query: str) -> bool: normalized = query.strip().casefold() @@ -96,12 +117,33 @@ 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"}: + supported_text_extensions = { + ".md", + ".markdown", + ".txt", + ".html", + ".htm", + ".xhtml", + ".css", + ".js", + ".json", + ".yaml", + ".yml", + } | CODE_DOCUMENT_EXTENSIONS + if entry.path.suffix.lower() not in supported_text_extensions: return "" + if not is_within_size_limit(entry.path, DEFAULT_SEARCH_INDEX_BYTES): + return "" + text = read_text_with_fallback(entry.path, max_bytes=DEFAULT_SEARCH_INDEX_BYTES) + return "" if text.startswith("读取失败:") else text + + +def _file_signature(path: Path) -> tuple[int, int] | None: try: - return entry.path.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - return "" + stat = path.stat() + except OSError: + return None + return stat.st_mtime_ns, stat.st_size def _snippet(text: str, index: int, length: int) -> str: diff --git a/mdhelper/settings_dialog.py b/mdhelper/settings_dialog.py index c5ad296..6ee30d9 100644 --- a/mdhelper/settings_dialog.py +++ b/mdhelper/settings_dialog.py @@ -10,8 +10,11 @@ from PySide6.QtWidgets import ( QDoubleSpinBox, QFormLayout, QVBoxLayout, + QWidget, ) +from .document_tree import DEFAULT_DOCUMENT_FILE_GROUPS, normalized_document_file_groups + @dataclass(frozen=True) class AppPreferences: @@ -19,8 +22,12 @@ class AppPreferences: theme_color: str theme_background: str font_scale: float + wheel_scroll_speed: float auto_refresh: bool + auto_refresh_mode: str + auto_refresh_delay_ms: int non_preview_action: str + document_file_groups: tuple[str, ...] = DEFAULT_DOCUMENT_FILE_GROUPS class SettingsDialog(QDialog): @@ -57,8 +64,28 @@ class SettingsDialog(QDialog): self.font_scale_spin.setDecimals(1) self.font_scale_spin.setValue(preferences.font_scale) - self.auto_refresh_checkbox = QCheckBox("文件变化后自动刷新当前阅读页") - self.auto_refresh_checkbox.setChecked(preferences.auto_refresh) + self.wheel_scroll_speed_spin = QDoubleSpinBox() + self.wheel_scroll_speed_spin.setRange(0.5, 3.0) + self.wheel_scroll_speed_spin.setSingleStep(0.1) + self.wheel_scroll_speed_spin.setDecimals(1) + self.wheel_scroll_speed_spin.setSuffix(" 倍") + self.wheel_scroll_speed_spin.setValue(preferences.wheel_scroll_speed) + + self.auto_refresh_mode_combo = QComboBox() + self.auto_refresh_mode_combo.addItem("当前文档、资源和目录", "all") + self.auto_refresh_mode_combo.addItem("当前文档和引用资源", "resources") + self.auto_refresh_mode_combo.addItem("仅当前文档", "current") + self.auto_refresh_mode_combo.addItem("关闭", "off") + mode = preferences.auto_refresh_mode if preferences.auto_refresh else "off" + self.auto_refresh_mode_combo.setCurrentIndex(max(0, self.auto_refresh_mode_combo.findData(mode))) + + self.auto_refresh_delay_combo = QComboBox() + self.auto_refresh_delay_combo.addItem("快速(0.8 秒)", 800) + self.auto_refresh_delay_combo.addItem("标准(1 秒)", 1000) + self.auto_refresh_delay_combo.addItem("稳定(1.5 秒)", 1500) + self.auto_refresh_delay_combo.setCurrentIndex( + max(0, self.auto_refresh_delay_combo.findData(preferences.auto_refresh_delay_ms)) + ) self.non_preview_combo = QComboBox() self.non_preview_combo.addItem("每次询问", "ask") @@ -66,12 +93,31 @@ class SettingsDialog(QDialog): self.non_preview_combo.addItem("阻止打开,仅提示路径", "block") self.non_preview_combo.setCurrentIndex(max(0, self.non_preview_combo.findData(preferences.non_preview_action))) + enabled_groups = set(normalized_document_file_groups(preferences.document_file_groups)) + self.markdown_files_check = QCheckBox("Markdown / 网页") + self.markdown_files_check.setChecked("markdown" in enabled_groups) + self.python_files_check = QCheckBox("Python") + self.python_files_check.setChecked("python" in enabled_groups) + self.cpp_files_check = QCheckBox("C / C++") + self.cpp_files_check.setChecked("cpp" in enabled_groups) + + file_types_widget = QWidget() + file_types_layout = QVBoxLayout(file_types_widget) + file_types_layout.setContentsMargins(0, 0, 0, 0) + file_types_layout.setSpacing(4) + file_types_layout.addWidget(self.markdown_files_check) + file_types_layout.addWidget(self.python_files_check) + file_types_layout.addWidget(self.cpp_files_check) + form = QFormLayout() form.addRow("主题颜色", self.theme_color_combo) form.addRow("主题背景", self.theme_background_combo) form.addRow("正文字号倍率", self.font_scale_spin) - form.addRow("自动刷新", self.auto_refresh_checkbox) + form.addRow("鼠标滚轮速度", self.wheel_scroll_speed_spin) + form.addRow("自动刷新", self.auto_refresh_mode_combo) + form.addRow("刷新延迟", self.auto_refresh_delay_combo) form.addRow("其他本地文件", self.non_preview_combo) + form.addRow("展示文件类型", file_types_widget) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) buttons.accepted.connect(self.accept) @@ -86,13 +132,26 @@ class SettingsDialog(QDialog): theme_background = str(self.theme_background_combo.currentData()) if theme_color != "colorful": theme_background = "none" + auto_refresh_mode = str(self.auto_refresh_mode_combo.currentData()) + document_file_groups = [] + if self.markdown_files_check.isChecked(): + document_file_groups.append("markdown") + if self.python_files_check.isChecked(): + document_file_groups.append("python") + if self.cpp_files_check.isChecked(): + document_file_groups.append("cpp") + return AppPreferences( theme="dark" if theme_color in {"black", "dark_gray"} else "light", theme_color=theme_color, theme_background=theme_background, font_scale=float(self.font_scale_spin.value()), - auto_refresh=self.auto_refresh_checkbox.isChecked(), + wheel_scroll_speed=float(self.wheel_scroll_speed_spin.value()), + auto_refresh=auto_refresh_mode != "off", + auto_refresh_mode=auto_refresh_mode, + auto_refresh_delay_ms=int(self.auto_refresh_delay_combo.currentData() or 1000), non_preview_action=str(self.non_preview_combo.currentData()), + document_file_groups=normalized_document_file_groups(document_file_groups), ) def _update_background_availability(self) -> None: diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py new file mode 100644 index 0000000..a9a4b02 --- /dev/null +++ b/mdhelper/style_dialog.py @@ -0,0 +1,705 @@ +from __future__ import annotations + +import ctypes +import os +from copy import deepcopy +from typing import Any + +from PySide6.QtCore import Qt +from PySide6.QtGui import QFont +from PySide6.QtWidgets import ( + QCheckBox, + QComboBox, + QDialog, + QDialogButtonBox, + QDoubleSpinBox, + QFrame, + QFontComboBox, + QFormLayout, + QGroupBox, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QPushButton, + QSpinBox, + QTabWidget, + QTextEdit, + QVBoxLayout, + QWidget, +) + + +STYLE_TARGETS = ( + ("paragraph", "正文段落", ".reader p"), + ("h1", "一级标题", ".reader h1"), + ("h2", "二级标题", ".reader h2"), + ("h3", "三级标题", ".reader h3"), + ("h4", "四级标题", ".reader h4"), + ("h5", "五级标题", ".reader h5"), + ("h6", "六级标题", ".reader h6"), + ("list", "列表项", ".reader li"), + ("blockquote", "引用段落", ".reader blockquote, .reader blockquote p, .reader .admonition, .reader .admonition p"), + ("code", "代码块", ".reader pre, .reader code"), + ("table", "表格", ".reader table"), +) +DEFAULT_CHINESE_FONT = "宋体" +DEFAULT_ENGLISH_FONT = "Times New Roman" + + +def build_document_style_css(rules: dict[str, dict[str, Any]] | None, extra_css: str = "") -> str: + parts: list[str] = [] + selector_by_target = {target_id: selector for target_id, _label, selector in STYLE_TARGETS} + for target_id, selector in selector_by_target.items(): + rule = rules.get(target_id, {}) if isinstance(rules, dict) else {} + declarations = _css_declarations(rule) + if declarations: + parts.append(f"{selector} {{\n" + "\n".join(f" {declaration}" for declaration in declarations) + "\n}") + extra = extra_css.strip() + if extra: + parts.append(extra) + return "\n\n".join(parts).strip() + + +def _css_declarations(rule: dict[str, Any]) -> list[str]: + declarations: list[str] = [] + font_declaration = _font_family_declaration(rule) + if font_declaration: + declarations.append(font_declaration) + + font_size = _positive_float(rule.get("font_size")) + if font_size > 0: + declarations.append(f"font-size: {_format_number(font_size)}px;") + + if bool(rule.get("bold")): + declarations.append("font-weight: 700;") + if bool(rule.get("italic")): + declarations.append("font-style: italic;") + + line_height = _positive_float(rule.get("line_height_value", rule.get("line_height"))) + if line_height > 0: + declarations.append(f"line-height: {_css_length_or_multiple(line_height, str(rule.get('line_height_unit') or 'multiple'))};") + + first_line_indent = _positive_float(rule.get("first_line_indent_chars", rule.get("first_line_indent"))) + hanging_indent = _positive_float(rule.get("hanging_indent_chars", rule.get("hanging_indent"))) + if hanging_indent > 0: + declarations.append(f"padding-left: {_format_number(hanging_indent)}em;") + declarations.append(f"text-indent: -{_format_number(hanging_indent)}em;") + elif first_line_indent > 0: + declarations.append(f"text-indent: {_format_number(first_line_indent)}em;") + + space_before = _positive_float(rule.get("space_before_value", rule.get("space_before"))) + if space_before > 0: + unit = str(rule.get("space_before_unit") or "multiple") + declarations.append(f"margin-top: {_css_length_or_multiple(space_before, unit, multiple_unit='em')};") + space_after = _positive_float(rule.get("space_after_value", rule.get("space_after"))) + if space_after > 0: + unit = str(rule.get("space_after_unit") or "multiple") + declarations.append(f"margin-bottom: {_css_length_or_multiple(space_after, unit, multiple_unit='em')};") + return declarations + + +def _font_family_declaration(rule: dict[str, Any]) -> str: + english_font = str(rule.get("english_font_family") or "").strip() + chinese_font = str(rule.get("chinese_font_family") or rule.get("font_family") or "").strip() + fonts = [font for font in (english_font, chinese_font, "Microsoft YaHei UI", "Arial", "sans-serif") if font] + unique_fonts: list[str] = [] + for font in fonts: + if font not in unique_fonts: + unique_fonts.append(font) + if not english_font and not chinese_font: + return "" + css_fonts = [ + font if font in {"serif", "sans-serif", "monospace"} else f'"{font.replace("\\", "\\\\").replace("\"", "\\\"")}"' + for font in unique_fonts + ] + return f"font-family: {', '.join(css_fonts)};" + + +def _css_length_or_multiple(value: float, unit: str, multiple_unit: str = "") -> str: + formatted = _format_number(value) + if unit == "pt": + return f"{formatted}pt" + if multiple_unit: + return f"{formatted}{multiple_unit}" + return formatted + + +def _positive_float(value: object) -> float: + try: + return max(0.0, float(value)) + except (TypeError, ValueError): + return 0.0 + + +def _format_number(value: float) -> str: + return f"{value:.2f}".rstrip("0").rstrip(".") + + +class DocumentStyleEditorDialog(QDialog): + def __init__( + self, + style: dict[str, Any] | None = None, + default_name: str = "自定义样式", + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.setWindowTitle("文档样式") + self.setMinimumSize(565, 620) + self.resize(565, 620) + source = style or {} + self.rules: dict[str, dict[str, Any]] = deepcopy(source.get("rules", {})) if isinstance(source.get("rules"), dict) else {} + self._current_target = STYLE_TARGETS[0][0] + self._loading = False + + self.name_edit = QLineEdit(str(source.get("name") or default_name)) + self.name_edit.setObjectName("styleNameEdit") + self.name_edit.setPlaceholderText("样式名称") + self.name_edit.setMaximumWidth(420) + + name_row = QHBoxLayout() + name_row.setContentsMargins(0, 0, 0, 0) + name_row.setSpacing(8) + name_row.addWidget(QLabel("样式名称")) + name_row.addWidget(self.name_edit) + name_row.addStretch(1) + + self.tabs = QTabWidget() + self.tabs.setMaximumWidth(535) + self.tabs.addTab(self._build_visual_tab(), "图形设置") + self.tabs.addTab(self._build_advanced_tab(str(source.get("extra_css") or source.get("css") or "")), "高级 CSS") + + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + button_row = QWidget() + button_row.setMaximumWidth(535) + button_layout = QHBoxLayout(button_row) + button_layout.setContentsMargins(0, 0, 0, 0) + button_layout.addStretch(1) + button_layout.addWidget(buttons) + + layout = QVBoxLayout(self) + layout.setContentsMargins(16, 14, 16, 16) + layout.setSpacing(12) + layout.addLayout(name_row) + layout.addWidget(self.tabs) + layout.addWidget(button_row) + self._load_rule_to_widgets(self.rules.get(self._current_target, {})) + + def apply_theme(self, theme_color: str) -> None: + palettes = { + "white": { + "chrome": "#f7f8fb", + "surface": "#ffffff", + "text": "#111827", + "muted": "#6b7280", + "border": "#dde2eb", + "hover": "#eef4ff", + "selected": "#dbeafe", + "focus": "#3b82f6", + }, + "black": { + "chrome": "#0c0d10", + "surface": "#17191f", + "text": "#f3f4f6", + "muted": "#a7adb7", + "border": "#2a2e38", + "hover": "#252b36", + "selected": "#243b5a", + "focus": "#60a5fa", + }, + "dark_gray": { + "chrome": "#282c33", + "surface": "#343943", + "text": "#f1f5f9", + "muted": "#c1c7d0", + "border": "#48505d", + "hover": "#3f4a59", + "selected": "#365b82", + "focus": "#7dd3fc", + }, + "colorful": { + "chrome": "#eef5ff", + "surface": "#ffffff", + "text": "#132238", + "muted": "#667085", + "border": "#cbd9ef", + "hover": "#e7f0ff", + "selected": "#cfe2ff", + "focus": "#2563eb", + }, + } + palette = palettes.get(theme_color, palettes["white"]) + chrome = palette["chrome"] + surface = palette["surface"] + text = palette["text"] + muted = palette["muted"] + border = palette["border"] + hover = palette["hover"] + selected = palette["selected"] + focus = palette["focus"] + self.setStyleSheet( + f""" + QDialog {{ + background: {chrome}; + color: {text}; + }} + + QLabel {{ + color: {text}; + }} + + QLineEdit, + QTextEdit, + QComboBox, + QFontComboBox, + QSpinBox, + QDoubleSpinBox {{ + background: {surface}; + color: {text}; + border: 1px solid {border}; + border-radius: 4px; + padding: 4px 6px; + selection-background-color: {selected}; + }} + + QLineEdit#styleNameEdit {{ + min-height: 24px; + font-weight: 600; + }} + + QLineEdit:focus, + QTextEdit:focus, + QComboBox:focus, + QFontComboBox:focus, + QSpinBox:focus, + QDoubleSpinBox:focus {{ + border-color: {focus}; + }} + + QSpinBox, + QDoubleSpinBox {{ + padding-right: 18px; + }} + + QSpinBox::up-button, + QDoubleSpinBox::up-button, + QSpinBox::down-button, + QDoubleSpinBox::down-button {{ + width: 15px; + background: transparent; + border-left: 1px solid {border}; + }} + + QSpinBox::up-button, + QDoubleSpinBox::up-button {{ + subcontrol-origin: border; + subcontrol-position: top right; + border-bottom: 1px solid {border}; + border-top-right-radius: 3px; + }} + + QSpinBox::down-button, + QDoubleSpinBox::down-button {{ + subcontrol-origin: border; + subcontrol-position: bottom right; + border-bottom-right-radius: 3px; + }} + + QSpinBox::up-button:hover, + QDoubleSpinBox::up-button:hover, + QSpinBox::down-button:hover, + QDoubleSpinBox::down-button:hover {{ + background: {hover}; + }} + + QSpinBox::up-arrow, + QDoubleSpinBox::up-arrow, + QSpinBox::down-arrow, + QDoubleSpinBox::down-arrow {{ + width: 7px; + height: 7px; + }} + + QCheckBox {{ + color: {text}; + }} + + QListWidget#styleTargetList {{ + background: {surface}; + color: {text}; + border: 1px solid {border}; + border-radius: 6px; + padding: 4px; + outline: 0; + }} + + QListWidget#styleTargetList::item {{ + min-height: 28px; + padding: 4px 8px; + border-radius: 4px; + }} + + QListWidget#styleTargetList::item:hover {{ + background: {hover}; + }} + + QListWidget#styleTargetList::item:selected {{ + background: {selected}; + color: {text}; + }} + + QGroupBox#styleSection {{ + background: {surface}; + color: {text}; + border: 1px solid {border}; + border-radius: 6px; + margin-top: 10px; + font-weight: 600; + }} + + QGroupBox#styleSection::title {{ + subcontrol-origin: margin; + left: 10px; + padding: 0 5px; + background: {chrome}; + }} + + QFrame#stylePreview {{ + background: {surface}; + border: 1px solid {border}; + border-radius: 6px; + }} + + QLabel#stylePreviewTitle {{ + color: {muted}; + font-weight: 600; + }} + + QLabel#stylePreviewText {{ + color: {text}; + line-height: 1.5; + }} + + QPushButton {{ + background: {surface}; + color: {text}; + border: 1px solid {border}; + border-radius: 4px; + padding: 6px 12px; + }} + + QPushButton:hover {{ + background: {hover}; + }} + + QPushButton#styleResetButton {{ + color: {muted}; + }} + + QTabWidget::pane {{ + border: 1px solid {border}; + background: {surface}; + border-radius: 6px; + top: -1px; + }} + + QTabBar::tab {{ + background: {chrome}; + color: {muted}; + border: 1px solid {border}; + border-bottom: 0; + padding: 7px 14px; + }} + + QTabBar::tab:selected {{ + background: {surface}; + color: {text}; + border-color: {border}; + }} + """ + ) + self._apply_window_title_bar_style(chrome, text, theme_color in {"black", "dark_gray"}) + + def _apply_window_title_bar_style(self, background: str, foreground: str, dark: bool) -> None: + if os.name != "nt": + return + + def colorref(value: str) -> int: + value = value.lstrip("#") + red = int(value[0:2], 16) + green = int(value[2:4], 16) + blue = int(value[4:6], 16) + return red | (green << 8) | (blue << 16) + + try: + hwnd = int(self.winId()) + dwmapi = ctypes.windll.dwmapi + dark_mode = ctypes.c_int(1 if dark else 0) + for attribute in (20, 19): + dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(dark_mode), ctypes.sizeof(dark_mode)) + for attribute, value in ((35, background), (36, foreground), (34, background)): + color = ctypes.c_int(colorref(value)) + dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(color), ctypes.sizeof(color)) + except (AttributeError, OSError, ValueError): + return + + def style_payload(self) -> dict[str, object]: + self._store_current_rule() + extra_css = self.extra_css_edit.toPlainText().strip() + return { + "name": self.name_edit.text().strip() or "自定义样式", + "rules": deepcopy(self.rules), + "extra_css": extra_css, + "css": build_document_style_css(self.rules, extra_css), + } + + def _build_visual_tab(self) -> QWidget: + tab = QWidget() + layout = QHBoxLayout(tab) + layout.setContentsMargins(10, 10, 10, 10) + layout.setSpacing(14) + + self.target_list = QListWidget() + self.target_list.setObjectName("styleTargetList") + self.target_list.setFixedWidth(156) + for target_id, label, _selector in STYLE_TARGETS: + item = QListWidgetItem(label) + item.setData(Qt.ItemDataRole.UserRole, target_id) + self.target_list.addItem(item) + self.target_list.currentRowChanged.connect(self._change_target) + layout.addWidget(self.target_list) + + content = QWidget() + content.setObjectName("styleEditorContent") + content.setMaximumWidth(500) + content_layout = QVBoxLayout(content) + content_layout.setContentsMargins(0, 0, 0, 0) + content_layout.setSpacing(12) + + self.chinese_font_combo = QFontComboBox() + self.chinese_font_combo.setCurrentFont(QFont(DEFAULT_CHINESE_FONT)) + self.chinese_font_combo.setMinimumWidth(220) + self.chinese_font_combo.setMaximumWidth(315) + self.chinese_font_combo.currentFontChanged.connect(self._store_and_refresh) + + self.english_font_combo = QFontComboBox() + self.english_font_combo.setCurrentFont(QFont(DEFAULT_ENGLISH_FONT)) + self.english_font_combo.setMinimumWidth(220) + self.english_font_combo.setMaximumWidth(315) + self.english_font_combo.currentFontChanged.connect(self._store_and_refresh) + + self.font_size_spin = QSpinBox() + self.font_size_spin.setRange(0, 96) + self.font_size_spin.setSpecialValueText("继承") + self.font_size_spin.setSuffix(" px") + self.font_size_spin.setMaximumWidth(150) + self.font_size_spin.valueChanged.connect(self._store_and_refresh) + + self.bold_checkbox = QCheckBox("加粗") + self.bold_checkbox.toggled.connect(self._store_and_refresh) + self.italic_checkbox = QCheckBox("斜体") + self.italic_checkbox.toggled.connect(self._store_and_refresh) + + font_style_row = QHBoxLayout() + font_style_row.addWidget(self.bold_checkbox) + font_style_row.addWidget(self.italic_checkbox) + font_style_row.addStretch(1) + + font_form = QFormLayout() + font_form.setContentsMargins(10, 12, 10, 10) + font_form.setHorizontalSpacing(12) + font_form.setVerticalSpacing(9) + font_form.addRow("中文字体", self.chinese_font_combo) + font_form.addRow("英文字体", self.english_font_combo) + font_form.addRow("字号", self.font_size_spin) + font_form.addRow("字形", font_style_row) + font_group = QGroupBox("字体") + font_group.setObjectName("styleSection") + font_group.setMaximumWidth(500) + font_group.setLayout(font_form) + + self.line_height_spin = self._number_spin(0.0, 200.0, "继承") + self.line_height_spin.setSingleStep(0.05) + self.line_height_spin.setMaximumWidth(150) + self.line_height_spin.valueChanged.connect(self._store_and_refresh) + self.line_height_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) + self.line_height_unit_combo.currentIndexChanged.connect(self._store_and_refresh) + self.first_indent_spin = self._number_spin(0.0, 20.0, "无") + self.first_indent_spin.setSuffix(" 字符") + self.first_indent_spin.setMaximumWidth(170) + self.first_indent_spin.valueChanged.connect(self._store_and_refresh) + self.hanging_indent_spin = self._number_spin(0.0, 20.0, "无") + self.hanging_indent_spin.setSuffix(" 字符") + self.hanging_indent_spin.setMaximumWidth(170) + self.hanging_indent_spin.valueChanged.connect(self._store_and_refresh) + self.space_before_spin = self._number_spin(0.0, 200.0, "无") + self.space_before_spin.setMaximumWidth(150) + self.space_before_spin.valueChanged.connect(self._store_and_refresh) + self.space_before_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) + self.space_before_unit_combo.currentIndexChanged.connect(self._store_and_refresh) + self.space_after_spin = self._number_spin(0.0, 200.0, "无") + self.space_after_spin.setMaximumWidth(150) + self.space_after_spin.valueChanged.connect(self._store_and_refresh) + self.space_after_unit_combo = self._unit_combo((("倍", "multiple"), ("磅", "pt"))) + self.space_after_unit_combo.currentIndexChanged.connect(self._store_and_refresh) + + reset_button = QPushButton("重置当前对象") + reset_button.setObjectName("styleResetButton") + reset_button.setMaximumWidth(128) + reset_button.clicked.connect(self._reset_current_target) + reset_row = QHBoxLayout() + reset_row.setContentsMargins(0, 0, 0, 0) + reset_row.addStretch(1) + reset_row.addWidget(reset_button) + + paragraph_form = QFormLayout() + paragraph_form.setContentsMargins(10, 12, 10, 10) + paragraph_form.setHorizontalSpacing(12) + paragraph_form.setVerticalSpacing(9) + paragraph_form.addRow("行间距", self._measurement_row(self.line_height_spin, self.line_height_unit_combo)) + paragraph_form.addRow("首行缩进", self.first_indent_spin) + paragraph_form.addRow("悬挂缩进", self.hanging_indent_spin) + paragraph_form.addRow("段前间距", self._measurement_row(self.space_before_spin, self.space_before_unit_combo)) + paragraph_form.addRow("段后间距", self._measurement_row(self.space_after_spin, self.space_after_unit_combo)) + paragraph_form.addRow("", reset_row) + paragraph_group = QGroupBox("段落") + paragraph_group.setObjectName("styleSection") + paragraph_group.setMaximumWidth(500) + paragraph_group.setLayout(paragraph_form) + + preview = QFrame() + preview.setObjectName("stylePreview") + preview.setMaximumWidth(500) + preview_layout = QVBoxLayout(preview) + preview_layout.setContentsMargins(14, 12, 14, 12) + preview_layout.setSpacing(6) + preview_title = QLabel("预览") + preview_title.setObjectName("stylePreviewTitle") + preview_text = QLabel("标题示例\n正文段落示例 Aa 123,查看字体、缩进和段落间距的整体感觉。") + preview_text.setObjectName("stylePreviewText") + preview_text.setWordWrap(True) + preview_layout.addWidget(preview_title) + preview_layout.addWidget(preview_text) + + content_layout.addWidget(font_group) + content_layout.addWidget(paragraph_group) + content_layout.addWidget(preview) + content_layout.addStretch(1) + layout.addWidget(content) + layout.addStretch(1) + previous_loading = self._loading + self._loading = True + self.target_list.setCurrentRow(0) + self._loading = previous_loading + return tab + + def _build_advanced_tab(self, css: str) -> QWidget: + tab = QWidget() + self.extra_css_edit = QTextEdit() + self.extra_css_edit.setAcceptRichText(False) + self.extra_css_edit.setPlainText(css) + self.extra_css_edit.setPlaceholderText("可选:补充 CSS,会叠加到图形设置生成的样式之后。") + layout = QVBoxLayout(tab) + layout.addWidget(QLabel("附加 CSS")) + layout.addWidget(self.extra_css_edit, 1) + return tab + + def _number_spin(self, minimum: float, maximum: float, special_text: str) -> QDoubleSpinBox: + spin = QDoubleSpinBox() + spin.setRange(minimum, maximum) + spin.setDecimals(2) + spin.setSingleStep(0.1) + spin.setSpecialValueText(special_text) + return spin + + def _unit_combo(self, items: tuple[tuple[str, str], ...]) -> QComboBox: + combo = QComboBox() + combo.setFixedWidth(58) + for label, value in items: + combo.addItem(label, value) + return combo + + def _measurement_row(self, spin: QDoubleSpinBox, unit_combo: QComboBox) -> QHBoxLayout: + row = QHBoxLayout() + row.setContentsMargins(0, 0, 0, 0) + row.setSpacing(6) + row.addWidget(spin) + row.addWidget(unit_combo) + row.addStretch(1) + return row + + def _change_target(self, row: int = -1) -> None: + if self._loading: + return + del row + self._store_current_rule() + item = self.target_list.currentItem() + if item is None: + return + self._current_target = str(item.data(Qt.ItemDataRole.UserRole) or STYLE_TARGETS[0][0]) + self._load_rule_to_widgets(self.rules.get(self._current_target, {})) + + def _store_current_rule(self) -> None: + rule: dict[str, object] = {} + rule["chinese_font_family"] = self.chinese_font_combo.currentFont().family() or DEFAULT_CHINESE_FONT + rule["english_font_family"] = self.english_font_combo.currentFont().family() or DEFAULT_ENGLISH_FONT + if self.font_size_spin.value() > 0: + rule["font_size"] = self.font_size_spin.value() + if self.bold_checkbox.isChecked(): + rule["bold"] = True + if self.italic_checkbox.isChecked(): + rule["italic"] = True + if self.line_height_spin.value() > 0: + rule["line_height_value"] = self.line_height_spin.value() + rule["line_height_unit"] = str(self.line_height_unit_combo.currentData() or "multiple") + if self.first_indent_spin.value() > 0: + rule["first_line_indent_chars"] = self.first_indent_spin.value() + if self.hanging_indent_spin.value() > 0: + rule["hanging_indent_chars"] = self.hanging_indent_spin.value() + if self.space_before_spin.value() > 0: + rule["space_before_value"] = self.space_before_spin.value() + rule["space_before_unit"] = str(self.space_before_unit_combo.currentData() or "multiple") + if self.space_after_spin.value() > 0: + rule["space_after_value"] = self.space_after_spin.value() + rule["space_after_unit"] = str(self.space_after_unit_combo.currentData() or "multiple") + if rule: + self.rules[self._current_target] = rule + else: + self.rules.pop(self._current_target, None) + + def _load_rule_to_widgets(self, rule: dict[str, Any]) -> None: + self._loading = True + chinese_family = str(rule.get("chinese_font_family") or rule.get("font_family") or DEFAULT_CHINESE_FONT) + english_family = str(rule.get("english_font_family") or DEFAULT_ENGLISH_FONT) + self.chinese_font_combo.setCurrentFont(QFont(chinese_family)) + self.english_font_combo.setCurrentFont(QFont(english_family)) + self.font_size_spin.setValue(int(_positive_float(rule.get("font_size")))) + self.bold_checkbox.setChecked(bool(rule.get("bold"))) + self.italic_checkbox.setChecked(bool(rule.get("italic"))) + self.line_height_spin.setValue(_positive_float(rule.get("line_height_value", rule.get("line_height")))) + self._set_combo_data(self.line_height_unit_combo, str(rule.get("line_height_unit") or "multiple")) + self.first_indent_spin.setValue(_positive_float(rule.get("first_line_indent_chars", rule.get("first_line_indent")))) + self.hanging_indent_spin.setValue(_positive_float(rule.get("hanging_indent_chars", rule.get("hanging_indent")))) + self.space_before_spin.setValue(_positive_float(rule.get("space_before_value", rule.get("space_before")))) + self._set_combo_data(self.space_before_unit_combo, str(rule.get("space_before_unit") or "multiple")) + self.space_after_spin.setValue(_positive_float(rule.get("space_after_value", rule.get("space_after")))) + self._set_combo_data(self.space_after_unit_combo, str(rule.get("space_after_unit") or "multiple")) + self._loading = False + + def _sync_font_enabled(self) -> None: + return + + def _set_combo_data(self, combo: QComboBox, value: str) -> None: + index = combo.findData(value) + combo.setCurrentIndex(max(0, index)) + + def _store_and_refresh(self) -> None: + if not self._loading: + self._store_current_rule() + + def _reset_current_target(self) -> None: + self.rules.pop(self._current_target, None) + self._load_rule_to_widgets({}) diff --git a/mdhelper/text_io.py b/mdhelper/text_io.py new file mode 100644 index 0000000..b832ddd --- /dev/null +++ b/mdhelper/text_io.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from pathlib import Path + +TEXT_ENCODINGS = ("utf-8-sig", "utf-8", "gbk", "latin-1") +DEFAULT_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024 +DEFAULT_SEARCH_INDEX_BYTES = 512 * 1024 +TRUNCATED_TEXT_NOTICE = "\n\n[MDHelper: 文件较大,已截断预览内容。]" + + +def file_size(path: Path) -> int | None: + try: + return path.stat().st_size + except OSError: + return None + + +def is_within_size_limit(path: Path, max_bytes: int) -> bool: + size = file_size(path) + return size is None or size <= max_bytes + + +def read_text_with_fallback(path: Path, max_bytes: int | None = None) -> str: + try: + data = path.read_bytes() if max_bytes is None else _read_limited_bytes(path, max_bytes) + except OSError as exc: + return f"读取失败:{exc}" + + truncated = max_bytes is not None and len(data) > max_bytes + if truncated: + data = data[:max_bytes] + + for encoding in TEXT_ENCODINGS: + try: + text = data.decode(encoding) + break + except UnicodeDecodeError: + continue + else: + text = data.decode("utf-8", errors="replace") + + if truncated: + text += TRUNCATED_TEXT_NOTICE + return text + + +def _read_limited_bytes(path: Path, max_bytes: int) -> bytes: + with path.open("rb") as handle: + return handle.read(max_bytes + 1) diff --git a/requirements.txt b/requirements.txt index 04622ac..0c779b2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,5 @@ PySide6==6.11.1 markdown-it-py==4.2.0 Pygments==2.20.0 Pillow==12.2.0 +python-docx==1.2.0 PyInstaller==6.20.0 diff --git a/run_mdhelper.py b/run_mdhelper.py index f2fff6c..1957d91 100644 --- a/run_mdhelper.py +++ b/run_mdhelper.py @@ -1,6 +1,19 @@ +from __future__ import annotations + +import os + + +os.environ.setdefault( + "QTWEBENGINE_CHROMIUM_FLAGS", + "--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --log-level=3", +) +os.environ.setdefault( + "QT_LOGGING_RULES", + "qt.multimedia.ffmpeg.*=false;qt.multimedia.*.debug=false;qt.multimedia.*.info=false", +) + from mdhelper.app import main if __name__ == "__main__": raise SystemExit(main()) - diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py index d1398f6..2e071d5 100644 --- a/tests/gui_smoke.py +++ b/tests/gui_smoke.py @@ -3,28 +3,41 @@ from __future__ import annotations import os import sys import traceback +import zipfile from pathlib import Path os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") -os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox") +os.environ.setdefault( + "QTWEBENGINE_CHROMIUM_FLAGS", + "--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --no-sandbox --log-level=3", +) +os.environ.setdefault( + "QT_LOGGING_RULES", + "qt.multimedia.ffmpeg.*=false;qt.multimedia.*.debug=false;qt.multimedia.*.info=false", +) 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 QEventLoop, QTimer, QUrl, Qt +from PySide6.QtCore import QEventLoop, QSettings, QTimer, QUrl, Qt from PySide6.QtGui import QTextCursor from PySide6.QtWebEngineCore import QWebEnginePage -from PySide6.QtWidgets import QApplication, QMessageBox, QToolBar +from PySide6.QtWidgets import QApplication, QMessageBox, QPushButton, QToolBar from mdhelper.main_window import MainWindow, ReaderPage, ReaderView, VideoPlayerWidget from mdhelper.markdown_editor import MarkdownEditorDialog +from mdhelper.settings_dialog import AppPreferences, SettingsDialog +from mdhelper.style_dialog import DocumentStyleEditorDialog def main() -> int: project_root = PROJECT_ROOT app = QApplication.instance() or QApplication([sys.argv[0]]) + settings = QSettings("MDHelper", "MDHelper") + settings.setValue("reader/document_file_groups", '["markdown"]') + settings.setValue("reader/wheel_scroll_speed", 1.0) window = MainWindow(project_root=project_root, initial_path=project_root / "sample.md") window.show() @@ -48,6 +61,21 @@ def main() -> int: 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") + original_file_groups = empty_window.document_file_groups + empty_window.document_file_groups = ("markdown", "python", "cpp") + empty_window._refresh_document_entries(force=True) + code_suffixes = {".py", ".c", ".cc", ".cxx", ".cpp", ".h", ".hh", ".hxx", ".hpp"} + if not any(entry.path.suffix.lower() in code_suffixes for entry in empty_window.entries): + checks.append("project_optional_code_files") + empty_window.open_document(project_root / "sample.md", add_history=False) + empty_window.document_file_groups = ("python",) + empty_window._refresh_document_entries(force=True) + if any(entry.path.suffix.lower() in {".md", ".markdown"} for entry in empty_window.entries): + checks.append("project_file_type_filter_entries") + if (project_root / "sample.md").resolve() in empty_window.path_to_item: + checks.append("project_file_type_filter_tree") + empty_window.document_file_groups = original_file_groups + empty_window._refresh_document_entries(force=True) tree_root = empty_window.tree.topLevelItem(0) if tree_root is None or not tree_root.isExpanded(): checks.append("file_tree_root_expanded") @@ -124,6 +152,13 @@ def main() -> int: checks.append("current_file") if window.tabs.count() < 1: checks.append("tabs") + if not window.tabs.isMovable(): + checks.append("tabs_movable") + tab_bar = window.tabs.tabBar() + if tab_bar.expanding(): + checks.append("tabs_non_expanding") + if hasattr(tab_bar, "changeCurrentOnDrag") and tab_bar.changeCurrentOnDrag(): + checks.append("tabs_no_drag_switch") if window._welcome_tab_index() >= 0: checks.append("welcome_closed_for_document") if window.windowIcon().isNull(): @@ -132,26 +167,72 @@ def main() -> int: checks.append("app_icon") if not isinstance(window.tabs.currentWidget(), ReaderView): checks.append("reader_view") + if abs(window.wheel_scroll_speed - 1.0) > 0.01: + checks.append("wheel_scroll_speed_default") + window.wheel_scroll_speed = 1.7 + window._apply_wheel_scroll_speed_to_tabs() + current_reader = window.tabs.currentWidget() + if isinstance(current_reader, ReaderView) and abs(float(current_reader.property("wheel_scroll_speed") or 0) - 1.7) > 0.01: + checks.append("wheel_scroll_speed_tab_property") if window.status_label.objectName() != "statusPathLabel": checks.append("status_label_theme_name") if hasattr(window, "find_box"): checks.append("toolbar_find_box_visible") if not all( hasattr(window, name) - for name in ("panel_open_folder_button", "find_current_button", "find_previous_button", "find_next_button") + for name in ( + "panel_open_folder_button", + "panel_refresh_button", + "find_current_button", + "find_previous_button", + "find_next_button", + ) ): checks.append("panel_find_buttons") - elif window.panel_open_folder_button.icon().isNull(): - checks.append("panel_open_folder_icon") - elif [window.find_current_button.text(), window.find_previous_button.text(), window.find_next_button.text()] != [ - "搜索", - "上一个", - "下一个", - ]: - checks.append("panel_find_button_order") + elif window.panel_open_folder_button.icon().isNull() or window.panel_refresh_button.icon().isNull(): + checks.append("panel_icon_buttons") + elif any( + button.text() + for button in ( + window.find_current_button, + window.find_previous_button, + window.find_next_button, + ) + ): + checks.append("panel_find_button_text") + elif any( + button.icon().isNull() + for button in ( + window.find_current_button, + window.find_previous_button, + window.find_next_button, + ) + ): + checks.append("panel_find_button_icons") expected_search_height = max(22, round(window.fontMetrics().height() * 1.5)) if abs(window.search_box.height() - expected_search_height) > 4: checks.append("panel_search_box_height") + settings_dialog = SettingsDialog( + AppPreferences( + theme=window.theme, + theme_color=window.theme_color, + theme_background=window.theme_background, + font_scale=window.font_scale, + wheel_scroll_speed=1.4, + auto_refresh=window.auto_refresh_enabled, + auto_refresh_mode=window.auto_refresh_mode, + auto_refresh_delay_ms=window.auto_refresh_delay_ms, + non_preview_action=window.non_preview_action, + document_file_groups=window.document_file_groups, + ), + window, + ) + if abs(settings_dialog.wheel_scroll_speed_spin.value() - 1.4) > 0.01: + checks.append("settings_wheel_scroll_speed") + settings_dialog.wheel_scroll_speed_spin.setValue(2.2) + if abs(settings_dialog.preferences().wheel_scroll_speed - 2.2) > 0.01: + checks.append("settings_wheel_scroll_speed_value") + settings_dialog.close() if window.findChildren(QToolBar): checks.append("main_toolbar_removed") if hasattr(window, "toolbar_font_label") or hasattr(window, "toolbar_font_size_label"): @@ -160,6 +241,10 @@ def main() -> int: checks.append("export_pdf_action") if not window.export_html_action.isEnabled(): checks.append("export_html_action") + if not window.export_docx_action.isEnabled(): + checks.append("export_docx_action") + if not window.export_mhtml_action.isEnabled(): + checks.append("export_mhtml_action") if hasattr(window, "theme_action"): checks.append("theme_toolbar_action") if hasattr(window, "home_action"): @@ -174,6 +259,80 @@ def main() -> int: if not hasattr(window, "theme_menu"): checks.append("theme_menu") menu_titles = [action.text() for action in window.menuBar().actions()] + if "样式" not in menu_titles or not hasattr(window, "style_menu"): + checks.append("style_menu") + style_values = { + str(action.data()) + for action in window.document_style_group.actions() + if action.data() is not None + } + if not {"default", "compact", "serif", "wide", "focus"}.issubset(style_values): + checks.append("style_builtin_options") + style_dialog = DocumentStyleEditorDialog( + { + "name": "图形样式", + "rules": { + "paragraph": { + "font_size": 18, + "line_height_value": 1.6, + "line_height_unit": "multiple", + "first_line_indent_chars": 2, + "space_after_value": 6, + "space_after_unit": "pt", + } + }, + "extra_css": ".reader strong { color: #0057b8; }", + }, + parent=window, + ) + style_dialog.apply_theme(window.theme_color) + style_payload = style_dialog.style_payload() + if ( + "font-size: 18px" not in str(style_payload.get("css")) + or "text-indent: 2em" not in str(style_payload.get("css")) + or "margin-bottom: 6pt" not in str(style_payload.get("css")) + ): + checks.append("style_editor_payload") + if hasattr(style_dialog, "use_chinese_font_checkbox") or hasattr(style_dialog, "use_english_font_checkbox"): + checks.append("style_font_checkboxes_removed") + if style_dialog.chinese_font_combo.maximumWidth() > 315 or style_dialog.english_font_combo.maximumWidth() > 315: + checks.append("style_font_combo_width") + if style_dialog.findChild(QPushButton, "styleResetButton").maximumWidth() > 128: + checks.append("style_reset_button_width") + if "QTabWidget::pane" not in style_dialog.styleSheet() or "border: 1px solid" not in style_dialog.styleSheet(): + checks.append("style_dialog_theme") + style_dialog.close() + previous_style = window.document_style_id + window._set_document_style("compact") + if window.document_style_id != "compact" or "max-width: 1120px" not in window._document_style_css(): + checks.append("style_apply_builtin") + if window.delete_custom_style_action.isEnabled(): + checks.append("style_delete_builtin_enabled") + style_test_path = project_root / "style_smoke.mdhelper-style" + try: + window._write_document_style_file(style_test_path, "compact") + imported_style_id = window._import_document_style_file(style_test_path) + if imported_style_id not in window.custom_document_styles: + checks.append("style_import_file") + window.document_style_id = imported_style_id + window._build_style_menu() + if not window.delete_custom_style_action.isEnabled(): + checks.append("style_delete_custom_disabled") + exported_payload = window._style_payload_for_id(imported_style_id) + if exported_payload.get("name") != "紧凑参考" or "max-width: 1120px" not in str(exported_payload.get("css")): + checks.append("style_payload") + original_question = QMessageBox.question + QMessageBox.question = lambda *args, **kwargs: QMessageBox.StandardButton.Yes + try: + window.delete_current_custom_document_style() + finally: + QMessageBox.question = original_question + if imported_style_id in window.custom_document_styles or window.document_style_id != "default": + checks.append("style_delete_custom") + finally: + style_test_path.unlink(missing_ok=True) + window.document_style_id = previous_style + window._build_style_menu() if "关于" not in menu_titles or menu_titles.index("关于") <= menu_titles.index("主题"): checks.append("about_menu_position") if window.about_action not in window.about_menu.actions(): @@ -371,6 +530,35 @@ def main() -> int: pdf_test_path.unlink(missing_ok=True) except OSError: pass + docx_test_path = project_root / "__gui_smoke_export.docx" + try: + if window.export_docx_to_path(docx_test_path) is None: + checks.append("export_docx_result") + elif not docx_test_path.exists(): + checks.append("export_docx_write") + else: + with zipfile.ZipFile(docx_test_path) as package: + if "word/document.xml" not in package.namelist(): + checks.append("export_docx_package") + finally: + try: + docx_test_path.unlink(missing_ok=True) + except OSError: + pass + mhtml_test_path = project_root / "__gui_smoke_export.mhtml" + try: + if window.export_mhtml_to_path(mhtml_test_path) is None: + checks.append("export_mhtml_result") + mhtml_loop = QEventLoop() + QTimer.singleShot(3000, mhtml_loop.quit) + mhtml_loop.exec() + if not mhtml_test_path.exists() or mhtml_test_path.stat().st_size <= 0: + checks.append("export_mhtml_write") + finally: + try: + mhtml_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") @@ -634,6 +822,8 @@ def main() -> int: checks.append("config_theme_background") if snapshot.get("reader", {}).get("document_tree_label_mode") not in {"title", "filename"}: checks.append("config_tree_label_mode") + if snapshot.get("reader", {}).get("wheel_scroll_speed") is None: + checks.append("config_wheel_scroll_speed") window._apply_configuration( { "reader": { @@ -641,6 +831,7 @@ def main() -> int: "theme_background": "peony", "math_engine": "katex", "font_scale": 1.2, + "wheel_scroll_speed": 1.8, "document_font_family": "Microsoft YaHei UI", "document_font_size": 18, "document_tree_label_mode": "filename", @@ -659,6 +850,8 @@ def main() -> int: 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 abs(window.wheel_scroll_speed - 1.8) > 0.01: + checks.append("config_apply_wheel_scroll_speed") 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: diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..4392fb7 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import zipfile +import shutil +from pathlib import Path + +from mdhelper.app import parse_arguments, project_and_initial_path, resolve_launch_path +from mdhelper.docx_exporter import export_markdown_to_docx +from mdhelper.logging_config import setup_logging + + +def test_parse_arguments_accepts_folder_alias() -> None: + args = parse_arguments(["--folder", "docs"]) + + assert args.project_root == "docs" + + +def test_resolve_launch_path_finds_relative_folder_name(tmp_path: Path, monkeypatch) -> None: + launch_root = tmp_path / "launcher" + docs_root = launch_root / "docs_project" + work_root = tmp_path / "work" + docs_root.mkdir(parents=True) + work_root.mkdir() + monkeypatch.chdir(work_root) + + resolved = resolve_launch_path("docs_project", (Path.cwd(), launch_root)) + + assert resolved == docs_root.resolve() + + +def test_project_and_initial_path_uses_file_parent(tmp_path: Path) -> None: + markdown_file = tmp_path / "guide.md" + markdown_file.write_text("# Guide\n", encoding="utf-8") + + project_root, initial_path = project_and_initial_path(markdown_file, None) + + assert project_root == tmp_path + assert initial_path == markdown_file + + +def test_project_and_initial_path_uses_folder_directly(tmp_path: Path) -> None: + project_root, initial_path = project_and_initial_path(tmp_path, None) + + assert project_root == tmp_path + assert initial_path is None + + +def test_export_markdown_to_docx_writes_word_document(tmp_path: Path) -> None: + output_path = tmp_path / "guide.docx" + + export_markdown_to_docx( + "# 标题\n\n正文 **加粗** 和 `代码`。\n\n- 项目一\n- 项目二\n\n| A | B |\n| - | - |\n| 1 | 2 |\n", + output_path, + engine="builtin", + ) + + assert output_path.exists() + with zipfile.ZipFile(output_path) as package: + names = set(package.namelist()) + document_xml = package.read("word/document.xml").decode("utf-8") + + assert {"[Content_Types].xml", "_rels/.rels", "word/document.xml", "word/styles.xml"} <= names + assert "标题" in document_xml + assert "项目一" in document_xml + assert "" in document_xml + + +def test_export_markdown_to_docx_python_docx_engine(tmp_path: Path) -> None: + output_path = tmp_path / "python_docx.docx" + + export_markdown_to_docx("# 标题\n\n正文\n", output_path, engine="python-docx") + + assert output_path.exists() + with zipfile.ZipFile(output_path) as package: + document_xml = package.read("word/document.xml").decode("utf-8") + assert "标题" in document_xml + + +def test_export_markdown_to_docx_pandoc_engine_when_available(tmp_path: Path) -> None: + if shutil.which("pandoc") is None: + return + output_path = tmp_path / "pandoc.docx" + source_path = tmp_path / "source.md" + source_path.write_text("# 标题\n\n正文\n", encoding="utf-8") + + export_markdown_to_docx(source_path.read_text(encoding="utf-8"), output_path, engine="pandoc", source_path=source_path) + + assert output_path.exists() + with zipfile.ZipFile(output_path) as package: + assert "word/document.xml" in package.namelist() + + +def test_setup_logging_uses_configured_writable_user_directory(tmp_path: Path, monkeypatch) -> None: + log_dir = tmp_path / "user_logs" + monkeypatch.setenv("MDHELPER_LOG_DIR", str(log_dir)) + + log_path = setup_logging(tmp_path / "install_root") + + assert log_path == log_dir / "mdhelper.log" + assert log_path.exists() diff --git a/tests/test_renderer.py b/tests/test_renderer.py index 84dafba..b4fb771 100644 --- a/tests/test_renderer.py +++ b/tests/test_renderer.py @@ -2,13 +2,16 @@ from pathlib import Path from tempfile import TemporaryDirectory from mdhelper.app import parse_arguments +from mdhelper import search as search_module from mdhelper.doc_check import check_documents -from mdhelper.document_tree import discover_documents +from mdhelper.code_structure import extract_code_headings +from mdhelper.document_tree import DocumentEntry, MAX_DISCOVERABLE_CODE_BYTES, discover_documents from mdhelper.history import HistoryItem, NavigationHistory from mdhelper.main_window import re_find_markdown_links from mdhelper.markdown_utils import extract_headings from mdhelper.markdown_renderer import MarkdownRenderer from mdhelper.search import SearchIndex, search_entries +from mdhelper.style_dialog import build_document_style_css def test_sample_media_and_code_rendering() -> None: @@ -34,6 +37,14 @@ def test_sample_media_and_code_rendering() -> None: assert "copy-code-button" in html assert "code-line" in html assert "toggle-code-button" in html + assert 'toggle.textContent = "收起";' in html + assert 'block.classList.add("is-collapsible");' in html + assert 'block.classList.add("is-collapsible", "is-collapsed")' not in html + assert '${line || " "}' in html + assert '.join("");' in html + assert "#569cd6" in html + assert "#ce9178" in html + assert "#1e1e1e" in html assert "image-lightbox" in html assert "image-lightbox__toolbar" in html assert 'data-action="fit"' in html @@ -52,6 +63,8 @@ def test_sample_media_and_code_rendering() -> None: assert "flowchart LR" in html assert "math-block" in html assert "data-math-engine=\"katex\"" in html + assert "data-wheel-scroll-speed=\"1.0\"" in html + assert "configuredWheelSpeed" in html assert "--reader-font-family:" in html assert "--reader-font-size:" in html assert "katex.min.css" in html @@ -68,10 +81,18 @@ def test_sample_media_and_code_rendering() -> None: project_root / "sample.md", document_font_family="Microsoft YaHei UI", document_font_size=18, + wheel_scroll_speed=2.4, ) + assert "data-wheel-scroll-speed=\"2.4\"" in custom_font_html assert '"Microsoft YaHei UI"' in custom_font_html assert "--reader-font-size: 18px;" in custom_font_html + custom_style_html = renderer.render_file( + project_root / "sample.md", + document_style_css=".reader { max-width: 720px; }", + ) + assert ".reader { max-width: 720px; }" in custom_style_html + def test_heading_extraction_matches_rendered_anchor() -> None: project_root = Path(__file__).resolve().parent.parent @@ -82,6 +103,50 @@ def test_heading_extraction_matches_rendered_anchor() -> None: assert any(heading.title == "10. Mermaid 图表示例" for heading in headings) +def test_document_style_builder_supports_word_like_paragraph_options() -> None: + css = build_document_style_css( + { + "paragraph": { + "chinese_font_family": "Microsoft YaHei UI", + "english_font_family": "Times New Roman", + "font_size": 18, + "line_height_value": 1.7, + "line_height_unit": "multiple", + "first_line_indent_chars": 2, + "space_before_value": 6, + "space_before_unit": "pt", + "space_after_value": 0.6, + "space_after_unit": "multiple", + }, + "h2": { + "bold": True, + "hanging_indent_chars": 1.5, + }, + "blockquote": { + "chinese_font_family": "KaiTi", + "english_font_family": "Georgia", + }, + }, + ".reader strong { color: #0057b8; }", + ) + + assert ".reader p" in css + assert 'font-family: "Times New Roman", "Microsoft YaHei UI"' in css + assert "font-size: 18px;" in css + assert "line-height: 1.7;" in css + assert "text-indent: 2em;" in css + assert "margin-top: 6pt;" in css + assert "margin-bottom: 0.6em;" in css + assert ".reader h2" in css + assert "font-weight: 700;" in css + assert "padding-left: 1.5em;" in css + assert "text-indent: -1.5em;" in css + assert ".reader blockquote p" in css + assert ".reader .admonition p" in css + assert 'font-family: "Georgia", "KaiTi"' in css + assert ".reader strong { color: #0057b8; }" in css + + def test_full_text_search_finds_document_body() -> None: project_root = Path(__file__).resolve().parent.parent entries = discover_documents(project_root) @@ -142,7 +207,7 @@ def test_document_checker_reports_missing_local_target() -> None: def test_app_arguments_support_initial_file_and_check_mode() -> None: args = parse_arguments(["sample.md"]) - assert args.file == "sample.md" + assert args.path == "sample.md" assert not args.check check_args = parse_arguments(["--check", "--project-root", "."]) @@ -162,3 +227,119 @@ def test_navigation_history_preserves_scroll_position() -> None: assert history.current is not None assert history.current.scroll_y == 120 assert history.back() == first + + +def test_document_discovery_filters_optional_code_groups(tmp_path: Path) -> None: + (tmp_path / "guide.md").write_text("# Guide\n", encoding="utf-8") + (tmp_path / "tool.py").write_text("def run():\n return 1\n", encoding="utf-8") + (tmp_path / "engine.cpp").write_text("int solve() { return 1; }\n", encoding="utf-8") + + default_entries = discover_documents(tmp_path) + all_entries = discover_documents(tmp_path, ("markdown", "python", "cpp")) + + assert [entry.path.name for entry in default_entries] == ["guide.md"] + assert {entry.path.name for entry in all_entries} == {"guide.md", "tool.py", "engine.cpp"} + + +def test_document_discovery_prunes_excluded_directories(tmp_path: Path) -> None: + (tmp_path / "guide.md").write_text("# Guide\n", encoding="utf-8") + hidden_git = tmp_path / ".git" + hidden_git.mkdir() + (hidden_git / "hidden.md").write_text("# Hidden\n", encoding="utf-8") + build_dir = tmp_path / "build" + build_dir.mkdir() + (build_dir / "generated.py").write_text("def generated():\n return 1\n", encoding="utf-8") + + entries = discover_documents(tmp_path, ("markdown", "python")) + + assert {entry.relative_path for entry in entries} == {"guide.md"} + + +def test_search_index_reads_body_lazily(tmp_path: Path, monkeypatch) -> None: + path = tmp_path / "guide.md" + path.write_text("placeholder", encoding="utf-8") + entry = DocumentEntry(path=path, title="Guide", relative_path="guide.md") + calls: list[Path] = [] + + def fake_read_text(read_entry: DocumentEntry) -> str: + calls.append(read_entry.path) + return "body needle" + + monkeypatch.setattr(search_module, "_read_text", fake_read_text) + + index = search_module.SearchIndex([entry]) + + assert calls == [] + assert index.search("Guide")[0].match_kind == "标题" + assert calls == [] + assert index.search("needle")[0].match_kind == "正文" + assert calls == [entry.path] + +def test_code_file_rendering_uses_highlighting_and_line_anchors(tmp_path: Path) -> None: + code_path = tmp_path / "tool.py" + source = "class Runner:\n def run(self):\n return 1\n" + renderer = MarkdownRenderer(tmp_path) + + html = renderer.render_code_source(source, code_path, language="python") + + assert "code-file-view" in html + assert "language-python" in html + assert "line-1" in html + assert "Runner" in html + + +def test_code_headings_extract_python_and_cpp_symbols(tmp_path: Path) -> None: + python_path = tmp_path / "tool.py" + cpp_path = tmp_path / "engine.cpp" + python_source = "class Runner:\n def run(self):\n return 1\n\nasync def main():\n return None\n" + cpp_source = "struct Node { int value; };\n\nint solve(int value) { return value; }\n" + + python_headings = extract_code_headings(python_path, python_source) + cpp_headings = extract_code_headings(cpp_path, cpp_source) + + assert [heading.title for heading in python_headings] == ["class Runner", "def run", "async def main"] + assert [heading.slug for heading in python_headings] == ["line-1", "line-2", "line-5"] + assert any(heading.title == "struct Node" for heading in cpp_headings) + assert any(heading.title == "function solve" for heading in cpp_headings) + + +def test_search_index_reads_optional_code_documents(tmp_path: Path) -> None: + (tmp_path / "tool.py").write_text("def calculate_magic_value():\n return 42\n", encoding="utf-8") + entries = discover_documents(tmp_path, ("python",)) + + matches = SearchIndex(entries).search("magic_value") + + assert matches + assert matches[0].entry.path.name == "tool.py" + assert matches[0].match_kind == "正文" + + +def test_large_code_files_are_not_auto_discovered(tmp_path: Path) -> None: + (tmp_path / "guide.md").write_text("# Guide\n", encoding="utf-8") + large_code = tmp_path / "large_module.py" + large_code.write_text("# large\n" + ("x = 1\n" * ((MAX_DISCOVERABLE_CODE_BYTES // 6) + 2)), encoding="utf-8") + + entries = discover_documents(tmp_path, ("markdown", "python")) + + assert {entry.path.name for entry in entries} == {"guide.md"} + + +def test_code_search_reads_gbk_source(tmp_path: Path) -> None: + source_path = tmp_path / "legacy.py" + source_path.write_text("# 中文注释\ndef legacy_name():\n return '命中'\n", encoding="gbk") + entries = discover_documents(tmp_path, ("python",)) + + matches = SearchIndex(entries).search("命中") + + assert matches + assert matches[0].entry.path.name == "legacy.py" + + +def test_code_headings_read_gbk_source_when_source_not_supplied(tmp_path: Path) -> None: + source_path = tmp_path / "legacy.py" + source_path.write_text("class 中文类:\n def run(self):\n return 1\n", encoding="gbk") + + headings = extract_code_headings(source_path) + + assert headings[0].title == "class 中文类" + assert headings[1].title == "def run" diff --git a/todo.md b/todo.md index 71a8f8f..8eb6ebe 100644 --- a/todo.md +++ b/todo.md @@ -9,10 +9,10 @@ 风险与注意事项: -- 内置保存和外部编辑器保存都会触发文件监听,需要区分“程序自己保存”和“外部变更”。 -- 当前多标签页可以打开同一个文件,保存后要明确哪些标签页刷新。 -- 编辑时关闭窗口或切换文件要防止未保存内容丢失。 -- 非 UTF-8 编码文件可能读取失败,需要给出友好的错误提示。 +- [x] 内置保存和外部编辑器保存都会触发文件监听:使用 `internal_save_paths` 区分本软件保存和外部变更。 +- [x] 当前多标签页可以打开同一个文件:保存和自动刷新会同步刷新已打开的同一文档标签、目录、文档树和搜索索引。 +- [x] 编辑时关闭窗口或切换文件要防止未保存内容丢失:编辑标签关闭前调用 `confirm_close()`,未保存时要求用户确认。 +- [x] 非 UTF-8 编码文件可能读取失败:编辑和阅读渲染路径均捕获 `UnicodeDecodeError` 并显示友好提示。 ## 2. 分屏编辑与预览 @@ -22,9 +22,9 @@ 风险与注意事项: -- WebEngine 渲染较重,实时预览需要节流。 -- 标题 slug、Mermaid、公式和媒体资源都依赖完整渲染,局部刷新不一定可靠。 -- 分屏会改变主界面布局,需要和现有多标签、主题、目录栏协同。 +- [x] WebEngine 渲染较重,实时预览需要节流:预览刷新使用 350ms 单次 `QTimer` 防抖。 +- [x] 标题 slug、Mermaid、公式和媒体资源依赖完整渲染:预览和阅读页保持完整渲染流程,不做不可靠的局部刷新。 +- [x] 分屏会改变主界面布局:编辑器已嵌入标签页,并同步主题、目录栏和多标签状态。 ## 3. 编辑体验增强 @@ -35,9 +35,9 @@ 风险与注意事项: -- 自动保存可能覆盖用户不想保存的临时改动,默认应谨慎。 -- 查找/替换要区分“源码编辑器内查找”和“阅读页页内查找”。 -- 行号和大文件语法高亮可能影响性能。 +- [x] 自动保存可能覆盖用户不想保存的临时改动:自动保存只写入草稿,不直接覆盖正式文件,恢复前需要用户确认。 +- [x] 查找/替换要区分“源码编辑器内查找”和“阅读页页内查找”:源码编辑器和阅读页使用独立查找控件和状态。 +- [x] 行号和大文件语法高亮可能影响性能:行号只绘制可见块,超大源码自动关闭 Markdown 语法高亮。 ## 4. 文件打开与链接策略继续完善 @@ -47,8 +47,8 @@ 风险与注意事项: -- 记住的程序路径可能被移动或卸载,打开前需要校验。 -- 不应强行在标签页内展示所有媒体,系统默认程序或用户指定程序更稳。 +- [x] 记住的程序路径可能被移动或卸载:打开前校验路径,缺失或启动失败时自动清除记录并提示。 +- [x] 不应强行在标签页内展示所有媒体:非预览文件沿用询问/默认程序/用户指定程序策略,视频提供内置播放和外部打开两种入口。 ## 5. GUI 自动化测试 @@ -60,8 +60,8 @@ 风险与注意事项: -- Qt WebEngine 在无界面环境下偶发不稳定,测试要保留最小烟雾测试和可重复的等待条件。 -- 涉及系统默认程序的测试应避免真的启动外部播放器。 +- [x] Qt WebEngine 在无界面环境下偶发不稳定:保留 `tests/gui_smoke.py` 离屏烟雾测试,并使用明确等待条件。 +- [x] 涉及系统默认程序的测试应避免真的启动外部播放器:GUI smoke 中替换外部启动函数,只验证路由和参数。 ## 6. 发布与打包 @@ -71,8 +71,8 @@ 风险与注意事项: -- WebEngine 资源和离线 Mermaid/KaTeX/MathJax 文件容易漏打包。 -- 单文件 exe 首次启动会解压,启动日志路径要能写入。 +- [x] WebEngine 资源和离线 Mermaid/KaTeX/MathJax 文件容易漏打包:`MDHelper.spec` 明确包含 `mdhelper/resources`、示例文档和媒体资源,并保留 PyInstaller hook 路径。 +- [x] 单文件 exe 首次启动会解压,启动日志路径要能写入:日志目录优先使用用户可写目录,并提供临时目录兜底。 ## 7. Markdown 编辑器继续完善 @@ -141,8 +141,23 @@ 风险与注意事项: -- 冲突检测要避免误判,也要避免静默覆盖外部工具已经保存的内容。 -- “另存为”后要同步文档树、最近文件、搜索索引、当前标签页标题和文件监听。 -- 草稿不能直接覆盖正式文件,只能在用户确认后恢复。 -- 分屏同步滚动只能做近似同步,Mermaid、公式和图片会让源码高度与预览高度不一致。 -- 插入工具栏要操作选区,不能破坏已有文本。 +- [x] 冲突检测要避免误判,也要避免静默覆盖外部工具已经保存的内容:保存前比较文件签名,检测到外部变更时要求用户确认。 +- [x] “另存为”后要同步文档树、最近文件、搜索索引、当前标签页标题和文件监听:另存为保存后统一走刷新与标签状态更新流程。 +- [x] 草稿不能直接覆盖正式文件,只能在用户确认后恢复:草稿恢复通过确认框选择,拒绝后清理草稿。 +- [x] 分屏同步滚动只能做近似同步,Mermaid、公式和图片会让源码高度与预览高度不一致:按滚动比例同步,并保留标题目录精确跳转。 +- [x] 插入工具栏要操作选区,不能破坏已有文本:插入模板通过当前选区替换,并保留无选区占位内容。 + +## 13. 可选代码文档展示 + +- [x] 增加“展示文件类型”设置,支持 Markdown、Python、C/C++ 分组开关。 +- [x] 将文档发现逻辑改为按用户选择的扩展名过滤,默认只展示 Markdown/网页文档。 +- [x] Python、C/C++ 文件在阅读页中用 Pygments 高亮展示,不再只作为普通文本预览。 +- [x] Python 使用 AST 提取类、函数作为右侧目录;C/C++ 先用轻量正则提取函数/类/结构体。 +- [x] 搜索索引和自动刷新监听跟随当前展示文件类型更新。 +- [x] 补充单元测试和 GUI smoke,覆盖配置过滤、代码高亮、代码目录。 + +风险与注意事项: + +- [x] 大型源码目录容易让文件树和搜索索引变慢:代码文件展示默认关闭,并跳过超大代码文件,搜索索引只读取安全大小内的文本。 +- [x] 代码文件编码可能不是 UTF-8:统一使用 `utf-8-sig`、`utf-8`、`gbk`、`latin-1` 回退读取。 +- [x] C/C++ 结构目录用正则只能做基础识别:按“基础结构目录”处理,避开明显声明和控制语句,不承诺完整语法解析。