diff --git a/docs/architecture.md b/docs/architecture.md index 749759f..d33ebfe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -29,6 +29,8 @@ `style_catalog.py` 定义稳定的语义标识、类型、名称、同类型继承及 Markdown 使用情况。格式声明仍以 `style_sync.py` 解析的核心 CSS 为准,名称与基准单独保存在 `rules._metadata`,通过原有配置和项目预设路径持久化。旧 `list`、`code`、`table` 作为兼容基准,细分对象未设置时继承它们。 +从内置样式复制时,`rules._preset` 保留原默认值来源;绝对首行/悬挂缩进使用 `indent_unit`,缺省仍为旧版的字符单位。图形编辑器对比控件加载快照,只写回实际编辑的组,避免范围限制和显示精度改写未编辑的 CSS。 + `style_panel.py` 仅在用户打开时创建,按文档版本缓存语法分析,隐藏时停止刷新;`style_dialog.py` 的实际阅读预览也只在切换到该页时创建。启动路径不创建这些浏览器,不重建主窗口。 `docx_style.py` 负责格式字段与 OOXML 属性的转换及属性顺序;`docx_semantic.py` 识别各引擎输出的语义、生成命名段落/字符/表格样式,并按属性保留继承。保留编号、公式、关系和书签;除用于防止 Word 反向切换的明确字符字形(加粗、斜体、删除线)外,不重复写入直接字体、字号、颜色和段落格式。组合字符采用命名样式。`tests/word_styles_smoke.ps1` 使用本机 Word 的独立隐藏实例,验证打开文件、样式修改传播及继承,关闭时不保存测试修改。 @@ -49,6 +51,8 @@ CSS 同步按三个步骤处理:`_collect_cascade` 决定生效的声明,`_CoreRuleReader` 转换可表达的字体和段落属性,`analyze_css` 汇总结果。无法映射的 CSS 继续保留原文,不改写级联规则或 Word 的支持范围。 +明确无效的声明在级联选择前忽略;简写中任一无效组件使整条简写失效,有效但不支持的表达式仍遮盖前面的值。普通 `p` 同时映射引用段落及 `rules._list_paragraph` 上下文;各引擎通过临时段落标记区分宽松列表和紧凑列表。表格文字使用独立内容容器承载段间距,表格边框和单元格内边距保持原位置。 + `render_css` 使用与图形写入相同的字体变量表达继承,并生成列表层级缩进及独立文字修饰的辅助规则。显式取消列表基准时会恢复该语义类型的默认格式,旧配置缺少元数据时仍保留兼容基准。 `docx_inline.py` 定义转换阶段的临时字符样式标记,记录 Markdown 从外到内的语义顺序。两个基础引擎直接记录解析栈;Pandoc 使用随包资源 `word_inline_styles.lua` 记录同一顺序。最终样式处理替换并删除临时标记,脚注仍保留原段落样式、编号和关系;导出文件不需要脚本或宏。 diff --git a/docs/user_manual.md b/docs/user_manual.md index 3e4fdce..7f005ed 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -187,6 +187,10 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加 核心同步覆盖对象的常规选择器,例如 `p`、`.reader p`、`h1`、`.reader h1`、`strong`、`em`、`s`、`a`,以及程序生成的 `data-mdh-style` 语义选择器。可识别的属性包括字体、字号、颜色、字符间距、`text-decoration-line`、`background-color`、对齐、行距、缩进、四向间距、换行分页,以及 `border-color` / `border-width`、表格 `padding` 和 `list-style-type`。支持常见字体简写、间距简写和 `!important`;重置当前对象只清除其核心设置,保留扩展效果。 +普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。 + +颜色选择“随所在文字颜色”(CSS `currentColor` / `inherit`)会继承段落或外层文字的颜色,不等同于“自动(随主题)”。如果它同时需要取消某个字符基准中的固定颜色,Word 无法只取消一个继承属性,因此导出会将该基准的其他已解析格式保留在当前命名字符样式内;导出后请修改此命名样式,其他普通样式的基准继承保持不变。 + 例如,将正文规则中的 `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` 表示同样式段落间不添加间距。这些属性由图形设置自动生成。 diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py index 76f3bfa..3e94e70 100644 --- a/mdhelper/document_style.py +++ b/mdhelper/document_style.py @@ -65,7 +65,7 @@ def normalize_rule(value: object) -> dict[str, Any]: if key in rule and not isinstance(rule[key], bool): rule.pop(key) for key in ('font_color', 'background_color', 'border_color'): - if key in rule and not re.fullmatch(r"auto|transparent|#[0-9a-fA-F]{6}", str(rule[key])): + if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])): rule.pop(key) for key, allowed in {"alignment": {"left", "center", "right", "justify"}, "indent_mode": {"none", "first", "hanging"}, diff --git a/mdhelper/docx_exporter.py b/mdhelper/docx_exporter.py index 26b76e0..a0afe05 100644 --- a/mdhelper/docx_exporter.py +++ b/mdhelper/docx_exporter.py @@ -15,7 +15,7 @@ from markdown_it import MarkdownIt from markdown_it.token import Token from .markdown_compat import cjk_strong_plugin -from .docx_inline import source_style_name +from .docx_inline import source_style_name, LIST_PARAGRAPH_STYLE WP_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" @@ -118,6 +118,7 @@ def export_markdown_to_docx_builtin(source: str, output_path: Path) -> Path: package.writestr("_rels/.rels", PACKAGE_RELS_XML) package.writestr("word/document.xml", document_xml) markers = ''.join(f'' for name in sorted(source_styles)) + markers += f'' package.writestr("word/styles.xml", STYLES_XML.replace('', markers + '')) package.writestr("word/settings.xml", SETTINGS_XML) relations = ''.join(f'' for href, identifier in links.items()) @@ -245,6 +246,12 @@ def _add_python_docx_paragraph(document: object, block: ParagraphBlock) -> None: elif block.quote_depth: style = "Quote" + if block.list_kind and block.loose: + from docx.enum.style import WD_STYLE_TYPE + if LIST_PARAGRAPH_STYLE not in document.styles: + marker = document.styles.add_style(LIST_PARAGRAPH_STYLE, WD_STYLE_TYPE.PARAGRAPH) + marker.base_style = document.styles[style] + style = LIST_PARAGRAPH_STYLE paragraph = document.add_paragraph(style=style) if block.list_kind: from docx.oxml import parse_xml @@ -319,6 +326,7 @@ class ParagraphBlock: list_level: int = 0 list_id: int = 0 list_start: int = 1 + loose: bool = False @dataclass @@ -377,7 +385,7 @@ class _DocxBuilder: 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, list_level=min(8, max(0, len(self.list_stack) - 1)), list_id=self.list_ids[-1] if self.list_ids else 0, - list_start=self.list_starts[-1] if self.list_starts else 1)) + list_start=self.list_starts[-1] if self.list_starts else 1, loose=not self.tokens[self.index].hidden)) self.index += 3 def _collect_table(self) -> TableBlock: @@ -471,7 +479,7 @@ def _block_xml(block: ParagraphBlock | TableBlock) -> str: def _paragraph_xml(block: ParagraphBlock) -> str: props = [f''] if block.style != "Normal" else [] if block.list_kind: - props = [''] + props = [f''] props.append(f'') if block.quote_depth: props.append('') diff --git a/mdhelper/docx_inline.py b/mdhelper/docx_inline.py index 86a47a0..f4f9f05 100644 --- a/mdhelper/docx_inline.py +++ b/mdhelper/docx_inline.py @@ -1,5 +1,6 @@ """Private, temporary style markers shared by the three DOCX converters.""" PREFIX = 'MDHelperSource_' +LIST_PARAGRAPH_STYLE = 'MDHelperSourceListParagraph' CODES = {'strong': 'B', 'emphasis': 'I', 'strike': 'S', 'link': 'L', 'inline_code': 'C'} diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py index f112405..9068c72 100644 --- a/mdhelper/docx_semantic.py +++ b/mdhelper/docx_semantic.py @@ -13,7 +13,7 @@ from lxml import etree as ET from .document_style import resolved_rules, normalize_rule, font_points, length_points, number from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties -from .docx_inline import source_style_order, ordered_styles +from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split() PARAGRAPH_FIELDS = 'jc spacing ind shd snapToGrid contextualSpacing keepNext keepLines pageBreakBefore widowControl rPr outlineLvl'.split() @@ -121,7 +121,8 @@ class WordStyles: remove_fields(child(table_text, 'rPr'), ('shd',)) base = 'table' style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(key, self.rules), base_id) - rule = self.effective[key] + rule = dict(self.effective[key]) + if rule.get('font_color') == 'inherit': rule['font_color'] = 'auto' _paragraph_properties(child(style, 'pPr'), rule) _run_properties(child(style, 'rPr'), rule) remove_fields(child(style, 'rPr'), ('shd',)) @@ -149,10 +150,14 @@ class WordStyles: if identifier in self.created: return identifier base = parent_style(key, self.rules) base_id = self.character(base) if base else '' - style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id) rule = self.character_rule(key) + # Word cannot clear one inherited character-style property. Preserve + # the resolved remaining properties and inherit color from the text. + if rule.get('font_color') == 'inherit' and base and self.character_rule(base).get('font_color') not in (None, 'inherit'): + base_id = '' + style = self.new(identifier, 'character', 'MDHelper ' + style_name(key, self.rules), base_id) _run_properties(child(style, 'rPr'), rule) - if base: + if base_id: old = ET.Element(W + 'rPr') _run_properties(old, self.character_rule(base)) _delta(child(style, 'rPr'), old, normalize_rule(self.rules.get(key))) @@ -161,8 +166,9 @@ class WordStyles: def combined_character(self, keys, paragraph_target): keys = ordered_styles(keys) if not keys: return '' - merged = dict(self.character_rule(keys[0])) - for key in keys[1:]: merged.update(self.character_rule(key)) + merged = {} + for key in keys: + merged.update({field: value for field, value in self.character_rule(key).items() if not (field == 'font_color' and value == 'inherit')}) identifier = self.character(keys[0]) if len(keys) == 1 else 'MDHelperMix' + ''.join(style_id(key)[8:] for key in keys) if identifier not in self.created: base = 'link' if 'link' in keys else keys[0] @@ -248,6 +254,22 @@ class WordStyles: child(style, 'pPr').append(ind) return identifier + def list_paragraph(self, target, base_id): + """A loose Markdown list contains a real p element; a tight one does not.""" + own = normalize_rule(self.rules.get('_list_paragraph')) + if not own: return base_id + identifier = base_id + 'Paragraph' + if identifier not in self.created: + style = self.new(identifier, 'paragraph', 'MDHelper ' + style_name(target, self.rules) + '(段落)' + base_id.removeprefix(style_id(target)), base_id) + base = self.effective[target] + rule = {**base, **own} + for tag, writer in (('pPr', _paragraph_properties), ('rPr', _run_properties)): + props, old = child(style, tag), ET.Element(W + tag) + writer(props, rule); writer(old, base) + if tag == 'rPr': remove_fields(props, ('shd',)); remove_fields(old, ('shd',)) + _delta(props, old, own) + return identifier + def apply_list_marker(self, numpr, target, marker): level, original_level = self.list_level(numpr) if original_level is None: return @@ -331,7 +353,9 @@ class WordStyles: def apply(self, document): for paragraph in document.iter(W + 'p'): ppr = properties(paragraph, 'pPr') - target = self.classify(paragraph, reference(ppr, 'pStyle') or 'Normal') + original_id = reference(ppr, 'pStyle') or 'Normal' + loose = any(reference(style, 'name') == LIST_PARAGRAPH_STYLE for style in self.chain(original_id)) + target = self.classify(paragraph, original_id) identifier = self.paragraph(target) if target.startswith('list_'): numpr = ppr.find(W + 'numPr') @@ -339,6 +363,7 @@ class WordStyles: if level: identifier = self.nested_list(target, level) marker = self.effective[target].get('list_marker') if marker: self.apply_list_marker(numpr, target, marker) + if loose: identifier = self.list_paragraph(target, identifier) remove_fields(ppr, PARAGRAPH_FIELDS) val(ppr, 'pStyle', identifier) for run in paragraph.iter(W + 'r'): self.apply_run(run, target) @@ -362,12 +387,17 @@ def apply_semantic_styles(path, rules, **defaults): adapter.apply(parts['word/document.xml']) for name in ('word/footnotes.xml', 'word/endnotes.xml'): if name in parts: + for paragraph in parts[name].iter(W + 'p'): + identifier = reference(paragraph.find(W + 'pPr'), 'pStyle') + if any(reference(s, 'name') == LIST_PARAGRAPH_STYLE for s in adapter.chain(identifier)): + adapter.apply(paragraph) for run in parts[name].iter(W + 'r'): identifier = reference(run.find(W + 'rPr'), 'rStyle') if any(source_style_order(reference(s, 'name')) for s in adapter.chain(identifier)): adapter.apply_run(run, 'paragraph') for style in list(parts['word/styles.xml']): - if source_style_order(reference(style, 'name')): parts['word/styles.xml'].remove(style) + if source_style_order(reference(style, 'name')) or reference(style, 'name') == LIST_PARAGRAPH_STYLE: + parts['word/styles.xml'].remove(style) for filename, root in parts.items(): _order_properties(root) payloads[filename] = ET.tostring(root, encoding='UTF-8', xml_declaration=True, standalone=True) diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py index efbc14d..e0bb9c8 100644 --- a/mdhelper/docx_style.py +++ b/mdhelper/docx_style.py @@ -65,7 +65,7 @@ def _run_properties(rpr, rule): if key in rule: val(rpr, xml, int(rule[key])) if key != 'strike': val(rpr, xml + 'Cs', int(rule[key])) - if 'font_color' in rule: + if 'font_color' in rule and rule['font_color'] != 'inherit': color = child(rpr, "color") color.attrib.clear() color.set(W + "val", str(rule["font_color"]).lstrip("#")) diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index c0a4a1b..4acf8ff 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -69,6 +69,12 @@ class MarkdownRenderer: self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists) self.markdown.core.ruler.push("mdhelper_semantic_styles", self._mark_semantic_styles) self.markdown.core.ruler.push("mdhelper_source_lines", self._add_source_lines) + # Table-cell margins have no layout effect. A content block gives the + # semantic paragraph spacing a real box without changing table padding. + for name in ('th_open', 'td_open'): + self.markdown.renderer.rules[name] = lambda tokens, idx, options, env: self.markdown.renderer.renderToken(tokens, idx, options, env) + '
' + for name in ('th_close', 'td_close'): + self.markdown.renderer.rules[name] = lambda tokens, idx, options, env: '
' + self.markdown.renderer.renderToken(tokens, idx, options, env) for name in ("fence", "code_block", "math_block"): original = self.markdown.renderer.rules[name] def mapped(tokens, idx, options, env, render=original): diff --git a/mdhelper/resources/word_inline_styles.lua b/mdhelper/resources/word_inline_styles.lua index d4ef9d7..635a0dc 100644 --- a/mdhelper/resources/word_inline_styles.lua +++ b/mdhelper/resources/word_inline_styles.lua @@ -46,4 +46,15 @@ local function mark(items, stack) end return output end -return {{Inlines=function(items) return mark(items, {}) end}} +local function list_paragraphs(list) + for _, item in ipairs(list.content) do + for index, block in ipairs(item) do + if block.t == 'Para' then + item[index] = pandoc.Div({block}, pandoc.Attr('', {}, {['custom-style']='MDHelperSourceListParagraph'})) + end + end + end + return list +end +return {{Inlines=function(items) return mark(items, {}) end}, + {BulletList=list_paragraphs, OrderedList=list_paragraphs}} diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 89a074d..4e56635 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -229,7 +229,7 @@ class DocumentStyleEditorDialog(QDialog): form.addRow('每级列表缩进', self.level_indent_spin) for edit in (self.background_edit, self.border_color_edit): edit.editingFinished.connect(self._store_and_refresh) - self.color_combo = self._combo([("继承", None), ("自动(随主题)", "auto"), ("自定义…", "custom")]) + self.color_combo = self._combo([("继承", None), ("随所在文字颜色", "inherit"), ("自动(随主题)", "auto"), ("自定义…", "custom")]) self.color_button = QPushButton("#23272f") self.color_button.clicked.connect(self._choose_color) form.addRow("字体颜色", self._row(self.color_combo, self.color_button)) @@ -421,7 +421,7 @@ class DocumentStyleEditorDialog(QDialog): color = QColorDialog.getColor(QColor(self.color_button.text()), self, "字体颜色") if color.isValid(): self.color_button.setText(color.name()) - self.color_combo.setCurrentIndex(2) + self._select(self.color_combo, 'custom') self._store_and_refresh() def _apply_size_preset(self, *_: object) -> None: @@ -624,7 +624,7 @@ class DocumentStyleEditorDialog(QDialog): char.setFontUnderline(rule.get('underline', False)) char.setFontStrikeOut(rule.get('strike', False)) if str(rule.get('background_color', '')).startswith('#'): char.setBackground(QColor(rule['background_color'])) - char.setForeground(QColor("#23272f" if rule["font_color"] == "auto" else rule["font_color"])) + char.setForeground(QColor("#23272f" if rule["font_color"] in ('auto', 'inherit') else rule["font_color"])) char.setFontLetterSpacingType(QFont.SpacingType.AbsoluteSpacing) char.setFontLetterSpacing(number(rule["letter_spacing"]) * scale) cursor.insertText(part, char) diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index 54e008d..2fa6e6d 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -63,6 +63,7 @@ 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)" DECORATION_EXPRESSION = 'var(--mdhelper-text-decoration, none)' +LIST_PARAGRAPH = '_list_paragraph' @dataclass @@ -211,9 +212,40 @@ def _font_names(value): return names +def _invalid_core_value(prop, tokens): + """Reject definite invalid values; retain valid unsupported expressions.""" + tokens = [t for t in tokens if t.type not in ('whitespace', 'comment')] + if not tokens or any(t.type == 'error' for t in tokens): return True + if len(tokens) != 1: return False + token = tokens[0] + wide = {'inherit', 'initial', 'unset', 'revert', 'revert-layer'} + if token.type == 'ident' and token.lower_value in wide: return False + lengths = {'font-size', 'line-height', 'letter-spacing', 'text-indent', 'padding', 'border-width', + 'margin-top', 'margin-bottom', 'margin-left', 'margin-right'} + keywords = { + 'font-size': {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller', 'math'}, + 'line-height': {'normal'}, 'letter-spacing': {'normal'}, 'border-width': {'thin', 'medium', 'thick'}, + 'font-weight': {'normal', 'bold', 'bolder', 'lighter'}, 'font-style': {'normal', 'italic', 'oblique'}, + **{f'margin-{side}': {'auto'} for side in ('top', 'bottom', 'left', 'right')}, + } + if token.type == 'ident': + if prop in ('color', 'background-color', 'border-color'): return parse_color(token) is None + if prop in lengths or prop in keywords: return token.lower_value not in keywords.get(prop, set()) + if prop in lengths and token.type in ('dimension', 'number', 'percentage'): + if token.value < 0 and prop not in ('letter-spacing', 'text-indent') and not prop.startswith('margin-'): return True + if token.type == 'number': return prop != 'line-height' and token.value != 0 + if token.type == 'percentage': return prop not in ('font-size', 'line-height', 'text-indent', 'padding') and not prop.startswith('margin-') + units = {'px', 'pt', 'pc', 'in', 'cm', 'mm', 'q', 'em', 'rem', 'ex', 'rex', 'ch', 'rch', 'cap', 'rcap', 'ic', 'ric', 'lh', 'rlh', + 'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax', 'cqw', 'cqh', 'cqi', 'cqb', 'cqmin', 'cqmax'} + units.update(prefix + unit for prefix in ('s', 'l', 'd') for unit in ('vw', 'vh', 'vi', 'vb', 'vmin', 'vmax')) + return token.lower_unit not in units + if prop == 'font-weight' and token.type == 'number': return not 1 <= token.value <= 1000 + return False + + def _collect_cascade(source: str, result: Analysis): """Choose core declarations by importance, specificity and source order.""" - winners = {target: {} for target in SELECTORS} + winners = {target: {} for target in (*SELECTORS, LIST_PARAGRAPH)} 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}") @@ -228,7 +260,11 @@ def _collect_cascade(source: str, result: Analysis): selector = _selector(part) target = ALIASES.get(selector) if target: - targets[target] = max(targets.get(target, (0, 0)), _specificity(selector)) + direct = int(target != 'blockquote' or selector.endswith(' p')) + targets[target] = max(targets.get(target, (0, (0, 0))), (direct, _specificity(selector))) + if selector in ('p', '.reader p'): + for context in ('blockquote', LIST_PARAGRAPH): + targets[context] = max(targets.get(context, (0, (0, 0))), (1, _specificity(selector))) else: result.notes.append("其他选择器保留在 CSS 中") declarations = css.parse_blocks_contents(node.content, skip_comments=False, skip_whitespace=False) @@ -240,6 +276,11 @@ def _collect_cascade(source: str, result: Analysis): result.errors.append(f"第 {raw.source_line} 行:{raw.name} 缺少属性值。") continue expanded = _expand(raw) + if any(d.type == 'declaration' and _property(d) in CORE_PROPERTIES and + _invalid_core_value(_property(d), d.value) for d in expanded): + # One invalid component invalidates the entire shorthand. + result.notes.append(f'已忽略无效的 {raw.lower_name}: {_text(raw.value)},沿用前面的有效声明') + continue 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: @@ -255,8 +296,8 @@ def _collect_cascade(source: str, result: Analysis): 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) + for target, (direct, specificity) in targets.items(): + rank = (direct, declaration.important, specificity, order, position) if prop not in winners[target] or rank >= winners[target][prop][0]: winners[target][prop] = (rank, _text(declaration.value)) return winners @@ -340,7 +381,9 @@ class _CoreRuleReader: self.result.notes.append(f'{LABELS[self.target]}的 widows/orphans 仅保留为 CSS') def read(self, prop, convert): - if prop not in self.props or self.props[prop].lower() in ('inherit', 'unset', 'revert'): + if prop not in self.props: + return + if self.props[prop].lower() in ('inherit', 'unset', 'revert') and prop != 'color': return try: convert(self.props[prop]) @@ -367,7 +410,10 @@ class _CoreRuleReader: self.rule.update(english_font_family=names[0], chinese_font_family=chinese) def color(self, value): - if value.lower() in ('currentcolor', 'var(--reader-text-color, #23272f)'): + if value.lower() in ('currentcolor', 'inherit', 'unset'): + self.rule['font_color'] = 'inherit' + return + if value.lower() == 'var(--reader-text-color, #23272f)': self.rule['font_color'] = 'auto' return rgba = parse_color(value) @@ -420,7 +466,7 @@ def analyze_css(source: str, font_size_px: float = 16) -> Analysis: return result winners = _collect_cascade(source, result) for target, entries in winners.items(): - rule = _CoreRuleReader(target, entries, result, font_size_px).parse() + rule = _CoreRuleReader('paragraph' if target == LIST_PARAGRAPH else target, entries, result, font_size_px).parse() if rule: result.rules[target] = rule result.notes = list(dict.fromkeys(result.notes)) @@ -522,7 +568,9 @@ def patch_core(source: str, target: str, before: dict, after: dict, *, reset=Fal # 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) + all(ALIASES.get(_selector(part)) == target and + (target != 'blockquote' or _selector(part).endswith(' p')) + 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) @@ -556,6 +604,12 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl for key, rule in inherited.items(): declarations = _core_declarations(rule) if declarations: helpers += '\n' + SELECTORS[key] + ' { ' + ' '.join(declarations) + ' }' + for key in ('table_head', 'table_cell'): + rule = {**inherited.get(key, {}), **rules.get(key, {})} + margins = {field: value for field, value in rule.items() if field.startswith(('space_before_', 'space_after_', 'left_indent_', 'right_indent_'))} + declarations = _core_declarations(margins) + if declarations: + helpers += '\n' + SELECTORS[key] + ' > .mdhelper-cell-paragraph { ' + ' '.join(declarations) + ' }' # The legacy code rule also selects the inner . Let the semantic # block own its typography instead of leaving that old child rule in charge. block = {**inherited.get('code_block', {}), **rules.get('code_block', {})} @@ -598,7 +652,7 @@ def normalize_payload(payload: dict, fallback_name="自定义样式", font_size_ if metadata: result.rules['_metadata'] = metadata from .style_presets import DOCUMENT_STYLE_PRESETS - if supplied_rules.get('_preset') in DOCUMENT_STYLE_PRESETS: + if isinstance(supplied_rules.get('_preset'), str) and supplied_rules['_preset'] in DOCUMENT_STYLE_PRESETS: result.rules['_preset'] = supplied_rules['_preset'] return {"name": str(payload.get("name") or fallback_name).strip() or fallback_name, "css_sync_version": 1, "css": source, diff --git a/tests/conftest.py b/tests/conftest.py index 91c0ce3..bfc4960 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,6 +8,7 @@ os.environ.setdefault("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu --no-sandbox import pytest from PySide6.QtWidgets import QApplication from PySide6.QtGui import QFontDatabase +from PySide6.QtCore import QCoreApplication, QEvent @pytest.fixture(scope="session", autouse=True) @@ -19,3 +20,12 @@ def qt_application(): QFontDatabase.addApplicationFont(os.path.join(os.environ.get("WINDIR", "C:/Windows"), "Fonts", "msyh.ttc")) yield app app.processEvents() + + +@pytest.fixture(autouse=True) +def release_closed_widgets(qt_application): + yield + # processEvents alone does not flush DeferredDelete without app.exec(). + # Release closed WebEngine pages before the next rendering regression. + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + qt_application.processEvents() diff --git a/tests/gui_smoke.py b/tests/gui_smoke.py index e0fb3f2..6e4e571 100644 --- a/tests/gui_smoke.py +++ b/tests/gui_smoke.py @@ -92,12 +92,11 @@ def main() -> int: (switch_root / "first.md").write_text("# First\n", encoding="utf-8") (nested_root / "inside.md").write_text("# Inside\n", encoding="utf-8") first_reader = empty_window._reader_from_tab(fixed_reader_host) - first_load_loop = QEventLoop() - if first_reader is not None: - first_reader.loadFinished.connect(first_load_loop.quit) empty_window.open_document(project_root / "sample.md", add_history=False) - QTimer.singleShot(5000, first_load_loop.quit) - first_load_loop.exec() + wait_until( + lambda: first_reader is not None and fixed_reader_host.stack.currentWidget() is first_reader, + timeout_ms=30000, + ) if empty_window.tabs.currentWidget() is not fixed_reader_host: checks.append("first_open_fixed_tab_host") if first_reader is None or fixed_reader_host.stack.currentWidget() is not first_reader: @@ -682,9 +681,7 @@ def main() -> int: window.set_theme_background_from_action(peony_action) if window.theme_background != "peony": checks.append("background_enabled_for_colorful") - toc_refresh_loop = QEventLoop() - QTimer.singleShot(700, toc_refresh_loop.quit) - toc_refresh_loop.exec() + wait_until(lambda: not window.web_view.page().isLoading(), timeout_ms=30000) if not hasattr(window, "manage_external_apps_action"): checks.append("manage_external_apps_action") close_window = MainWindow(project_root=project_root) @@ -724,11 +721,9 @@ def main() -> int: result["scroll_y"] = float(value or 0) except (TypeError, ValueError): result["scroll_y"] = -1 - toc_loop.quit() window.web_view.page().runJavaScript("Math.max(0, window.scrollY || document.documentElement.scrollTop || 0)", store_scroll) - QTimer.singleShot(1000, toc_loop.quit) - toc_loop.exec() + wait_until(lambda: "scroll_y" in result, timeout_ms=30000) if result.get("scroll_y", -1) < 0: checks.append("toc_second_click_scroll") if window.search_index.search("斐波那契") == []: @@ -820,18 +815,11 @@ def main() -> int: pass pdf_test_path = project_root / "__gui_smoke_export.pdf" try: - pdf_loop = QEventLoop() window.export_pdf_to_path(pdf_test_path) - - def poll_pdf_export() -> None: - if pdf_test_path.exists() or getattr(window, "_pdf_export_page", None) is None: - pdf_loop.quit() - return - QTimer.singleShot(100, poll_pdf_export) - - QTimer.singleShot(100, poll_pdf_export) - QTimer.singleShot(15000, pdf_loop.quit) - pdf_loop.exec() + wait_until( + lambda: pdf_test_path.exists() or getattr(window, "_pdf_export_page", None) is None, + timeout_ms=60000, + ) if not pdf_test_path.exists() or pdf_test_path.stat().st_size <= 0: checks.append("export_pdf_write") finally: diff --git a/tests/test_semantic_style_controls.py b/tests/test_semantic_style_controls.py index 2f37ecb..1bf641b 100644 --- a/tests/test_semantic_style_controls.py +++ b/tests/test_semantic_style_controls.py @@ -55,7 +55,7 @@ def test_browser_semantic_styles_and_contextual_character_inheritance(qt_applica page = QWebEnginePage(); loaded = [] page.loadFinished.connect(loaded.append); page.setHtml(content) def wait(condition): - deadline = time.monotonic() + 10 + deadline = time.monotonic() + 30 while not condition() and time.monotonic() < deadline: qt_application.processEvents(); time.sleep(.01) assert condition() try: diff --git a/tests/test_style_regressions.py b/tests/test_style_regressions.py index bc4c118..b45385d 100644 --- a/tests/test_style_regressions.py +++ b/tests/test_style_regressions.py @@ -3,7 +3,7 @@ import time import zipfile from lxml import etree as ET import pytest -from PySide6.QtCore import Qt +from PySide6.QtCore import Qt, QCoreApplication, QEvent from PySide6.QtWebEngineCore import QWebEnginePage from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.docx_style import W, NS, val @@ -37,7 +37,7 @@ def parts(path): def browser(qapp, tmp_path, payload, source, expression): page = QWebEnginePage(); loaded = []; result = [] def wait(predicate): - end = time.monotonic() + 12 + end = time.monotonic() + 30 while not predicate() and time.monotonic() < end: qapp.processEvents(); time.sleep(.01) assert predicate(), 'WebEngine timed out' try: @@ -48,7 +48,10 @@ def browser(qapp, tmp_path, payload, source, expression): page.runJavaScript('JSON.stringify(' + expression + ')', result.append) wait(lambda: result) return json.loads(result[0]) - finally: page.deleteLater(); qapp.processEvents() + finally: + page.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + qapp.processEvents() @pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc']) diff --git a/tests/test_style_revision_052.py b/tests/test_style_revision_052.py index b33dd34..af92013 100644 --- a/tests/test_style_revision_052.py +++ b/tests/test_style_revision_052.py @@ -17,6 +17,8 @@ REPEATED_RULES = {'strong': {'font_color': '#ff0000'}, 'emphasis': {'font_color' ABSOLUTE_PAYLOAD = {'css_sync_version': 1, 'css': '.reader h1 {font-size:20pt;} .reader h2 {text-indent:24pt;}', 'rules': {'_metadata': {'h2': {'based_on': 'h1'}}}} +SCOPED_SOURCE = 'BodyText\n\n> QuoteText\n\n- TightItem\n- TightSecond\n\n---\n\n- LooseItem\n\n- LooseSecond' +SCOPED_CSS = 'p {color:red; font-size:20pt;} blockquote {color:blue;}' def text_run(document, word): @@ -128,3 +130,120 @@ def test_absolute_first_indent_survives_inherited_font_and_gui_roundtrip(qt_appl ind = effective_document(doc, styles).find('.//w:pPr/w:ind', NS) assert ind.get(W + 'firstLine') == '480' and ind.get(W + 'firstLineChars') == '0' finally: dialog.close() + + +@pytest.mark.parametrize('engine', ENGINES) +def test_p_selector_covers_quotes_and_loose_lists_without_changing_tight_lists(qt_application, tmp_path, engine): + payload = normalize_payload({'css': SCOPED_CSS}) + assert payload['rules']['blockquote']['font_color'] == '#ff0000' + dialog = DocumentStyleEditorDialog(payload) + try: + dialog.font_size_spin.setValue(21) + payload = normalize_payload(dialog.style_payload()) + assert payload['rules']['blockquote']['font_size'] == 21 + assert payload['rules']['_list_paragraph']['font_size'] == 21 + finally: dialog.close() + path = export_markdown_to_docx(SCOPED_SOURCE, tmp_path / 'scope.docx', engine=engine, style_rules=payload['rules']) + doc, styles = parts(path) + rendered = effective_document(doc, styles) + for word in ('BodyText', 'QuoteText', 'LooseItem', 'LooseSecond'): + run = text_run(rendered, word) + assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000', (engine, word) + assert run.find('w:rPr/w:sz', NS).get(W + 'val') == '42' + assert text_run(rendered, 'TightItem').find('w:rPr/w:color', NS).get(W + 'val') == 'auto' + for word in ('LooseItem', 'LooseSecond'): + p = next(p for p in doc.iter(W + 'p') if word in ''.join(p.itertext())) + assert p.find('w:pPr/w:numPr', NS) is not None + assert not any('MDHelperSourceListParagraph' in str(s.attrib) for s in styles) + + +def test_reader_p_scope_and_table_paragraph_spacing(qt_application, tmp_path): + payload = normalize_payload({'css': SCOPED_CSS}) + colors = browser(qt_application, tmp_path, payload, SCOPED_SOURCE, + "[...document.querySelectorAll('p,li')].filter(e=>['BodyText','QuoteText','TightItem','LooseItem'].includes(e.textContent.trim())).map(e=>[e.textContent.trim(),getComputedStyle(e).color])") + assert ['BodyText', 'rgb(255, 0, 0)'] in colors and ['QuoteText', 'rgb(255, 0, 0)'] in colors + assert ['LooseItem', 'rgb(255, 0, 0)'] in colors and ['TightItem', 'rgb(35, 39, 47)'] in colors + sizes = [] + for amount in (0, 30): + payload = normalize_payload({'rules': {'table_cell': {'space_before_value': amount, 'space_before_unit': 'pt', + 'space_after_value': amount, 'space_after_unit': 'pt'}}}) + sizes.append(browser(qt_application, tmp_path, payload, '| Header |\n|---|\n| Cell |', + "(()=>{let c=document.querySelector('td'),p=c.querySelector('.mdhelper-cell-paragraph');return [c.getBoundingClientRect().height,p.getBoundingClientRect().top-c.getBoundingClientRect().top]})()")) + assert sizes[1][0] - sizes[0][0] == pytest.approx(80, abs=.1) + assert sizes[1][1] - sizes[0][1] == pytest.approx(40, abs=.1) + + +@pytest.mark.parametrize('engine', ENGINES) +def test_contextual_color_follows_paragraph_and_outer_inline_color(qt_application, tmp_path, engine): + source = 'Body **Colored** [Link](https://example.com)\n\n# Heading **HeadingColor**\n\n**[Nested](https://example.com)**' + css = '.reader p {color:red;} h1 {color:blue;} strong {color:currentColor;} a {color:currentColor;}' + payload = normalize_payload({'css': css}) + assert payload['rules']['strong']['font_color'] == 'inherit' + dialog = DocumentStyleEditorDialog(payload) + try: + dialog.select_target('strong') + assert dialog.color_combo.currentData() == 'inherit' + assert normalize_payload(dialog.style_payload()) == payload + finally: dialog.close() + path = export_markdown_to_docx(source, tmp_path / 'color.docx', engine=engine, style_rules=payload['rules']) + doc, styles = parts(path) + rendered = effective_document(doc, styles) + for word, color in (('Colored', 'ff0000'), ('Link', 'ff0000'), ('Nested', 'ff0000'), ('HeadingColor', '0000ff')): + assert text_run(rendered, word).find('w:rPr/w:color', NS).get(W + 'val') == color + assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:rPr/w:color", NS) is None + + +@pytest.mark.parametrize('invalid', ['font-size:nope', 'font-size:-2pt !important', 'font-size:20wrong', 'color:invalid !important']) +def test_invalid_declaration_keeps_previous_valid_core_value(qt_application, tmp_path, invalid): + css = 'p {font-size:20pt;color:red;' + invalid + ';}' + payload = normalize_payload({'css': css}) + assert payload['rules']['paragraph']['font_size'] == 20 + assert payload['rules']['paragraph']['font_color'] == '#ff0000' + assert payload['css'] == css and analyze_css(css).notes + value = browser(qt_application, tmp_path, payload, 'Text', + "(()=>{const s=getComputedStyle(document.querySelector('p'));return [parseFloat(s.fontSize),s.color]})()") + assert value[0] == pytest.approx(20 * 4/3, abs=.01) and value[1] == 'rgb(255, 0, 0)' + + +@pytest.mark.parametrize('value', ['calc(10pt + 2vw)', '5vw', 'larger', 'var(--size)']) +def test_valid_extended_values_do_not_restore_obsolete_core_values(value): + result = analyze_css('p {font-size:20pt;font-size:' + value + ';color:red;}') + assert 'font_size' not in result.rules['paragraph'] + assert result.notes + + +def test_graphical_quote_override_wins_over_broad_p_rule(qt_application, tmp_path): + dialog = DocumentStyleEditorDialog({'css': SCOPED_CSS}) + try: + dialog.select_target('blockquote') + dialog.color_button.setText('#008800') + dialog._store_and_refresh() + payload = dialog.style_payload() + assert payload['rules']['blockquote']['font_color'] == '#008800' + assert payload['rules']['paragraph']['font_color'] == '#ff0000' + assert browser(qt_application, tmp_path, payload, '> Quote', + "getComputedStyle(document.querySelector('blockquote p')).color") == 'rgb(0, 136, 0)' + finally: dialog.close() + + +@pytest.mark.parametrize('engine', ENGINES) +@pytest.mark.parametrize('colored_base', [False, True]) +def test_contextual_color_preserves_other_resolved_character_fields(tmp_path, engine, colored_base): + rules = {'paragraph': {'font_color': '#ff0000'}, 'emphasis': {'english_font_family': 'Arial'}, + 'strong': {'font_color': 'inherit'}, '_metadata': {'strong': {'based_on': 'emphasis'}}} + if colored_base: rules['emphasis']['font_color'] = '#0000ff' + path = export_markdown_to_docx('**InheritedText**', tmp_path / 'context-base.docx', engine=engine, style_rules=rules) + doc, styles = parts(path) + run = text_run(effective_document(doc, styles), 'InheritedText') + assert run.find('w:rPr/w:color', NS).get(W + 'val') == 'ff0000' + assert run.find('w:rPr/w:rFonts', NS).get(W + 'ascii') == 'Arial' + assert run.find('w:rPr/w:i', NS).get(W + 'val') == '1' + if not colored_base: + assert styles.find("w:style[@w:styleId='MDHelperStrong']/w:basedOn", NS).get(W + 'val') == 'MDHelperEmphasis' + + +def test_invalid_shorthand_does_not_apply_its_valid_components(): + result = analyze_css('p {margin:20pt; margin:3pt nope; font-size:18pt; font:14pt/nope Arial;}') + rule = result.rules['paragraph'] + assert rule['space_before_value'] == rule['space_after_value'] == rule['left_indent_value'] == rule['right_indent_value'] == 20 + assert rule['font_size'] == 18 diff --git a/tests/word_styles_smoke.ps1 b/tests/word_styles_smoke.ps1 index 426a447..2672508 100644 --- a/tests/word_styles_smoke.ps1 +++ b/tests/word_styles_smoke.ps1 @@ -12,7 +12,7 @@ from test_word_named_styles import SOURCE from mdhelper.docx_exporter import export_markdown_to_docx from mdhelper.style_catalog import style_name from test_style_regressions import PARTIAL_RULES, UNIT_RULES, NESTED_SOURCE, NESTED_RULES -from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD +from test_style_revision_052 import REPEATED_SOURCE, REPEATED_RULES, ABSOLUTE_PAYLOAD, SCOPED_SOURCE, SCOPED_CSS from mdhelper.style_sync import normalize_payload folder = Path(tempfile.mkdtemp(prefix='MDHelper-Word-Styles-')) rules = {'h2': {'bold': False}, '_metadata': {'h2': {'based_on': 'h1'}}} @@ -25,6 +25,11 @@ for engine in ('builtin', 'python-docx', 'pandoc'): export_markdown_to_docx('- OuterList\n - InnerList', folder / (engine + '-list.docx'), engine=engine) export_markdown_to_docx('## Indented', folder / (engine + '-absolute.docx'), engine=engine, style_rules=normalize_payload(ABSOLUTE_PAYLOAD)['rules']) export_markdown_to_docx('BookText', folder / (engine + '-preset.docx'), engine=engine, style_rules={'_preset': 'serif'}, preset='custom:copy') + export_markdown_to_docx(SCOPED_SOURCE, folder / (engine + '-scope.docx'), engine=engine, style_rules=normalize_payload({'css': SCOPED_CSS})['rules']) + export_markdown_to_docx('Body **ContextColor** [ContextLink](https://example.com)', folder / (engine + '-context.docx'), engine=engine, + style_rules=normalize_payload({'css': 'p {color:red;} strong,a {color:currentColor;}'})['rules']) + export_markdown_to_docx('ValidValue', folder / (engine + '-fallback.docx'), engine=engine, + style_rules=normalize_payload({'css': 'p {font-size:20pt;font-size:nope;color:red;color:invalid;}'})['rules']) (folder / 'names.json').write_text(json.dumps({key: 'MDHelper ' + style_name(key) for key in ('paragraph', 'strong', 'link', 'h1')}), encoding='utf-8') print(folder) '@ | & $Python -B -).Trim() @@ -109,6 +114,23 @@ print(folder) } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } } Write-Output "$engine passed: repeated inline styles, nested list edits, absolute indents and copied presets." + foreach ($case in @('scope', 'context', 'fallback')) { + $doc = $word.Documents.Open((Join-Path $testDirectory "$engine-$case.docx"), $false, $true) + try { + $texts = switch ($case) { 'scope' { @('BodyText', 'QuoteText', 'LooseItem', 'LooseSecond') }; 'context' { @('ContextColor', 'ContextLink') }; 'fallback' { @('ValidValue') } } + foreach ($text in $texts) { + $range = $doc.Content.Duplicate + if (-not $range.Find.Execute($text)) { throw "Missing $text" } + if ($range.Font.Color -ne 255) { throw "$engine lost $case color for $text." } + if ($case -ne 'context' -and $range.Font.Size -ne 20) { throw "$engine lost $case font size." } + } + if ($case -eq 'scope') { + $range = $doc.Content.Duplicate; [void]$range.Find.Execute('TightItem') + if ($range.Font.Color -eq 255) { throw "$engine applied paragraph CSS to tight list." } + } + } finally { $doc.Close(0); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($doc) } + } + Write-Output "$engine passed: paragraph selector scope, contextual colors and invalid-value fallback." } } finally { if ($word) { $word.Quit(); [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word) }