From 9d4bc8c91ab43bf82f8e784425734ece0114d36a Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 29 Oct 2026 15:48:23 +0800 Subject: [PATCH] feat: synchronize typography controls with editable CSS --- README.md | 7 +- docs/user_manual.md | 16 +- mdhelper/__init__.py | 2 +- mdhelper/main_window.py | 20 +- mdhelper/style_dialog.py | 102 +++++++- mdhelper/style_sync.py | 477 +++++++++++++++++++++++++++++++++++ requirements.txt | 1 + tests/test_document_style.py | 2 +- tests/test_style_sync.py | 232 +++++++++++++++++ 9 files changed, 826 insertions(+), 33 deletions(-) create mode 100644 mdhelper/style_sync.py create mode 100644 tests/test_style_sync.py diff --git a/README.md b/README.md index bdffea8..cf03366 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MDHelper -当前版本:`0.2.1` +当前版本:`0.2.2` MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构建桌面窗口,用 Qt WebEngine 展示由 Markdown 转换得到的 HTML 页面。它面向本地项目文档、技术手册、源码说明和离线帮助文件,重点是离线可用、多标签阅读、全文搜索、样式管理和导出。 @@ -19,7 +19,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 自动刷新当前文档、已打开文档和引用资源;外部修改后会重新读取并渲染。 - 可配置主题颜色、主题背景、正文字号倍率、鼠标滚轮速度、纸张宽度、自动刷新策略和非预览文件打开策略。 - 提供“样式”菜单,支持内置文档样式和自定义样式文件,样式可配置字体、缩进、行距、段前段后间距等。 -- 图形样式支持磅值/中文字号、字体颜色、字符间距、对齐、左右和特殊缩进、同样式段落间距及分页控制;三个 DOCX 导出引擎均保留这些设置。高级 CSS 仅用于阅读器及 HTML/PDF。 +- 图形样式支持磅值/中文字号、字体颜色、字符间距、对齐、左右和特殊缩进、同样式段落间距及分页控制。图形设置与高级 CSS 双向同步,三个 DOCX 导出引擎均保留可识别的核心设置;背景、边框及条件规则等扩展效果用于阅读器及 HTML/PDF。 - 导出支持 PDF、HTML、DOCX、MHTML;DOCX 可选择 `pandoc` 或 `python-docx` 相关实现。 - 图片点击放大,支持缩放、旋转、适应窗口、原始大小、保存图片和在文件夹中显示。 - 表格支持横向滚动和一键复制。 @@ -116,7 +116,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 首次缺少 Inno Setup 时会从官方来源下载、校验发布者签名并安装到 `pack\.tools`;后续构建复用。 需要可用的 64 位 Python 3.10+;兼容当前项目的两种 `mdhelper_env` 目录布局。 -安装程序位于 `pack\output\MDHelper-Setup-0.2.1-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 +安装程序位于 `pack\output\MDHelper-Setup-0.2.2-x64.exe`(版本号自动读取),同目录包含 SHA256 校验文件。 默认按当前用户安装,提供开始菜单入口、可选桌面快捷方式,以及 Windows 卸载入口。 程序运行时无需单独安装 Python 或 Pandoc。 @@ -146,6 +146,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 ```text PySide6==6.11.1 markdown-it-py==4.2.0 +tinycss2==1.5.1 Pygments==2.20.0 Pillow==12.2.0 python-docx==1.2.0 diff --git a/docs/user_manual.md b/docs/user_manual.md index 3da23ce..9f405ac 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -2,7 +2,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,适合阅读项目说明、技术手册、源码旁文档和离线帮助文件。它使用 PySide6 提供桌面窗口,用 Qt WebEngine 渲染 Markdown 转换后的 HTML 页面,并在本地完成全文搜索、样式管理、导出和自动刷新。 -当前版本:`0.2.1` +当前版本:`0.2.2` ## 1. 适用场景 @@ -146,6 +146,18 @@ Markdown 支持: 纸张宽度是全局阅读设置,内置样式不再写死正文宽度,会跟随纸张宽度变化。 +### 图形设置与高级 CSS 双向同步 + +“高级 CSS”显示完整的自定义样式。修改图形设置时,只更新对应对象的核心属性;原有背景、边框、阴影、注释和其他对象的规则会保留。直接修改 CSS 后,停止输入约 0.35 秒即可回填到图形设置和预览;立即点击确定也会先同步再保存。CSS 未写完整或存在语法错误时,保留上一次有效设置并提示修正,避免把半成品保存为样式。 + +核心同步覆盖对象的常规选择器,例如 `p`、`.reader p`、`h1`、`.reader h1`,以及程序生成的正文、列表、引用、代码和表格选择器。可识别的属性包括 `font-family`、`font-size`、`font-weight`、`font-style`、`color`、`letter-spacing`、`text-align`、`line-height`、`text-indent`、`margin`/四个方向的间距,以及换行、分页属性。支持常见字体简写、间距简写和 `!important`;重置当前对象只清除其核心设置,保留扩展效果。 + +例如,将正文规则中的 `font-size: 12pt` 改成 `font-size: 14pt`,图形字号会变为 14 磅,导出 Word 也使用 14 磅。之后在图形界面调整字号,CSS 对应值会随之更新。删除某项属性后,如果没有其他常规规则提供该属性,图形设置显示“继承”。 + +中英文字体及 Word 特有设置使用可编辑的 CSS 自定义属性:`--mdhelper-font-chinese` / `--mdhelper-font-english` 区分字体;`--mdhelper-line-spacing-mode: at-least` 配合磅值 `line-height` 表示最小值行距;`--mdhelper-contextual-spacing: true` 表示同样式段落间不添加间距。这些属性由图形设置自动生成。 + +`@media`、嵌套规则、局部选择器(例如 `p:hover`、特定类名),以及图形界面无法表示的 `calc()`、动态变量、透明颜色等值会保留在 CSS 中,并在编辑器底部说明同步范围。它们不会被猜测为统一的图形设置或 Word 格式。需要统一控制文档核心排版时,建议修改程序生成的对象规则;扩展规则仍可用于阅读器及 HTML/PDF 的显示效果。 + ## 10. 媒体与表格 图片: @@ -196,7 +208,7 @@ DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。正式安装版 Pandoc、python-docx 和内置基础导出均保留图形设置中的字体、字号、颜色、字符间距、对齐、缩进、段间距、行距和分页选项。正文、各级标题、列表、引用、代码和表格分别应用对应设置;Markdown 中显式加粗、斜体的局部文本仍保留强调。Word 字号按其支持的半磅精度写入;自动颜色使用 Word 自动文字颜色。 -高级 CSS 仅影响阅读器及 HTML/PDF,不能转换为 Word 样式。阅读器是连续页面,固定值/最小值行距及分页效果可能与 Word 显示不同;导出文件分别保留 Word 的固定值、最小值和分页属性。三个引擎的表格、复杂 Markdown、图片或公式支持范围仍按各自能力处理。 +高级 CSS 中可识别的核心属性会同步到图形设置,并用于 Word 导出;背景、边框、条件规则等扩展 CSS 不转换为 Word 格式。阅读器是连续页面,固定值/最小值行距及分页效果可能与 Word 显示不同;导出文件分别保留 Word 的固定值、最小值和分页属性。三个引擎的表格、复杂 Markdown、图片或公式支持范围仍按各自能力处理。 ## 13. 配置与迁移 diff --git a/mdhelper/__init__.py b/mdhelper/__init__.py index 5fdc3fb..15173d5 100644 --- a/mdhelper/__init__.py +++ b/mdhelper/__init__.py @@ -1,3 +1,3 @@ """MDHelper package.""" -__version__ = "0.2.1" +__version__ = "0.2.2" diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 3717aa6..8d0fdf4 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -95,6 +95,7 @@ from .pdf_export import ( from .search import SearchIndex from .settings_dialog import AppPreferences, SettingsDialog from .style_dialog import DocumentStyleEditorDialog, build_document_style_css +from .style_sync import normalize_payload, render_css from .text_io import DEFAULT_TEXT_PREVIEW_BYTES, read_text_with_fallback from .startup_scan import StartupScan @@ -1553,6 +1554,8 @@ class MainWindow(QMainWindow): 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: + if style.get("css_sync_version") == 1: + return render_css(str(style.get("css") or ""), style.get("rules") or {}) return build_document_style_css( style.get("rules") if isinstance(style.get("rules"), dict) else {}, str(style.get("extra_css") or ""), @@ -4287,6 +4290,9 @@ class MainWindow(QMainWindow): } if isinstance(style.get("rules"), dict): payload["rules"] = style["rules"] + if style.get("css_sync_version") == 1: + payload["css_sync_version"] = 1 + payload["css"] = str(style.get("css") or "") if "extra_css" in style: payload["extra_css"] = str(style.get("extra_css") or "") return payload @@ -4327,19 +4333,7 @@ class MainWindow(QMainWindow): 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 + return normalize_payload(payload, fallback_name, self.document_font_size) def choose_interface_font(self) -> None: current = QApplication.instance().font() if QApplication.instance() is not None else QFont() diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 3304f67..c4fbc38 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -6,7 +6,7 @@ import re from copy import deepcopy from typing import Any -from PySide6.QtCore import Qt +from PySide6.QtCore import Qt, QTimer, QSignalBlocker from PySide6.QtGui import QFont, QColor, QTextBlockFormat, QTextCharFormat, QTextCursor from PySide6.QtWidgets import ( QCheckBox, @@ -35,6 +35,7 @@ from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules, from .document_style import build_document_style_css +from .style_sync import analyze_css, source_from_payload, patch_core class DocumentStyleEditorDialog(QDialog): @@ -53,6 +54,13 @@ class DocumentStyleEditorDialog(QDialog): self._current_target = STYLE_TARGETS[0][0] self._loading = False + self._css_dirty = False + self._syncing_css = False + self._css_timer = QTimer(self) + self._css_timer.setSingleShot(True) + self._css_timer.setInterval(350) + self._css_timer.timeout.connect(self._sync_from_css) + self.name_edit = QLineEdit(str(source.get("name") or default_name)) self.name_edit.setObjectName("styleNameEdit") self.name_edit.setPlaceholderText("样式名称") @@ -68,10 +76,11 @@ class DocumentStyleEditorDialog(QDialog): self.tabs = QTabWidget() self.tabs.setMinimumWidth(750) self.tabs.addTab(self._build_visual_tab(), "图形设置") - extra_css = source.get("extra_css", "" if source.get("rules") else source.get("css", "")) - self.tabs.addTab(self._build_advanced_tab(str(extra_css or "")), "高级 CSS") + self.tabs.addTab(self._build_advanced_tab(source_from_payload(source)), "高级 CSS") + self.tabs.currentChanged.connect(self._tab_changed) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + self.button_box = buttons buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) button_row = QWidget() @@ -88,6 +97,7 @@ class DocumentStyleEditorDialog(QDialog): layout.addWidget(self.tabs) layout.addWidget(button_row) self._load_rule_to_widgets(self.rules.get(self._current_target, {})) + self._sync_from_css() def apply_theme(self, theme_color: str) -> None: palettes = { @@ -348,15 +358,19 @@ class DocumentStyleEditorDialog(QDialog): return def style_payload(self) -> dict[str, object]: - self._store_current_rule() - extra_css = self.extra_css_edit.toPlainText().strip() + if not self._sync_from_css(): + raise ValueError("CSS 尚未完成,请先修正提示的错误。") 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), + "css_sync_version": 1, + "css": self.extra_css_edit.toPlainText(), } + def accept(self) -> None: + if self._sync_from_css(): + super().accept() + @staticmethod def _combo(items: list[tuple[str, object]]) -> QComboBox: box = QComboBox() @@ -471,7 +485,7 @@ class DocumentStyleEditorDialog(QDialog): scroll.setWidget(panel) right = QVBoxLayout() right.addWidget(scroll, 1) - right.addWidget(QLabel("实时预览(分页效果请以导出的 Word 为准)")) + right.addWidget(QLabel("字体与段落预览(扩展 CSS 应用后查看;分页以 Word 为准)")) self.preview = QTextEdit() self.preview.setReadOnly(True) self.preview.setMinimumHeight(125) @@ -495,15 +509,70 @@ class DocumentStyleEditorDialog(QDialog): def _build_advanced_tab(self, css: str) -> QWidget: page = QWidget() layout = QVBoxLayout(page) - label = QLabel("高级 CSS 仅用于阅读器及 HTML/PDF。导出 Word 保留“图形设置”中的字体和段落选项。") + label = QLabel("这里是完整自定义样式。修改常规对象规则中的核心属性会同步到图形设置及 Word;背景、边框、条件规则等扩展效果保留为 CSS。") label.setWordWrap(True) layout.addWidget(label) self.extra_css_edit = QTextEdit() self.extra_css_edit.setAcceptRichText(False) + self.extra_css_edit.setPlaceholderText("可以先调整图形设置,再编辑这里生成的 CSS。\n例如:.reader p { font-size: 14pt; color: #24558a; }") self.extra_css_edit.setPlainText(css) + self.extra_css_edit.setFont(QFont("Consolas", 10)) + self.extra_css_edit.textChanged.connect(self._css_changed) layout.addWidget(self.extra_css_edit) + self.css_status_label = QLabel() + self.css_status_label.setWordWrap(True) + self.css_status_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + layout.addWidget(self.css_status_label) return page + def _css_changed(self) -> None: + if not self._syncing_css: + self._css_dirty = True + self.css_status_label.setText("正在编辑,停止输入后同步核心设置…") + self._css_timer.start() + + def _sync_from_css(self, update_widgets: bool = True) -> bool: + self._css_timer.stop() + result = analyze_css(self.extra_css_edit.toPlainText(), getattr(self.parent(), "document_font_size", 16)) + valid = not result.errors + self.tabs.setTabEnabled(0, valid) + self.button_box.button(QDialogButtonBox.StandardButton.Ok).setEnabled(valid) + if not valid: + self.css_status_label.setText("尚未同步:" + ";".join(result.errors[:3])) + return False + self._css_dirty = False + self.rules = result.rules + if update_widgets: + self._load_rule_to_widgets(self.rules.get(self._current_target, {})) + else: + self._refresh_preview() + summary = "可识别的核心设置已同步,并用于 Word 导出。" + if result.notes: + summary += "\n" + ";".join(result.notes[:4]) + (";更多说明见悬停提示。" if len(result.notes) > 4 else "") + self.css_status_label.setText(summary) + self.css_status_label.setToolTip("\n".join(result.notes)) + return True + + def _tab_changed(self, *_: object) -> None: + if self._css_dirty: + self._sync_from_css() + + def _write_css(self, source: str) -> None: + if source == self.extra_css_edit.toPlainText(): + return + self._syncing_css = True + blocker = QSignalBlocker(self.extra_css_edit) + cursor = self.extra_css_edit.textCursor() + position = cursor.position() + cursor.beginEditBlock() + cursor.select(QTextCursor.SelectionType.Document) + cursor.insertText(source) + cursor.endEditBlock() + cursor.setPosition(min(position, len(source))) + self.extra_css_edit.setTextCursor(cursor) + del blocker + self._syncing_css = False + def _choose_color(self) -> None: color = QColorDialog.getColor(QColor(self.color_button.text()), self, "字体颜色") if color.isValid(): @@ -599,18 +668,25 @@ class DocumentStyleEditorDialog(QDialog): self.rules.pop(self._current_target, None) def _change_target(self, current: QListWidgetItem, previous: QListWidgetItem | None) -> None: - self._store_current_rule() + if self._css_dirty: + self._sync_from_css() self._current_target = current.data(Qt.ItemDataRole.UserRole) self._load_rule_to_widgets(self.rules.get(self._current_target, {})) def _reset_current_rule(self) -> None: - self.rules.pop(self._current_target, None) - self._load_rule_to_widgets({}) + before = self.rules.get(self._current_target, {}) + self._write_css(patch_core(self.extra_css_edit.toPlainText(), self._current_target, before, {}, reset=True)) + self._sync_from_css() def _store_and_refresh(self, *_: object) -> None: if not self._loading: + if self._css_dirty and not self._sync_from_css(): + return + before = deepcopy(self.rules.get(self._current_target, {})) self._store_current_rule() - self._refresh_preview() + after = self.rules.get(self._current_target, {}) + self._write_css(patch_core(self.extra_css_edit.toPlainText(), self._current_target, before, after)) + self._sync_from_css(update_widgets=False) def _refresh_preview(self) -> None: self.indent_spin.setEnabled(self.indent_mode_combo.currentData() in ("first", "hanging")) diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py new file mode 100644 index 0000000..6b068f4 --- /dev/null +++ b/mdhelper/style_sync.py @@ -0,0 +1,477 @@ +"""Loss-aware editing of core typography inside an otherwise arbitrary stylesheet. + +The authored CSS is authoritative. Only unconditional, known object selectors +and representable values map to controls/Word. Other rules remain CSS verbatim. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from copy import deepcopy +import re + +import tinycss2 as css +from tinycss2.color3 import parse_color + +from .document_style import (STYLE_TARGETS, normalize_rule, css_declarations, + build_document_style_css, fmt, font_points, resolved_rules) + +SELECTORS = {key: selector for key, _, selector in STYLE_TARGETS} +LABELS = {key: label for key, label, _ in STYLE_TARGETS} +GROUPS = { + "fonts": ("chinese_font_family", "english_font_family"), + "size": ("font_size", "font_size_unit"), "bold": ("bold",), "italic": ("italic",), + "color": ("font_color",), "tracking": ("letter_spacing",), "align": ("alignment",), + "line": ("line_spacing_mode", "line_height_value"), "indent": ("indent_mode", "indent_value"), + **{side: (f"{side}_indent_value", f"{side}_indent_unit") for side in ("left", "right")}, + **{side: (f"space_{side}_value", f"space_{side}_unit") for side in ("before", "after")}, + **{name: (name,) for name in ("contextual_spacing", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control")}, +} +PROPERTIES = { + "fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"}, + "size": {"font-size"}, "bold": {"font-weight"}, "italic": {"font-style"}, "color": {"color"}, + "tracking": {"letter-spacing"}, "align": {"text-align"}, + "line": {"line-height", "--mdhelper-line-spacing-mode"}, "indent": {"text-indent"}, + **{side: {f"margin-{side}"} for side in ("left", "right")}, + "before": {"margin-top"}, "after": {"margin-bottom"}, + "contextual_spacing": {"--mdhelper-contextual-spacing"}, + "keep_with_next": {"break-after", "page-break-after"}, + "keep_lines_together": {"break-inside", "page-break-inside"}, + "page_break_before": {"break-before", "page-break-before"}, "widow_control": {"widows", "orphans"}, +} +CORE_PROPERTIES = set().union(*PROPERTIES.values()) + + +def _normalize_selector_text(value): + value = re.sub(r"\s+", " ", value.strip()) + value = re.sub(r"\s*,\s*", ",", value) + return re.sub(r"\s+\)", ")", re.sub(r"\(\s+", "(", value)) + + +ALIASES = {"p": "paragraph", **{f"h{i}": f"h{i}" for i in range(1, 7)}, "li": "list", + "blockquote": "blockquote", "blockquote p": "blockquote", ".admonition p": "blockquote", + "pre": "code", "code": "code", "table": "table", "th": "table", "td": "table"} +ALIASES.update({".reader " + key: target for key, target in list(ALIASES.items())}) +ALIASES[_normalize_selector_text(SELECTORS["paragraph"])] = "paragraph" +FONT_VARIABLES = {"chinese_font_family": "--mdhelper-font-chinese", "english_font_family": "--mdhelper-font-english"} +FONT_EXPRESSION = "var(--mdhelper-font-english, var(--mdhelper-font-chinese, var(--reader-font-family))), var(--mdhelper-font-chinese, sans-serif)" + + +@dataclass +class Analysis: + rules: dict = field(default_factory=dict) + errors: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + + +def _text(tokens) -> str: + return css.serialize(tokens).strip() + + +def _split(tokens, delimiter=","): + parts, current = [], [] + for token in tokens: + if token.type == "literal" and token.value == delimiter: + parts.append(current) + current = [] + else: + current.append(token) + return parts + [current] + + +def _selector(tokens): + return _normalize_selector_text(_text([t for t in tokens if t.type != "comment"])) + + +def _property(declaration): + # Custom property names are case-sensitive in CSS. + return declaration.name if declaration.name.startswith("--") else declaration.lower_name + + +def _specificity(selector): + # Only aliases in the allow-list reach this function. :where has zero weight. + selector = re.sub(r":not\(:where\(.*\)\)", "", selector) + return selector.count("."), len(re.findall(r"(?:^|\s)(?:p|h[1-6]|li|blockquote|pre|code|table|th|td)\b", selector)) + + +def _balanced(source): + stack, index = [], 0 + while index < len(source): + char = source[index] + if source.startswith("/*", index): + end = source.find("*/", index + 2) + if end < 0: + return "CSS 注释尚未结束(缺少 */)。" + index = end + 2 + continue + if char in "\"'": + quote = char + index += 1 + while index < len(source): + if source[index] == "\\": + index += 2 + elif source[index] == quote: + break + else: + index += 1 + if index >= len(source): + return "CSS 字符串尚未结束(缺少引号)。" + elif char == "\\": + index += 1 + elif char in "{([": + stack.append(char) + elif char in "})]": + if not stack or stack.pop() != {"}": "{", ")": "(", "]": "["}[char]: + return f"CSS 括号不匹配:{char}。" + index += 1 + return "CSS 规则尚未结束(缺少右括号)。" if stack else "" + + +def _declaration(name, value, important=False): + return css.parse_declaration_list(f"{name}: {value}{' !important' if important else ''};", skip_whitespace=True)[0] + + +def _expand(declaration): + """Expand margins while keeping individual tokens (including calc/var).""" + if declaration.type == "declaration" and declaration.lower_name == "font": + tokens = [t for t in declaration.value if t.type not in ("whitespace", "comment")] + size_index = next((i for i, t in enumerate(tokens) if t.type == "dimension" and t.lower_unit in ("pt", "px")), None) + if size_index is None: + return [declaration] + prefix = [_text([t]).lower() for t in tokens[:size_index]] + if any(value not in ("normal", "italic", "bold", "400", "700") for value in prefix): + return [declaration] + end = size_index + 1 + line = "normal" + if end < len(tokens) and tokens[end].type == "literal" and tokens[end].value == "/": + if end + 1 >= len(tokens): + return [declaration] + line, end = _text([tokens[end + 1]]), end + 2 + # Preserve whitespace inside unquoted family names. + family_token = tokens[end] if end < len(tokens) else None + if family_token is None: + return [declaration] + family = _text(declaration.value[declaration.value.index(family_token):]) + try: + _font_names(family) + except ValueError: + return [declaration] + values = {"font-size": _text([tokens[size_index]]), "line-height": line, "font-family": family, + "font-weight": "bold" if any(v in prefix for v in ("bold", "700")) else "normal", + "font-style": "italic" if "italic" in prefix else "normal"} + return [_declaration(prop, value, declaration.important) for prop, value in values.items()] + if declaration.type != "declaration" or declaration.lower_name != "margin": + return [declaration] + values = [t for t in declaration.value if t.type not in ("whitespace", "comment")] + if not 1 <= len(values) <= 4: + return [declaration] + top = values[0] + right = values[1] if len(values) > 1 else top + bottom = values[2] if len(values) > 2 else top + left = values[3] if len(values) > 3 else right + return [_declaration("margin-" + side, _text([value]), declaration.important) + for side, value in zip(("top", "right", "bottom", "left"), (top, right, bottom, left))] + + +def _length(value, units=("pt", "px", "cm", "em", "lh"), negative=False): + tokens = css.parse_component_value_list(value, skip_comments=True) + tokens = [t for t in tokens if t.type != "whitespace"] + if len(tokens) != 1: + raise ValueError + token = tokens[0] + if token.type == "number" and token.value == 0: + amount, unit = 0, "pt" + elif token.type == "dimension" and token.lower_unit in units: + amount, unit = token.value, token.lower_unit + else: + raise ValueError + if not negative and amount < 0: + raise ValueError + return amount, unit + + +def _font_names(value): + names = [] + for part in _split(css.parse_component_value_list(value)): + tokens = [t for t in part if t.type not in ("whitespace", "comment")] + if len(tokens) == 1 and tokens[0].type == "string": + names.append(tokens[0].value) + elif tokens and all(t.type == "ident" for t in tokens): + names.append(" ".join(t.value for t in tokens)) + else: + raise ValueError + return names + + +def analyze_css(source: str, font_size_px: float = 16) -> Analysis: + result = Analysis() + balance = _balanced(source) + if balance: + result.errors.append(balance) + return result + winners = {target: {} for target in SELECTORS} + for order, node in enumerate(css.parse_stylesheet(source, skip_comments=False, skip_whitespace=False)): + if node.type == "error": + result.errors.append(f"第 {node.source_line} 行:{node.message}") + continue + if node.type == "at-rule": + result.notes.append("条件规则、@规则保留在 CSS 中") + continue + if node.type != "qualified-rule": + continue + targets = {} + for part in _split(node.prelude): + selector = _selector(part) + target = ALIASES.get(selector) + if target: + targets[target] = max(targets.get(target, (0, 0)), _specificity(selector)) + else: + result.notes.append("其他选择器保留在 CSS 中") + declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False) + for position, raw in enumerate(declarations): + if raw.type == "error": + result.errors.append(f"第 {raw.source_line} 行:{raw.message}") + continue + if raw.type == "declaration" and not raw.name.startswith("--") and not _text(raw.value): + result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。") + continue + expanded = _expand(raw) + if raw.type in ("qualified-rule", "at-rule"): + result.notes.append("嵌套规则保留在 CSS 中") + if raw.type == "declaration" and raw.lower_name == "font" and len(expanded) == 1: + # A shorthand resets all five longhands, even if its value cannot + # be represented. Do not show stale, overridden control values. + expanded += [_declaration(prop, "var(--unsupported-font-shorthand)", raw.important) + for prop in ("font-family", "font-size", "font-weight", "font-style", "line-height")] + for declaration in expanded: + if declaration.type != "declaration": + continue + prop = _property(declaration) + if prop == "font": + result.notes.append("font 简写保留在 CSS 中;核心字体请使用 font-family/font-size 等属性") + if prop not in CORE_PROPERTIES: + continue + for target, specificity in targets.items(): + rank = (declaration.important, specificity, order, position) + if prop not in winners[target] or rank >= winners[target][prop][0]: + winners[target][prop] = (rank, _text(declaration.value)) + for target, entries in winners.items(): + props = {key: value[1] for key, value in entries.items()} + rule = {} + def read(prop, convert): + if prop not in props or props[prop].lower() in ("inherit", "unset", "revert"): + return + try: + convert(props[prop]) + except (ValueError, KeyError, TypeError): + result.notes.append(f"{LABELS[target]}的 {prop}: {props[prop]} 仅保留为 CSS") + def choice(prop, key, options): + read(prop, lambda value: rule.update({key: options[value.lower()]})) + def sized(value): + amount, unit = _length(value, ("pt", "px")) + if not 0 < amount <= 200: + raise ValueError + rule.update(font_size=amount, font_size_unit=unit) + read("font-size", sized) + def families(value): + if re.sub(r"\s+", "", value) == re.sub(r"\s+", "", FONT_EXPRESSION): + for key, variable in FONT_VARIABLES.items(): + if variable in props: + rule[key] = _font_names(props[variable])[0] + else: + names = _font_names(value) + rule.update(english_font_family=names[0], chinese_font_family=names[1] if len(names) > 1 and names[1] not in ("serif", "sans-serif", "monospace") else names[0]) + read("font-family", families) + choice("font-weight", "bold", {"bold": True, "700": True, "normal": False, "400": False}) + choice("font-style", "italic", {"italic": True, "normal": False}) + choice("text-align", "alignment", {name: name for name in ("left", "center", "right", "justify")}) + def color(value): + if value.lower() in ("currentcolor", "var(--reader-text-color, #23272f)"): + rule["font_color"] = "auto" + return + rgba = parse_color(value) + if rgba is None or isinstance(rgba, str) or rgba.alpha != 1: + raise ValueError + rule["font_color"] = "#" + "".join(f"{round(v * 255):02x}" for v in rgba[:3]) + read("color", color) + def tracking(value): + amount, unit = (0, "pt") if value == "normal" else _length(value, ("pt", "px"), negative=True) + amount *= .75 if unit == "px" else 1 + if abs(amount) > 100: + raise ValueError + rule["letter_spacing"] = amount + read("letter-spacing", tracking) + def line(value): + if value == "normal": + amount, mode = 1, "multiple" + elif re.fullmatch(r"(?:\d+(?:\.\d*)?|\.\d+)%?", value): + amount = float(value.rstrip("%")) / (100 if value.endswith("%") else 1) + mode = "multiple" + else: + amount, unit = _length(value, ("pt", "px")) + amount *= .75 if unit == "px" else 1 + mode = "at_least" if props.get("--mdhelper-line-spacing-mode") == "at-least" else "exact" + if not .1 <= amount <= 500: + raise ValueError + rule.update(line_height_value=amount, line_spacing_mode=mode) + read("line-height", line) + for side, prefix in (("left", "left_indent"), ("right", "right_indent"), ("top", "space_before"), ("bottom", "space_after")): + def margin(value, prefix=prefix): + amount, unit = _length(value, ("em", "pt", "px", "cm") if "indent" in prefix else ("em", "pt", "px", "lh", "cm")) + if unit == "px": + amount, unit = amount * .75, "pt" + if unit == "cm" and "indent" not in prefix: + amount, unit = amount * 72 / 2.54, "pt" + if amount > (200 if "indent" in prefix else 1000): + raise ValueError + rule.update({prefix + "_value": amount, prefix + "_unit": "line" if unit == "lh" else unit}) + read("margin-" + side, margin) + def indent(value): + amount, unit = _length(value, ("em", "pt", "px"), negative=True) + if unit != "em": + points = font_points({**resolved_rules({}, font_size_px=font_size_px)[target], **rule}) + amount = amount * (.75 if unit == "px" else 1) / points + if abs(amount) > 100: + raise ValueError + rule.update(indent_mode="none" if not amount else "first" if amount > 0 else "hanging", indent_value=abs(amount)) + read("text-indent", indent) + for field, modern, legacy, yes in (("keep_with_next", "break-after", "page-break-after", ("avoid", "avoid-page")), + ("keep_lines_together", "break-inside", "page-break-inside", ("avoid", "avoid-page")), + ("page_break_before", "break-before", "page-break-before", ("page", "always"))): + candidates = [name for name in (modern, legacy) if name in entries] + if candidates: + prop = max(candidates, key=lambda name: entries[name][0]) + choice(prop, field, {**{v: True for v in yes}, "auto": False}) + widow_values = [props[p] for p in ("widows", "orphans") if p in props] + if widow_values: + if all(v == "1" for v in widow_values) or all(v == "2" for v in widow_values): + rule["widow_control"] = widow_values[0] == "2" + else: + result.notes.append(f"{LABELS[target]}的 widows/orphans 仅保留为 CSS") + choice("--mdhelper-contextual-spacing", "contextual_spacing", {"true": True, "false": False}) + if rule: + result.rules[target] = rule + result.notes = list(dict.fromkeys(result.notes)) + return result + + +def _core_declarations(rule): + declarations = [d for d in css_declarations(rule) if not d.startswith(("font-family:", "padding-left:"))] + if any(rule.get(key) for key in FONT_VARIABLES): + for key, variable in FONT_VARIABLES.items(): + if rule.get(key): + name = str(rule[key]).replace("\\", "\\\\").replace('"', '\\"') + declarations.append(f'{variable}: "{name}";') + declarations.append(f"font-family: {FONT_EXPRESSION};") + if "line_spacing_mode" in rule: + declarations.append(f"--mdhelper-line-spacing-mode: {rule['line_spacing_mode'].replace('_', '-')};") + if "contextual_spacing" in rule: + declarations.append(f"--mdhelper-contextual-spacing: {str(rule['contextual_spacing']).lower()};") + return declarations + + +def source_from_payload(payload: dict) -> str: + if payload.get("css_sync_version") == 1: + return str(payload.get("css") or "") + rules = payload.get("rules") + if isinstance(rules, dict) and rules: + blocks = [] + for target, _, selector in STYLE_TARGETS: + declarations = _core_declarations(normalize_rule(rules.get(target))) + if declarations: + blocks.append(selector + " {\n " + "\n ".join(declarations) + "\n}") + return "\n\n".join(blocks + [str(payload.get("extra_css") or "")]).strip() + return str(payload.get("extra_css") or payload.get("css") or "") + + +def patch_core(source: str, target: str, before: dict, after: dict, *, reset=False) -> str: + """Change only edited groups, preserving comments, extensions and conditions.""" + changed = set(GROUPS) if reset else {group for group, keys in GROUPS.items() if any(before.get(key) != after.get(key) for key in keys)} + if not changed: + return source + affected = set().union(*(PROPERTIES[group] for group in changed)) + important = set() + output = [] + for node in css.parse_stylesheet(source, skip_whitespace=False, skip_comments=False): + if node.type != "qualified-rule": + output.append(node) + continue + selectors = _split(node.prelude) + selected = [p for p in selectors if ALIASES.get(_selector(p)) == target] + if not selected: + output.append(node) + continue + others = [p for p in selectors if ALIASES.get(_selector(p)) != target] + declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False) + kept = [] + touched = False + for raw in declarations: + expanded = _expand(raw) + relevant = [d for d in expanded if d.type == "declaration" and _property(d) in affected] + if reset and raw.type == "declaration" and raw.lower_name == "font": + touched = True + continue + if not relevant: + kept.append(raw) + if raw.type == "declaration" and raw.lower_name == "font" and raw.important: + important.update(changed & {"fonts", "size", "bold", "italic", "line"}) + continue + touched = True + for declaration in expanded: + if declaration.type == "declaration" and _property(declaration) in affected: + if declaration.important: + important.update(group for group in changed if _property(declaration) in PROPERTIES[group]) + else: + kept.append(declaration) + if not touched: + output.append(node) + continue + if others: + original = deepcopy(node) + original.prelude = css.parse_component_value_list(", ".join(_text(p) for p in others) + " ") + output.append(original) + has_replacement = any(key in after for group in changed for key in GROUPS[group]) + if has_replacement or any(d.type not in ("whitespace",) for d in kept): + node.prelude = css.parse_component_value_list(", ".join(_text(p) for p in selected) + " ") + node.content = css.parse_component_value_list(css.serialize(kept)) + output.append(node) + fragment = {key: value for group in changed for key in GROUPS[group] if (value := after.get(key)) is not None} + declarations = _core_declarations(fragment) + marked = [] + for text in declarations: + prop = text.split(":", 1)[0] + if any(prop in PROPERTIES[group] for group in important): + text = text.rstrip(";") + " !important;" + marked.append(text) + # Reuse an existing block for this object, retaining its authored selector. + # This also avoids expanding a simple .reader p rule into a second block. + if marked: + canonical = next((node for node in reversed(output) if node.type == "qualified-rule" and + all(ALIASES.get(_selector(part)) == target for part in _split(node.prelude))), None) + if canonical is not None: + content = css.serialize(canonical.content).rstrip() + "\n " + "\n ".join(marked) + "\n" + canonical.content = css.parse_component_value_list(content) + marked = [] + result = css.serialize(output).rstrip() + if marked: + result += ("\n\n" if result else "") + SELECTORS[target] + " {\n " + "\n ".join(marked) + "\n}" + return result + + +def render_css(source: str, rules: dict) -> str: + """Materialize the few core features which need companion reader rules.""" + contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if rule.get("contextual_spacing")} + helpers = build_document_style_css(contextual) + paragraph = rules.get("paragraph", {}) + if paragraph.get("font_size"): + helpers += f"\n.reader {{ --reader-math-font-size: {fmt(paragraph['font_size'])}{paragraph.get('font_size_unit', 'px')}; }}" + if rules.get("list"): + helpers += "\n.reader li > p { margin: 0; text-indent: inherit; }" + return (helpers.strip() + "\n\n" + source).strip() + + +def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_px=16) -> dict: + source = source_from_payload(payload) + result = analyze_css(source, font_size_px) + return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name, + "css_sync_version": 1, "css": source, + "rules": result.rules if not result.errors else deepcopy(payload.get("rules") or {})} diff --git a/requirements.txt b/requirements.txt index 1b60c2e..d1bb60c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # Core dependencies for MDHelper PySide6==6.11.1 markdown-it-py==4.2.0 +tinycss2==1.5.1 Pygments==2.20.0 Pillow==12.2.0 python-docx==1.2.0 diff --git a/tests/test_document_style.py b/tests/test_document_style.py index 8b8c630..12f6f06 100644 --- a/tests/test_document_style.py +++ b/tests/test_document_style.py @@ -77,7 +77,7 @@ def test_dialog_legacy_px_and_no_duplicate_generated_css(app): dialog = DocumentStyleEditorDialog({"rules": {"paragraph": {"font_size": 18}}, "css": ".reader p {font-size:18px}"}) try: assert dialog.font_size_unit_combo.currentData() == "px" - assert not dialog.extra_css_edit.toPlainText() + assert dialog.extra_css_edit.toPlainText().count("font-size:") == 1 dialog.font_size_preset_combo.setCurrentIndex(dialog.font_size_preset_combo.findData(10.5)) rule = dialog.style_payload()["rules"]["paragraph"] assert rule["font_size"] == 10.5 and rule["font_size_unit"] == "pt" diff --git a/tests/test_style_sync.py b/tests/test_style_sync.py new file mode 100644 index 0000000..8b1f81c --- /dev/null +++ b/tests/test_style_sync.py @@ -0,0 +1,232 @@ +import os +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import zipfile +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QApplication, QDialogButtonBox + +from mdhelper.style_sync import analyze_css, patch_core, source_from_payload, normalize_payload, render_css +from mdhelper.style_dialog import DocumentStyleEditorDialog +from mdhelper.docx_exporter import export_markdown_to_docx + + +@pytest.fixture +def app(): + return QApplication.instance() or QApplication([]) + + +def test_graphical_changes_update_full_css_without_losing_extensions(app): + source = '.reader p { font-size: 12pt; border: 1px solid red; }\n@media print { p { background: #eee; } }' + dialog = DocumentStyleEditorDialog({"css": source}) + try: + assert dialog.font_size_spin.value() == 12 + dialog.font_size_spin.setValue(14) + payload = dialog.style_payload() + assert payload["css_sync_version"] == 1 + assert payload["rules"]["paragraph"]["font_size"] == 14 + assert 'border: 1px solid red;' in payload["css"] + assert 'p:not' not in payload["css"] # Update the authored object rule in place. + assert '@media print { p { background: #eee; } }' in payload["css"] + reopened = DocumentStyleEditorDialog(payload) + try: + assert reopened.style_payload() == payload + finally: + reopened.close() + finally: + dialog.close() + + +def test_css_to_controls_immediate_save_and_undo(app): + dialog = DocumentStyleEditorDialog() + try: + dialog.extra_css_edit.setPlainText('p {font-size:10.5pt; font-weight:700; text-indent:2em; color:rgb(255,0,0); margin:0;}') + # Saving before the debounce timer fires must use the new CSS. + rules = dialog.style_payload()["rules"]["paragraph"] + assert rules["font_size"] == 10.5 and rules["bold"] is True + assert rules["font_color"] == "#ff0000" + assert dialog.font_size_spin.value() == 10.5 + assert dialog.bold_checkbox.checkState() == Qt.CheckState.Checked + assert dialog.indent_mode_combo.currentData() == "first" + assert dialog.space_before_spin.value() == 0 + before = dialog.extra_css_edit.toPlainText() + dialog.font_size_spin.setValue(16) + dialog.extra_css_edit.undo() + assert dialog.style_payload()["css"] == before + assert dialog.font_size_spin.value() == 10.5 + finally: + dialog.close() + + +def test_invalid_css_does_not_clobber_previous_rules(app): + dialog = DocumentStyleEditorDialog({"css": 'p {font-size:14pt;} '}) + try: + dialog.extra_css_edit.setPlainText('p {font-size:') + assert not dialog._sync_from_css() + assert dialog.rules["paragraph"]["font_size"] == 14 + assert not dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled() + with pytest.raises(ValueError): + dialog.style_payload() + dialog.extra_css_edit.setPlainText('p {font-size:16pt;}') + assert dialog.style_payload()["rules"]["paragraph"]["font_size"] == 16 + assert dialog.button_box.button(QDialogButtonBox.StandardButton.Ok).isEnabled() + finally: + dialog.close() + + +def test_cascade_grouped_selectors_important_and_preserved_comments(): + source = '/* keep ; } */ p,h1,.custom { font-size:12pt !important; background:url("a;b.png"); } p {font-size:20px;}' + before = analyze_css(source).rules["paragraph"] + assert before["font_size"] == 12 + patched = patch_core(source, "paragraph", before, {**before, "font_size": 18}) + result = analyze_css(patched) + assert result.rules["paragraph"]["font_size"] == 18 + assert result.rules["h1"]["font_size"] == 12 + assert 'background:url("a;b.png");' in patched + assert '/* keep ; } */' in patched and '.custom' in patched + assert 'font-size: 18pt !important' in patched + + +def test_margin_shorthand_change_one_side_preserves_other_sides(): + source = 'p {margin: 1pt 2pt 3pt 4pt; box-shadow:0 1px 2px #333;}' + before = analyze_css(source).rules["paragraph"] + updated = patch_core(source, "paragraph", before, {**before, "space_before_value": 0}) + rule = analyze_css(updated).rules["paragraph"] + assert rule["space_before_value"] == 0 + assert rule["right_indent_value"] == 2 + assert rule["space_after_value"] == 3 and rule["left_indent_value"] == 4 + assert 'box-shadow:0 1px 2px #333;' in updated + + +def test_font_shorthand_and_individual_override(): + source = 'p {font: italic bold 14pt/1.5 "Times New Roman", "宋体"; color: navy;}' + rule = analyze_css(source).rules["paragraph"] + assert rule["font_size"] == 14 and rule["bold"] and rule["italic"] + assert rule["chinese_font_family"] == "宋体" and rule["line_height_value"] == 1.5 + result = analyze_css(patch_core(source, "paragraph", rule, {**rule, "font_size": 16})) + assert result.rules["paragraph"]["font_size"] == 16 + assert result.rules["paragraph"]["bold"] and result.rules["paragraph"]["italic"] + + +def test_unsupported_values_remain_css_and_do_not_reappear_as_stale_controls(): + source = 'p {font-size:12pt; font:var(--other); font-size:calc(10pt + 2vw); color:red;} @media screen {p {color:blue;}}' + result = analyze_css(source) + assert not result.errors + assert "font_size" not in result.rules["paragraph"] + assert result.notes + changed = patch_core(source, "paragraph", result.rules["paragraph"], {**result.rules["paragraph"], "font_color": "#008000"}) + assert 'font-size:calc(10pt + 2vw)' in changed + assert '@media screen {p {color:blue;}}' in changed + assert analyze_css(changed).rules["paragraph"]["font_color"] == "#008000" + + +@pytest.mark.parametrize("field,value", [("chinese_font_family", "宋体"), ("english_font_family", "Arial")]) +def test_single_language_font_and_word_only_modes_roundtrip(field, value): + rule = {field: value, "line_spacing_mode": "at_least", "line_height_value": 22, "contextual_spacing": False, + "keep_with_next": False, "keep_lines_together": True, "page_break_before": True, "widow_control": False} + migrated = normalize_payload({"rules": {"paragraph": rule}}) + assert migrated["rules"]["paragraph"] == rule + assert normalize_payload(migrated) == migrated + + +def test_reset_only_removes_core_leaving_extensions_and_other_targets(app): + dialog = DocumentStyleEditorDialog({"css": 'p,h2 {font-size:14pt; border:1px solid blue;} p {color:red;}'} ) + try: + dialog._reset_current_rule() + payload = dialog.style_payload() + assert "paragraph" not in payload["rules"] + assert payload["rules"]["h2"]["font_size"] == 14 + assert "border:1px solid blue" in payload["css"] + finally: + dialog.close() + + +def test_valid_nested_and_conditional_extensions_are_preserved(): + source = 'p {color: red; &:hover {color: blue;}} @supports (display:grid) {p{display:grid;}}' + result = analyze_css(source) + assert not result.errors and result.rules["paragraph"]["font_color"] == "#ff0000" + changed = patch_core(source, "paragraph", result.rules["paragraph"], {"font_color": "#008000"}) + assert '&:hover {color: blue;}' in changed and '@supports' in changed + + +@pytest.mark.parametrize("engine", ["builtin", "python-docx", "pandoc"]) +def test_css_edits_reach_word_via_saved_rules(tmp_path, engine): + payload = normalize_payload({"css": 'p {font-size:14pt;color:#123456; margin:0; text-align:center; line-height:24pt; --mdhelper-line-spacing-mode:at-least;}'} ) + docx = export_markdown_to_docx("CSS 同步到 Word", tmp_path / f"{engine}.docx", engine=engine, style_rules=payload["rules"]) + from lxml import etree + with zipfile.ZipFile(docx) as archive: + doc = etree.fromstring(archive.read("word/document.xml")) + ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"} + w = "{" + ns["w"] + "}" + assert doc.find(".//w:sz", ns).get(w + "val") == "28" + assert doc.find(".//w:color", ns).get(w + "val") == "123456" + assert doc.find(".//w:jc", ns).get(w + "val") == "center" + assert doc.find(".//w:spacing", ns).get(w + "lineRule") == "atLeast" + + +def test_contextual_helper_materialization_and_legacy_extra_css_override(): + source = source_from_payload({"rules": {"paragraph": {"font_size": 12, "font_size_unit": "pt"}}, + "extra_css": '.reader p {font-size:14pt; --mdhelper-contextual-spacing:true;}'} ) + result = analyze_css(source) + assert result.rules["paragraph"]["font_size"] == 14 + rendered = render_css(source, result.rules) + assert '--reader-math-font-size: 14pt' in rendered and 'margin-bottom: 0' in rendered + + +def test_debounced_typing_keeps_css_text_and_cursor(app): + from PySide6.QtTest import QTest + dialog = DocumentStyleEditorDialog() + try: + dialog.tabs.setCurrentIndex(1) + source = 'p { font-size: 15pt; color: blue; } /* authored */' + dialog.extra_css_edit.setPlainText(source) + cursor = dialog.extra_css_edit.textCursor() + cursor.setPosition(9) + dialog.extra_css_edit.setTextCursor(cursor) + QTest.qWait(450) + assert dialog.font_size_spin.value() == 15 + assert dialog.extra_css_edit.toPlainText() == source + assert dialog.extra_css_edit.textCursor().position() == 9 + finally: + dialog.close() + + +def test_style_file_roundtrip_reader_and_word_integration(app, tmp_path, monkeypatch): + from PySide6.QtCore import QSettings + from mdhelper import main_window + monkeypatch.setattr(main_window, "QSettings", lambda *_: QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat)) + window = main_window.MainWindow(None, app_root=tmp_path) + try: + source = 'p {font-size:14pt; color:red; border:1px solid blue;}' + window.custom_document_styles['custom:sync'] = window._normalize_document_style_payload({'name': '同步测试', 'css': source}) + style_file = tmp_path / 'test.mdhelper-style' + window._write_document_style_file(style_file, 'custom:sync') + imported = window._import_document_style_file(style_file) + payload = window._style_payload_for_id(imported) + assert payload['css'] == source and payload['css_sync_version'] == 1 + assert payload['rules']['paragraph']['font_size'] == 14 + window.document_style_id = imported + assert 'border:1px solid blue' in window._document_style_css() + markdown = tmp_path / 'test.md' + markdown.write_text('同步正文', encoding='utf-8') + window.current_file = markdown + docx_path = window.export_docx_to_path(tmp_path / 'test.docx') + with zipfile.ZipFile(docx_path) as archive: + xml = archive.read('word/document.xml').decode() + assert 'w:sz w:val="28"' in xml and 'w:color w:val="ff0000"' in xml + finally: + window.close() + + +def test_selector_formatting_and_case_sensitive_custom_properties(): + source = '.reader p:not(:where( li p,blockquote p,.admonition p,th p,td p )) {font-size:14pt; --MDHELPER-contextual-spacing:true;}' + result = analyze_css(source) + assert result.rules["paragraph"]["font_size"] == 14 + assert "contextual_spacing" not in result.rules["paragraph"] + assert analyze_css('p {font-size:;}').errors + + +def test_reset_can_remove_unrepresentable_core_values(): + source = 'p {font-size:calc(10pt + 1vw); border:1px solid red; font:var(--dynamic);}' + changed = patch_core(source, "paragraph", {}, {}, reset=True) + assert 'font' not in changed and 'border:1px solid red' in changed