fix: align contextual CSS rendering and Word styles

This commit is contained in:
2026-10-30 13:12:05 +08:00
parent cc4f91899e
commit f9bf62b71c
17 changed files with 313 additions and 53 deletions
+10
View File
@@ -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()
+10 -22
View File
@@ -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:
+1 -1
View File
@@ -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:
+6 -3
View File
@@ -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'])
+119
View File
@@ -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
+23 -1
View File
@@ -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) }