From 72fb37fc857367e03a7af95d573064f1d7cf87ad Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 29 Oct 2026 19:40:45 +0800 Subject: [PATCH] refactor: unify configuration validation and persistence --- docs/architecture.md | 4 + mdhelper/document_session.py | 6 +- mdhelper/export_workflow.py | 13 +- mdhelper/main_window.py | 388 +++-------------------------------- mdhelper/preferences.py | 222 ++++++++++++++++++++ mdhelper/style_presets.py | 96 +++++++++ tests/gui_smoke.py | 36 +++- tests/test_preferences.py | 55 +++++ 8 files changed, 443 insertions(+), 377 deletions(-) create mode 100644 mdhelper/preferences.py create mode 100644 mdhelper/style_presets.py create mode 100644 tests/test_preferences.py diff --git a/docs/architecture.md b/docs/architecture.md index f350d79..0fd4153 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -23,6 +23,10 @@ `ExportSnapshot` 同时保存文本与 `RenderOptions`,导出期间的标签或外观变化不改变当前任务。PDF 和 MHTML 各有独立任务对象,共用 `ExportLifecycle` 的进度窗口、截止计时和页面资源就绪检查。`mhtml_archive.py` 只处理归档数据,不创建 Qt 对象。 +## 配置与迁移 + +`preferences.py` 定义 `ReaderPreferences` 和 `ApplicationConfiguration`。本地设置与 JSON 导入共用字段、取值检查和旧版迁移规则;`ConfigurationStore` 负责持久化。页面设置保留旧版 PDF 页边距的读取方式。窗口几何状态和草稿仍由各自的界面、文档组件管理。内置文档样式集中在 `style_presets.py`。 + ## 验证约定 每个重构阶段独立提交。运行单元测试,并按改动范围运行 `gui_smoke.py`、`improvements_smoke.py` 和 `reliability_smoke.py`。涉及浏览器生命周期的调整必须检查欢迎页、首次打开文件、标签切换以及预览滚动;涉及保存的调整必须检查保存失败、取消、另存为和后台标签。 diff --git a/mdhelper/document_session.py b/mdhelper/document_session.py index 19ed7d7..8ada24d 100644 --- a/mdhelper/document_session.py +++ b/mdhelper/document_session.py @@ -70,13 +70,13 @@ class DraftStore: "file_mtime_ns": signature[0] if signature else 0, "file_size": signature[1] if signature else 0, } - self._persist() + self.persist() def clear(self, path: Path) -> None: self.entries.pop(str(path.resolve()), None) - self._persist() + self.persist() - def _persist(self) -> None: + def persist(self) -> None: self.settings.setValue(DRAFTS_KEY, json.dumps(self.entries, ensure_ascii=False)) def sync(self) -> None: diff --git a/mdhelper/export_workflow.py b/mdhelper/export_workflow.py index 98ba21b..2e3b498 100644 --- a/mdhelper/export_workflow.py +++ b/mdhelper/export_workflow.py @@ -16,6 +16,7 @@ from .export_settings import PageSettings from .file_versions import atomic_write from .markdown_utils import Heading from .render_options import RenderOptions +from .preferences import ConfigurationStore from typing import Callable from .pdf_export_task import PdfExportController from .pdf_export import PdfExportSettingsDialog, PdfMargins @@ -46,6 +47,7 @@ class ExportContext: class ExportController: def __init__(self, context: ExportContext): self.context = context + self.configuration = ConfigurationStore(context.settings) self._export_jobs = set() self._mhtml_exports = set() self._pdf_controller = None @@ -70,21 +72,14 @@ class ExportController: return confirm_export(self.context.parent, check_export(snapshot.source, snapshot.path, kind, snapshot.style.get("css", ""))) def _saved_page_settings(self) -> PageSettings: - try: - value = json.loads(str(self.context.settings.value("export/page_settings", "{}"))) - if isinstance(value, dict) and value: - return PageSettings.from_dict(value).normalized() - except (TypeError, ValueError): - pass - margins = self._saved_pdf_margins() - return PageSettings(top=margins.top, bottom=margins.bottom, left=margins.left, right=margins.right) + return self.configuration.load_page_settings() def _choose_page_settings(self) -> PageSettings | None: dialog = PdfExportSettingsDialog(self._saved_page_settings(), self.context.parent) if dialog.exec() != QDialog.DialogCode.Accepted: return None settings = dialog.page_settings() - self.context.settings.setValue("export/page_settings", json.dumps(asdict(settings), ensure_ascii=False)) + self.configuration.save_page_settings(settings) return settings def _saved_pdf_margins(self) -> PdfMargins: diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index a384212..da4086d 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -9,6 +9,7 @@ import os import re import shutil from pathlib import Path +from dataclasses import fields, asdict from urllib.parse import unquote, urlsplit from PySide6.QtCore import QEventLoop, QFile, QFileSystemWatcher, QPoint, QProcess, QSettings, QSignalBlocker, QSize, QThreadPool, QTimer, QUrl, Qt, Slot @@ -58,12 +59,14 @@ from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback from .startup_scan import StartupScan from .export_workflow import ExportController, ExportContext, ExportSnapshot from .render_options import RenderOptions, render_document +from .preferences import ReaderPreferences, ApplicationConfiguration, ConfigurationStore, normalize_custom_styles from .document_session import DocumentStore, DraftStore, DocumentCloseController, CloseChoice from .document_resources import analyze_document, resolve_local_reference from .tab_controller import TabController, document_path from .reader_widgets import ReaderPage, ReaderBridge, ReaderView, ReaderTabHost, CompactTreeDelegate from .video_player import VideoPlayerWidget from .ui_theme import navigation_theme, apply_title_bar_style +from .style_presets import DOCUMENT_STYLE_PRESETS BOOKMARKS_SETTING_KEY = "bookmarks/items" @@ -89,101 +92,6 @@ def available_new_markdown_path(directory: Path) -> Path: return candidate -DOCUMENT_STYLE_PRESETS = { - "default": { - "name": "默认阅读", - "css": "", - }, - "compact": { - "name": "紧凑参考", - "css": """ -.reader { - max-width: var(--reader-paper-width); - 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: var(--reader-paper-width); - 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: var(--reader-paper-width); - 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: var(--reader-paper-width); - 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"), @@ -248,6 +156,7 @@ class MainWindow(QMainWindow): self._startup_initial_path = initial_path self._startup_prompt = prompt_for_project self.settings = QSettings("MDHelper", "MDHelper") + self.configurations = ConfigurationStore(self.settings) self.documents = DocumentStore() self.drafts = DraftStore(self.settings, self.documents) self.document_closer = DocumentCloseController(self.drafts, self._choose_editor_close, lambda editor: self._save_editor_tab(editor, editor.path, editor.source_text(), editor.file_signature)) @@ -2720,138 +2629,30 @@ class MainWindow(QMainWindow): ), ) + def _configuration_data(self) -> ApplicationConfiguration: + reader = ReaderPreferences(**{item.name: getattr(self, "auto_refresh_enabled" if item.name == "auto_refresh" else item.name) + for item in fields(ReaderPreferences)}) + return ApplicationConfiguration(reader, str(self.project_root) if self.has_project else "", + [str(path) for path in self.recent_files], self.bookmarks, self.scroll_positions, + self.external_applications, self._saved_page_settings()) + + def _apply_configuration_data(self, config: ApplicationConfiguration) -> None: + for item in fields(ReaderPreferences): + setattr(self, "auto_refresh_enabled" if item.name == "auto_refresh" else item.name, getattr(config.reader, item.name)) + self.recent_files = [Path(path) for path in config.recent_files] + self.bookmarks = config.bookmarks + self.scroll_positions = config.scroll_positions + self.external_applications = config.external_applications + def _configuration_snapshot(self) -> dict[str, object]: - return { - "app": "MDHelper", - "version": __version__, - "reader": { - "theme": self.theme, - "theme_color": self.theme_color, - "theme_background": self.theme_background, - "font_scale": self.font_scale, - "wheel_scroll_speed": self.wheel_scroll_speed, - "reader_width_scale": self.reader_width_scale, - "ui_font_family": self.ui_font_family, - "ui_font_point_size": self.ui_font_point_size, - "document_font_family": self.document_font_family, - "document_font_size": self.document_font_size, - "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], - "bookmarks": self.bookmarks, - "scroll_positions": self.scroll_positions, - "external_applications": self.external_applications, - } + return self._configuration_data().to_payload(__version__) def _apply_configuration(self, payload: dict[str, object]) -> None: - reader = payload.get("reader", {}) - if isinstance(reader, dict): - theme_color = str(reader.get("theme_color", self.theme_color)) - if theme_color in THEME_COLOR_VALUES: - self._set_theme_color(theme_color) - - theme_background = str(reader.get("theme_background", self.theme_background)) - self.theme_background = self._normalized_theme_background(theme_background) - - theme = str(reader.get("theme", self.theme)) - if "theme_color" not in reader and theme in {"light", "dark"}: - self._set_theme_color("black" if theme == "dark" else "white") - - math_engine = str(reader.get("math_engine", self.math_engine)) - if math_engine in {"katex", "mathjax"}: - self.math_engine = math_engine - - try: - self.font_scale = max(0.8, min(1.6, float(reader.get("font_scale", self.font_scale)))) - except (TypeError, ValueError): - pass - self.wheel_scroll_speed = self._normalized_wheel_scroll_speed( - reader.get("wheel_scroll_speed", self.wheel_scroll_speed) - ) - self.reader_width_scale = self._normalized_reader_width_scale( - reader.get("reader_width_scale", self.reader_width_scale) - ) - self.document_font_size = max(12, min(28, round(self.font_scale * 16))) - try: - self.document_font_size = max(12, min(28, int(reader.get("document_font_size", self.document_font_size)))) - self.font_scale = self.document_font_size / 16 - except (TypeError, ValueError): - pass - - self.ui_font_family = str(reader.get("ui_font_family", self.ui_font_family)).strip() - try: - self.ui_font_point_size = max(0, min(32, int(reader.get("ui_font_point_size", self.ui_font_point_size)))) - except (TypeError, ValueError): - pass - self.document_font_family = str(reader.get("document_font_family", self.document_font_family)).strip() - 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 - - recent_files = payload.get("recent_files", []) - if isinstance(recent_files, list): - self.recent_files = [Path(str(path)).expanduser().resolve() for path in recent_files if str(path)] - - bookmarks = payload.get("bookmarks", []) - if isinstance(bookmarks, list): - self.bookmarks = [item for item in bookmarks if isinstance(item, dict)] - - scroll_positions = payload.get("scroll_positions", {}) - if isinstance(scroll_positions, dict): - self.scroll_positions = { - str(path): int(position) - for path, position in scroll_positions.items() - if self._is_int_like(position) - } - - external_applications = payload.get("external_applications", {}) - if isinstance(external_applications, dict): - self.external_applications = { - str(extension).lower(): str(program) - for extension, program in external_applications.items() - if str(extension).startswith(".") and str(program) - } - - project_root = payload.get("project_root", "") - if isinstance(project_root, str) and project_root and Path(project_root).exists(): - self.set_project_root(Path(project_root), save=True) + config = ApplicationConfiguration.from_payload(payload, self._configuration_data()) + self._apply_configuration_data(config) + self.settings.setValue("export/page_settings", json.dumps(asdict(config.page_settings), ensure_ascii=False)) + if config.project_root and Path(config.project_root).exists(): + self.set_project_root(Path(config.project_root), save=True) def _is_int_like(self, value: object) -> bool: try: @@ -4150,84 +3951,10 @@ class MainWindow(QMainWindow): self.bookmarks_menu.addAction(action) def _load_preferences(self) -> None: - self.theme = str(self.settings.value("reader/theme", "light")) - self.theme_color = str(self.settings.value("reader/theme_color", "colorful")) - if self.theme_color not in THEME_COLOR_VALUES: - self.theme_color = "colorful" - self.theme = self._reader_theme_for_color(self.theme_color) - self.theme_background = self._normalized_theme_background(str(self.settings.value("reader/theme_background", "none"))) - self.math_engine = str(self.settings.value("reader/math_engine", "katex")) - if self.math_engine not in {"katex", "mathjax"}: - self.math_engine = "katex" - 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.reader_width_scale = self._normalized_reader_width_scale( - self.settings.value("reader/width_scale", 1.0) - ) - self.document_font_size = max(12, min(28, round(self.font_scale * 16))) - try: - self.document_font_size = max(12, min(28, int(self.settings.value("reader/document_font_size", self.document_font_size)))) - except (TypeError, ValueError): - pass - self.font_scale = self.document_font_size / 16 - self.ui_font_family = str(self.settings.value("reader/ui_font_family", "")).strip() - try: - self.ui_font_point_size = max(0, min(32, int(self.settings.value("reader/ui_font_point_size", 0)))) - except (TypeError, ValueError): - self.ui_font_point_size = 0 - self.document_font_family = str(self.settings.value("reader/document_font_family", "")).strip() - self.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" - recent_value = self.settings.value("recent/files", []) - if isinstance(recent_value, str): - recent_paths = [recent_value] - else: - recent_paths = list(recent_value or []) - self.recent_files = [Path(str(path)).resolve() for path in recent_paths if str(path)] - bookmarks = self._load_json_setting(BOOKMARKS_SETTING_KEY, []) - scroll_positions = self._load_json_setting(SCROLL_POSITIONS_SETTING_KEY, {}) - external_applications = self._load_json_setting(EXTERNAL_APPLICATIONS_SETTING_KEY, {}) - editor_drafts = self._load_json_setting(EDITOR_DRAFTS_SETTING_KEY, {}) - self.bookmarks = bookmarks if isinstance(bookmarks, list) else [] - self.scroll_positions = scroll_positions if isinstance(scroll_positions, dict) else {} - if isinstance(external_applications, dict): - self.external_applications = { - str(extension).lower(): str(program) - for extension, program in external_applications.items() - if str(extension).startswith(".") and str(program) - } - if isinstance(editor_drafts, dict): - self.editor_drafts = { - str(path): draft - for path, draft in editor_drafts.items() - if isinstance(draft, dict) and isinstance(draft.get("source"), str) - } + self._apply_configuration_data(self.configurations.load()) + drafts = self.configurations.read_json(EDITOR_DRAFTS_SETTING_KEY, {}) + self.editor_drafts = {str(path): draft for path, draft in drafts.items() + if isinstance(draft, dict) and isinstance(draft.get("source"), str)} if isinstance(drafts, dict) else {} def _apply_auto_refresh_timing(self) -> None: if hasattr(self, "refresh_timer"): @@ -4253,38 +3980,8 @@ class MainWindow(QMainWindow): self.directory_poll_timer.stop() 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/width_scale", self.reader_width_scale) - self.settings.remove("reader/embedded_toc") - self.settings.remove("reader/external_toc") - self.settings.remove("reader/embedded_progress") - 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]) - self.settings.setValue(BOOKMARKS_SETTING_KEY, json.dumps(self.bookmarks, ensure_ascii=False)) - self.settings.setValue(SCROLL_POSITIONS_SETTING_KEY, json.dumps(self.scroll_positions, ensure_ascii=False)) - self.settings.setValue( - EXTERNAL_APPLICATIONS_SETTING_KEY, - json.dumps(self.external_applications, ensure_ascii=False), - ) - self.settings.setValue(EDITOR_DRAFTS_SETTING_KEY, json.dumps(self.editor_drafts, ensure_ascii=False)) + self.configurations.save(self._configuration_data()) + self.drafts.persist() if hasattr(self, "splitter"): self.settings.setValue("window/splitter", self.splitter.saveState()) self.settings.setValue("window/geometry", self.saveGeometry()) @@ -4302,29 +3999,10 @@ class MainWindow(QMainWindow): return restored def _load_json_setting(self, key: str, fallback: object) -> object: - value = self.settings.value(key, "") - if not value: - return fallback - try: - return json.loads(str(value)) - except json.JSONDecodeError: - return fallback + return self.configurations.read_json(key, 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 + return normalize_custom_styles(value, self.document_font_size) def _save_current_scroll_position(self) -> None: if self.current_file is None: diff --git a/mdhelper/preferences.py b/mdhelper/preferences.py new file mode 100644 index 0000000..8c225b2 --- /dev/null +++ b/mdhelper/preferences.py @@ -0,0 +1,222 @@ +"""One configuration schema for local settings and portable JSON files.""" +from __future__ import annotations + +import json +import math +import re +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + +from .document_tree import DEFAULT_DOCUMENT_FILE_GROUPS, normalized_document_file_groups +from .export_settings import PageSettings +from .style_presets import DOCUMENT_STYLE_PRESETS +from .style_sync import normalize_payload + +THEME_COLORS = {"white", "black", "dark_gray", "colorful"} +BACKGROUNDS = {"none", "chinese_knot", "cloud", "ruyi", "brush", "peony", "bamboo", "meander"} +WIDTH_SCALES = (1.0, 1.25, 1.5, 1.75, 2.0) +REFRESH_MODES = {"off", "current", "resources", "all"} +REFRESH_DELAYS = {800, 1000, 1500} + + +def number(value, default, minimum, maximum): + try: + value = float(value) + return max(minimum, min(maximum, value)) if math.isfinite(value) else default + except (ValueError, TypeError, OverflowError): + return default + + +def boolean(value, default=True): + if isinstance(value, str): + return {"true": True, "false": False, "1": True, "0": False}.get(value.lower(), default) + return bool(value) if isinstance(value, (bool, int)) else default + + +def normalize_custom_styles(value, font_size=16): + if not isinstance(value, dict): + return {} + result = {} + for key, style in value.items(): + if not isinstance(style, dict): + continue + normalized = normalize_payload(style, "自定义样式", font_size) + name = str(normalized.get("name", "")).strip() + if not name: + continue + key = str(key) + if not key.startswith("custom:"): + safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff._-]+", "-", name).strip("-._") or "style" + key, suffix = "custom:" + safe, 2 + while key in result: + key = f"custom:{safe}-{suffix}" + suffix += 1 + result[key] = normalized + return result + + +@dataclass(frozen=True) +class ReaderPreferences: + theme: str = "light" + theme_color: str = "colorful" + theme_background: str = "none" + font_scale: float = 1.0 + wheel_scroll_speed: float = 1.0 + reader_width_scale: float = 1.0 + ui_font_family: str = "" + ui_font_point_size: int = 0 + document_font_family: str = "" + document_font_size: int = 16 + document_style_id: str = "default" + custom_document_styles: dict = field(default_factory=dict) + document_tree_label_mode: str = "title" + math_engine: str = "katex" + auto_refresh: bool = True + auto_refresh_mode: str = "all" + auto_refresh_delay_ms: int = 1000 + non_preview_action: str = "ask" + document_file_groups: tuple[str, ...] = DEFAULT_DOCUMENT_FILE_GROUPS + + @classmethod + def from_mapping(cls, values: dict, base: ReaderPreferences | None = None): + base = base or cls() + data = asdict(base) + data.update({key: value for key, value in values.items() if key in data}) + if "theme_color" not in values and isinstance(values.get("theme"), str) and values["theme"] in {"light", "dark"}: + data["theme_color"] = "black" if values["theme"] == "dark" else "white" + def choice(name, allowed): + if not isinstance(data[name], str) or data[name] not in allowed: + data[name] = getattr(base, name) + choice("theme_color", THEME_COLORS) + data["theme"] = "dark" if data["theme_color"] in {"black", "dark_gray"} else "light" + if data["theme_color"] != "colorful" or not isinstance(data["theme_background"], str) or data["theme_background"] not in BACKGROUNDS: + data["theme_background"] = "none" + size = base.document_font_size + if "font_scale" in values and "document_font_size" not in values: + size = round(number(values["font_scale"], base.font_scale, .75, 1.75) * 16) + data["document_font_size"] = int(number(values.get("document_font_size", size), size, 12, 28)) + data["font_scale"] = data["document_font_size"] / 16 + data["wheel_scroll_speed"] = number(data["wheel_scroll_speed"], base.wheel_scroll_speed, .5, 3) + width = number(data["reader_width_scale"], base.reader_width_scale, 1, 2) + data["reader_width_scale"] = min(WIDTH_SCALES, key=lambda value: abs(value - width)) + data["ui_font_point_size"] = int(number(data["ui_font_point_size"], base.ui_font_point_size, 0, 32)) + for name in ("ui_font_family", "document_font_family"): + data[name] = str(data[name]).strip() + data["custom_document_styles"] = normalize_custom_styles(data["custom_document_styles"], data["document_font_size"]) + choice("document_style_id", set(DOCUMENT_STYLE_PRESETS) | set(data["custom_document_styles"])) + if data["document_style_id"] not in DOCUMENT_STYLE_PRESETS and data["document_style_id"] not in data["custom_document_styles"]: + data["document_style_id"] = "default" + choice("document_tree_label_mode", {"title", "filename"}) + choice("math_engine", {"katex", "mathjax"}) + choice("auto_refresh_mode", REFRESH_MODES) + enabled = boolean(data["auto_refresh"], base.auto_refresh) + if not enabled or data["auto_refresh_mode"] == "off": + data["auto_refresh_mode"] = "off" + data["auto_refresh"] = data["auto_refresh_mode"] != "off" + delay = int(number(data["auto_refresh_delay_ms"], base.auto_refresh_delay_ms, 0, 10000)) + data["auto_refresh_delay_ms"] = delay if delay in REFRESH_DELAYS else base.auto_refresh_delay_ms + choice("non_preview_action", {"ask", "open", "block"}) + data["document_file_groups"] = normalized_document_file_groups(data["document_file_groups"]) + return cls(**data) + + +@dataclass +class ApplicationConfiguration: + reader: ReaderPreferences = field(default_factory=ReaderPreferences) + project_root: str = "" + recent_files: list[str] = field(default_factory=list) + bookmarks: list[dict] = field(default_factory=list) + scroll_positions: dict[str, int] = field(default_factory=dict) + external_applications: dict[str, str] = field(default_factory=dict) + page_settings: PageSettings = field(default_factory=PageSettings) + + def to_payload(self, version: str) -> dict: + result = asdict(self) + result["reader"]["document_file_groups"] = list(self.reader.document_file_groups) + result.update(app="MDHelper", version=version) + return result + + @classmethod + def from_payload(cls, payload: dict, base: ApplicationConfiguration | None = None): + base = base or cls() + result = cls(**{name: getattr(base, name) for name in cls.__dataclass_fields__}) + if isinstance(payload.get("reader"), dict): + result.reader = ReaderPreferences.from_mapping(payload["reader"], base.reader) + if isinstance(payload.get("project_root"), str): + result.project_root = payload["project_root"] + recent = payload.get("recent_files", base.recent_files) + if isinstance(recent, str): + recent = [recent] + if isinstance(recent, list): + result.recent_files = [str(Path(str(path)).expanduser().resolve()) for path in recent if path] + bookmarks = payload.get("bookmarks", base.bookmarks) + if isinstance(bookmarks, list): + result.bookmarks = [item for item in bookmarks if isinstance(item, dict)] + positions = payload.get("scroll_positions", base.scroll_positions) + if isinstance(positions, dict): + result.scroll_positions = {} + for path, position in positions.items(): + try: + result.scroll_positions[str(path)] = int(position) + except (TypeError, ValueError, OverflowError): + pass + applications = payload.get("external_applications", base.external_applications) + if isinstance(applications, dict): + result.external_applications = {str(ext).lower(): str(program) for ext, program in applications.items() + if str(ext).startswith(".") and str(program)} + if isinstance(payload.get("page_settings"), dict): + result.page_settings = PageSettings.from_dict(payload["page_settings"]).normalized() + return result + + +READER_KEYS = {item.name: "reader/" + item.name for item in fields(ReaderPreferences)} +READER_KEYS.update(reader_width_scale="reader/width_scale", document_tree_label_mode="tree/markdown_label_mode") +JSON_READER_FIELDS = {"custom_document_styles", "document_file_groups"} +COLLECTION_KEYS = {"bookmarks": "bookmarks/items", "scroll_positions": "reader/scroll_positions", + "external_applications": "external_apps/by_extension"} + + +class ConfigurationStore: + def __init__(self, settings): + self.settings = settings + + def read_json(self, key, default): + try: + value = self.settings.value(key, None) + return json.loads(str(value)) if value is not None else default + except (TypeError, ValueError): + return default + + def load(self) -> ApplicationConfiguration: + reader = {} + for name, key in READER_KEYS.items(): + if self.settings.contains(key): + reader[name] = self.read_json(key, None) if name in JSON_READER_FIELDS else self.settings.value(key) + payload = {"reader": reader, "recent_files": self.settings.value("recent/files", []), + "project_root": self.settings.value("project/last_root", ""), + "page_settings": asdict(self.load_page_settings())} + payload.update({name: self.read_json(key, [] if name == "bookmarks" else {}) for name, key in COLLECTION_KEYS.items()}) + return ApplicationConfiguration.from_payload(payload) + + def load_page_settings(self) -> PageSettings: + value = self.read_json("export/page_settings", {}) + if isinstance(value, dict) and value: + return PageSettings.from_dict(value).normalized() + margins = {name: number(self.settings.value(f"pdf/{name}_margin_mm", 15), 15, 0, 50) + for name in ("top", "bottom", "left", "right")} + return PageSettings(**margins) + + def save_page_settings(self, value: PageSettings) -> None: + self.settings.setValue("export/page_settings", json.dumps(asdict(value), ensure_ascii=False)) + + def save(self, config: ApplicationConfiguration): + for name, value in asdict(config.reader).items(): + self.settings.setValue(READER_KEYS[name], json.dumps(value, ensure_ascii=False) if name in JSON_READER_FIELDS else value) + for key in ("reader/embedded_toc", "reader/external_toc", "reader/embedded_progress"): + self.settings.remove(key) + for name, key in COLLECTION_KEYS.items(): + self.settings.setValue(key, json.dumps(getattr(config, name), ensure_ascii=False)) + self.settings.setValue("recent/files", config.recent_files) + if config.project_root: + self.settings.setValue("project/last_root", config.project_root) + self.save_page_settings(config.page_settings) diff --git a/mdhelper/style_presets.py b/mdhelper/style_presets.py new file mode 100644 index 0000000..253ca90 --- /dev/null +++ b/mdhelper/style_presets.py @@ -0,0 +1,96 @@ +"""Built-in document style data shared by settings and the interface.""" +DOCUMENT_STYLE_PRESETS = { + "default": { + "name": "默认阅读", + "css": "", + }, + "compact": { + "name": "紧凑参考", + "css": """ +.reader { + max-width: var(--reader-paper-width); + 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: var(--reader-paper-width); + 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: var(--reader-paper-width); + 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: var(--reader-paper-width); + 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(), + }, +} diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py index 4f62f7c..e0fb3f2 100644 --- a/tests/gui_smoke.py +++ b/tests/gui_smoke.py @@ -33,6 +33,25 @@ from mdhelper.settings_dialog import AppPreferences, SettingsDialog from mdhelper.style_dialog import DocumentStyleEditorDialog +def wait_until(condition, timeout_ms=15000) -> bool: + """Wait for completion, not a fixed rendering speed on the test machine.""" + if condition(): + return True + loop = QEventLoop() + poll = QTimer() + poll.setInterval(20) + poll.timeout.connect(lambda: loop.quit() if condition() else None) + deadline = QTimer() + deadline.setSingleShot(True) + deadline.timeout.connect(loop.quit) + poll.start() + deadline.start(timeout_ms) + loop.exec() + poll.stop() + deadline.stop() + return bool(condition()) + + def main() -> int: isolated_settings = tempfile.TemporaryDirectory(prefix="mdhelper-gui-smoke-") QSettings.setDefaultFormat(QSettings.Format.IniFormat) @@ -839,9 +858,7 @@ def main() -> int: 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() + wait_until(lambda: not window._mhtml_exports) if not mhtml_test_path.exists() or mhtml_test_path.stat().st_size <= 0: checks.append("export_mhtml_write") finally: @@ -920,15 +937,14 @@ def main() -> int: checks.append("video_theme_sample_tab") else: theme_result: dict[str, str] = {} - theme_loop = QEventLoop() - def store_sample_theme(value: object) -> None: theme_result["theme"] = str(value) - theme_loop.quit() - - QTimer.singleShot(600, lambda: sample_view.page().runJavaScript("document.documentElement.dataset.theme", store_sample_theme)) - QTimer.singleShot(1800, theme_loop.quit) - theme_loop.exec() + theme_poll = QTimer() + theme_poll.setInterval(100) + theme_poll.timeout.connect(lambda: sample_view.page().runJavaScript("document.documentElement.dataset.theme", store_sample_theme)) + theme_poll.start() + wait_until(lambda: theme_result.get("theme") == "dark") + theme_poll.stop() if theme_result.get("theme") != "dark": checks.append("video_theme_refresh_all_tabs") finally: diff --git a/tests/test_preferences.py b/tests/test_preferences.py new file mode 100644 index 0000000..abd63ec --- /dev/null +++ b/tests/test_preferences.py @@ -0,0 +1,55 @@ +from dataclasses import asdict + +from PySide6.QtCore import QSettings + +from mdhelper.preferences import ApplicationConfiguration, ConfigurationStore, ReaderPreferences +from mdhelper.export_settings import PageSettings + + +def test_local_settings_and_json_use_the_same_schema(tmp_path): + settings = QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat) + store = ConfigurationStore(settings) + config = ApplicationConfiguration.from_payload({ + "reader": {"theme_color": "colorful", "theme_background": "cloud", "document_font_size": 22, + "custom_document_styles": {"custom:demo": {"name": "Demo", "css": "/* kept */ p {color: red}"}}, + "document_style_id": "custom:demo", "document_file_groups": ["markdown", "python"]}, + "recent_files": [str(tmp_path / "note.md")], "bookmarks": [{"title": "Example"}], + "scroll_positions": {"note.md": 123}, "external_applications": {".TXT": "viewer.exe"}, + "page_settings": asdict(PageSettings(paper="Letter", header="header", toc_depth=4)), + }) + store.save(config) + local = store.load() + portable = ApplicationConfiguration.from_payload(config.to_payload("0.3.1")) + assert local == portable == config + assert "/* kept */" in local.reader.custom_document_styles["custom:demo"]["css"] + assert "editor/drafts" not in config.to_payload("0.3.1") + + +def test_legacy_settings_migrate_without_losing_pdf_margins(tmp_path): + settings = QSettings(str(tmp_path / "legacy.ini"), QSettings.Format.IniFormat) + settings.setValue("reader/theme", "dark") + settings.setValue("reader/font_scale", "1.25") + settings.setValue("reader/auto_refresh", "false") + settings.setValue("pdf/top_margin_mm", 8) + store = ConfigurationStore(settings) + config = store.load() + assert config.reader.theme_color == "black" and config.reader.document_font_size == 20 + assert config.reader.auto_refresh_mode == "off" + assert config.page_settings.top == 8 + store.save(config) + assert store.load() == config + + +def test_invalid_configuration_values_have_safe_defaults(): + preferences = ReaderPreferences.from_mapping({"theme_color": {}, "theme_background": [], "document_font_size": "NaN", + "ui_font_point_size": "inf", "wheel_scroll_speed": "invalid", "reader_width_scale": None, + "math_engine": [], "custom_document_styles": [], "auto_refresh_delay_ms": "not a number"}) + assert preferences == ReaderPreferences() + + +def test_importing_a_partial_configuration_preserves_other_settings(): + base = ApplicationConfiguration(reader=ReaderPreferences(document_font_size=20, font_scale=1.25), + bookmarks=[{"title": "keep"}], page_settings=PageSettings(header="keep")) + changed = ApplicationConfiguration.from_payload({"reader": {"theme_color": "black"}}, base) + assert changed.reader.document_font_size == 20 and changed.reader.theme == "dark" + assert changed.bookmarks == base.bookmarks and changed.page_settings == base.page_settings