fix: preserve nested Word structures and synchronize valid font families
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
"""Multiword font family names may contain words that are reserved alone."""
|
||||
import pytest
|
||||
from mdhelper.style_sync import normalize_payload, analyze_css
|
||||
from mdhelper.style_dialog import DocumentStyleEditorDialog
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_style import W, NS
|
||||
from test_style_regressions import browser, parts
|
||||
from docx_assertions import effective_document
|
||||
|
||||
|
||||
@pytest.mark.parametrize('family', ['Initial Font', 'Default Sans', 'Inherit Serif', 'Unset Sans', 'Revert Layer'])
|
||||
def test_valid_family_syncs_browser_and_graphical_controls(qt_application, tmp_path, family):
|
||||
css = f'p{{font:italic 20pt {family}}}'
|
||||
payload = normalize_payload({'css':css})
|
||||
assert not analyze_css(css).notes
|
||||
assert payload['rules']['paragraph']['english_font_family'] == family
|
||||
result = browser(qt_application, tmp_path, payload, 'Text', "(()=>{const s=getComputedStyle(document.querySelector('p'));return [parseFloat(s.fontSize),s.fontStyle]})()")
|
||||
assert result[0] == pytest.approx(20*4/3, abs=.01) and result[1] == 'italic'
|
||||
dialog = DocumentStyleEditorDialog(payload)
|
||||
try:
|
||||
assert dialog.font_size_spin.value() == 20
|
||||
dialog.font_size_spin.setValue(22)
|
||||
rule = analyze_css(dialog.style_payload()['css']).rules['paragraph']
|
||||
assert rule['font_size'] == 22 and rule['english_font_family'] == family and rule['italic']
|
||||
dialog.extra_css_edit.setPlainText(css)
|
||||
assert dialog.style_payload()['rules']['paragraph']['font_size'] == 20
|
||||
assert dialog.font_size_spin.value() == 20
|
||||
finally: dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ['builtin', 'python-docx', 'pandoc'])
|
||||
def test_valid_family_exports_editable_size_and_italic(tmp_path, engine):
|
||||
rules = normalize_payload({'css':'p{font:italic 20pt Initial Font}'})['rules']
|
||||
doc, styles = parts(export_markdown_to_docx('Text', tmp_path/'font.docx', engine=engine, style_rules=rules))
|
||||
base = styles.find("w:style[@w:styleId='MDHelperParagraph']/w:rPr", NS)
|
||||
assert base.find(W+'sz').get(W+'val') == '40'
|
||||
assert base.find(W+'i').get(W+'val') == '1'
|
||||
base.find(W+'sz').set(W+'val', '48')
|
||||
assert effective_document(doc, styles).find('.//w:r/w:rPr/w:sz', NS).get(W+'val') == '48'
|
||||
@@ -106,9 +106,9 @@ def test_word_preserves_all_settings_and_content(tmp_path: Path, engine):
|
||||
assert spacing.get(W + "before") == spacing.get(W + "after") == "0"
|
||||
assert spacing.get(W + "line") == "400" and spacing.get(W + "lineRule") == "exact"
|
||||
ind = ppr.find(W + "ind")
|
||||
# List geometry uses absolute lengths so Word's document grid cannot
|
||||
# shift code/heading continuations away from their list's text column.
|
||||
assert ind.get(W + "firstLineChars") == ("0" if ppr.find(W + 'numPr') is not None else "200")
|
||||
# List/quote geometry uses absolute lengths, independent of Word's grid.
|
||||
absolute = ppr.find(W + 'numPr') is not None or ''.join(p.itertext()).startswith('Quote')
|
||||
assert ind.get(W + "firstLineChars") == ("0" if absolute else "200")
|
||||
assert ind.get(W + "firstLine") == "420" and ind.get(W + "right") == "120"
|
||||
assert ind.get(W + "left") == "850"
|
||||
for name, value in (("keepNext", "1"), ("keepLines", "1"), ("contextualSpacing", "1"), ("pageBreakBefore", "0"), ("widowControl", "0")):
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Empty and invalid directory history must not resolve to the working folder."""
|
||||
from unittest.mock import MagicMock
|
||||
import pytest
|
||||
from PySide6.QtCore import QSettings
|
||||
from mdhelper import app
|
||||
|
||||
|
||||
@pytest.mark.parametrize('history', [None, '', ' ', 'missing', 'file', 'directory'])
|
||||
def test_startup_history_requires_a_nonempty_directory(tmp_path, monkeypatch, history):
|
||||
settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat)
|
||||
folder = tmp_path/'project'; folder.mkdir()
|
||||
file = folder/'note.md'; file.write_text('Text')
|
||||
value = {'missing': str(tmp_path/'missing'), 'file': str(file), 'directory': str(folder)}.get(history, history)
|
||||
if value is not None: settings.setValue('project/last_root', value)
|
||||
window = MagicMock()
|
||||
monkeypatch.setattr(app, 'QSettings', lambda *_: settings)
|
||||
monkeypatch.setattr(app, 'QApplication', MagicMock())
|
||||
monkeypatch.setattr(app, 'MainWindow', window)
|
||||
monkeypatch.setattr(app, 'configure_process_runtime', lambda *_: None)
|
||||
monkeypatch.setattr(app, 'setup_logging', lambda *_: None)
|
||||
app.main([])
|
||||
args = window.call_args.kwargs
|
||||
assert args['project_root'] == (folder if history == 'directory' else None)
|
||||
assert args['prompt_for_project'] == (history != 'directory')
|
||||
assert args['initial_path'] is None
|
||||
# Explicit startup files still take precedence over all history values.
|
||||
app.main([str(file)])
|
||||
assert window.call_args.kwargs['project_root'] == folder
|
||||
assert window.call_args.kwargs['initial_path'] == file
|
||||
@@ -93,7 +93,8 @@ def test_quoted_list_keeps_additive_nested_indents(tmp_path, engine):
|
||||
text=''.join(p.itertext())
|
||||
if text in ('Outer','Inner'):
|
||||
ind=p.find('w:pPr/w:ind',NS)
|
||||
assert int(ind.get(W+'left'))/20 == (36 if text=='Outer' else 72)
|
||||
# Include the quote container's 12 pt padding and 3 pt border.
|
||||
assert int(ind.get(W+'left'))/20 == (51 if text=='Outer' else 87)
|
||||
assert ind.get(W+'hangingChars','0')=='0'
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Nested list markers and quote containers remain shared, editable Word styles."""
|
||||
import pytest
|
||||
from mdhelper.docx_exporter import export_markdown_to_docx
|
||||
from mdhelper.docx_style import W, NS
|
||||
from test_style_regressions import parts
|
||||
from docx_assertions import effective_document
|
||||
|
||||
ENGINES = ['builtin', 'python-docx', 'pandoc']
|
||||
NESTED_TABLE = '1. Outer\n - | HeadOne | HeadTwo |\n |---|---|\n | CellOne | CellTwo |\n\n2. End'
|
||||
QUOTE_TABLE = '1. > | HeadOne | HeadTwo |\n > |---|---|\n > | CellOne | CellTwo |\n\n2. End'
|
||||
NESTED_FIRST = '1. - FirstChild\n - SecondChild\n\n2. End'
|
||||
QUOTE_TEXT = '> OuterText\n>\n> > InnerText\n> >\n> > ### InnerHeading\n> >\n> > ```text\n> > InnerCode\n> > ```'
|
||||
MIXED_QUOTE = '1. Outer\n\n > - Inner\n >\n > Continued\n >\n > ### Heading\n >\n > ```text\n > CodeLine\n > ```\n\n2. End'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
@pytest.mark.parametrize('source', [NESTED_TABLE, QUOTE_TABLE, NESTED_FIRST])
|
||||
def test_nested_blocks_keep_parent_marker_and_content(tmp_path, engine, source):
|
||||
doc, styles = parts(export_markdown_to_docx(source, tmp_path/'nested.docx', engine=engine))
|
||||
paragraphs = doc.findall('w:body/w:p', NS)
|
||||
first, last = paragraphs[0], paragraphs[-1]
|
||||
assert first.find('w:pPr/w:numPr', NS) is not None
|
||||
assert first.find('w:pPr/w:numPr/w:numId', NS).get(W+'val') == last.find('w:pPr/w:numPr/w:numId', NS).get(W+'val')
|
||||
assert 'H2' not in first.find('w:pPr/w:pStyle', NS).get(W+'val')
|
||||
if 'HeadOne' in source:
|
||||
assert [''.join(c.itertext()) for c in doc.findall('.//w:tbl/w:tr/w:tc', NS)] == ['HeadOne','HeadTwo','CellOne','CellTwo']
|
||||
assert '\u200b' not in ''.join(doc.itertext())
|
||||
assert not any(a.startswith('{urn:mdhelper:source}') for el in doc.iter() for a in el.attrib)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_parent_text_after_nested_list_is_a_continuation(tmp_path, engine):
|
||||
source = NESTED_FIRST.replace('\n\n2. End', '\n\n Continued\n\n2. End')
|
||||
doc, _ = parts(export_markdown_to_docx(source, tmp_path/'continued.docx', engine=engine))
|
||||
p = next(p for p in doc.iter(W+'p') if ''.join(p.itertext()) == 'Continued')
|
||||
assert p.find('w:pPr/w:numPr', NS) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_nested_quote_text_keeps_depth_and_base_font_inheritance(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(QUOTE_TEXT, tmp_path/'quote.docx', engine=engine))
|
||||
effective = effective_document(doc, styles)
|
||||
def left(text):
|
||||
p = next(p for p in effective.iter(W+'p') if ''.join(p.itertext()) == text)
|
||||
return int(p.find('w:pPr/w:ind', NS).get(W+'left'))
|
||||
assert left('InnerText') - left('OuterText') == 300
|
||||
styles.find("w:style[@w:styleId='MDHelperBlockquote']/w:rPr/w:color", NS).set(W+'val','008000')
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
if ''.join(p.itertext()) in ('OuterText', 'InnerText'):
|
||||
assert p.find('.//w:rPr/w:color',NS).get(W+'val') == '008000'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
def test_mixed_quote_containers_align_text_headings_and_code(tmp_path, engine):
|
||||
doc, styles = parts(export_markdown_to_docx(MIXED_QUOTE, tmp_path/'mixed.docx', engine=engine))
|
||||
positions = []
|
||||
for p in effective_document(doc,styles).iter(W+'p'):
|
||||
if ''.join(p.itertext()) in ('Inner','Continued','Heading','CodeLine'):
|
||||
positions.append(int(p.find('w:pPr/w:ind',NS).get(W+'left')))
|
||||
assert positions == [1500]*4
|
||||
|
||||
|
||||
@pytest.mark.parametrize('engine', ENGINES)
|
||||
@pytest.mark.parametrize('depth', [1, 2])
|
||||
def test_quoted_tables_preserve_container_depth(tmp_path, engine, depth):
|
||||
source = '\n'.join('> '*depth+line for line in ['| Head |','|---|','| Cell |'])
|
||||
doc, _ = parts(export_markdown_to_docx(source, tmp_path/'table.docx', engine=engine))
|
||||
assert doc.find('.//w:tblPr/w:tblInd', NS).get(W+'w') == str(round(depth*300 + 12*.76*20))
|
||||
@@ -45,7 +45,7 @@ print(folder)
|
||||
if($text -eq 'Continuation' -and $range.ListFormat.ListString.Trim() -ne ''){throw "$engine continuation consumed a marker"}
|
||||
}
|
||||
} elseif($case -eq 'quoted') {
|
||||
foreach($pair in @(@('Outer',36),@('Inner',72))) {
|
||||
foreach($pair in @(@('Outer',51),@('Inner',87))) {
|
||||
$range=$doc.Content.Duplicate;[void]$range.Find.Execute($pair[0])
|
||||
if([Math]::Abs($range.ParagraphFormat.LeftIndent-$pair[1]) -gt 0.1){throw "$engine quoted $($pair[0]) indent: $($range.ParagraphFormat.LeftIndent)"}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
param([string]$Python = (Join-Path $PSScriptRoot '..\mdhelper_env\mdhelper_env\Scripts\python.exe'))
|
||||
$ErrorActionPreference='Stop'
|
||||
Push-Location (Join-Path $PSScriptRoot '..')
|
||||
$word=$null
|
||||
try {
|
||||
$folder = (@'
|
||||
import sys,tempfile
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path('tests').resolve()))
|
||||
from test_style_revision_058 import *
|
||||
from mdhelper.style_sync import normalize_payload
|
||||
folder=Path(tempfile.mkdtemp(prefix='MDHelper-058-Word-'))
|
||||
for engine in ENGINES:
|
||||
for name,source in [('nested-table',NESTED_TABLE),('quote-table',QUOTE_TABLE),('nested-first',NESTED_FIRST),('quote-text',QUOTE_TEXT),('mixed',MIXED_QUOTE)]:
|
||||
export_markdown_to_docx(source,folder/f'{engine}-{name}.docx',engine=engine)
|
||||
for depth in range(3):
|
||||
source='\n'.join('> '*depth+line for line in ['| Head |','|---|','| Cell |'])
|
||||
export_markdown_to_docx(source,folder/f'{engine}-table-{depth}.docx',engine=engine)
|
||||
rules=normalize_payload({'css':'p{font:italic 20pt Initial Font}'})['rules']
|
||||
export_markdown_to_docx('Text',folder/f'{engine}-font.docx',engine=engine,style_rules=rules)
|
||||
print(folder)
|
||||
'@ | & $Python -B -).Trim()
|
||||
if($LASTEXITCODE -ne 0){throw 'Fixture generation failed'}
|
||||
$word=New-Object -ComObject Word.Application
|
||||
$word.Visible=$false;$word.DisplayAlerts=0
|
||||
foreach($engine in @('builtin','python-docx','pandoc')) {
|
||||
foreach($case in @('nested-table','quote-table','nested-first','quote-text','mixed','table-0','table-1','table-2','font')) {
|
||||
$doc=$word.Documents.Open((Join-Path $folder "$engine-$case.docx"),$false,$true,$false)
|
||||
try {
|
||||
if($case -in @('nested-table','quote-table','nested-first')) {
|
||||
if($doc.Paragraphs.Item(1).Range.ListFormat.ListString.Trim() -ne '1.'){throw "$engine $case parent number missing"}
|
||||
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('End')
|
||||
if($r.ListFormat.ListString.Trim() -ne '2.'){throw "$engine $case next number wrong"}
|
||||
if($case -eq 'nested-table') {
|
||||
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('Outer')
|
||||
if($r.Style.NameLocal -match '标题|Heading'){throw "$engine parent became a heading"}
|
||||
}
|
||||
} elseif($case -eq 'font') {
|
||||
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('Text')
|
||||
if($r.Font.Size -ne 20 -or $r.Font.Italic -ne -1){throw "$engine font CSS lost"}
|
||||
$doc.Styles.Item('MDHelper 正文').Font.Size=24
|
||||
if($r.Font.Size -ne 24){throw "$engine font no longer follows paragraph style"}
|
||||
} else {
|
||||
$doc.ExportAsFixedFormat((Join-Path $folder "$engine-$case.pdf"),17)
|
||||
if($case -eq 'quote-text') {
|
||||
$doc.Styles.Item('MDHelper 引用').Font.Color=255
|
||||
foreach($text in @('OuterText','InnerText')) {
|
||||
$r=$doc.Content.Duplicate;[void]$r.Find.Execute($text)
|
||||
if($r.Font.Color -ne 255){throw "$engine nested quote lost base inheritance"}
|
||||
}
|
||||
} elseif($case -eq 'mixed') {
|
||||
$doc.Styles.Item('MDHelper 标题 3').Font.Size=20
|
||||
$r=$doc.Content.Duplicate;[void]$r.Find.Execute('Heading')
|
||||
if($r.Font.Size -ne 20){throw "$engine nested heading lost base inheritance"}
|
||||
}
|
||||
}
|
||||
Write-Output "$engine $case PASS"
|
||||
} finally {$doc.Close(0)}
|
||||
}
|
||||
}
|
||||
@'
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from pypdf import PdfReader
|
||||
folder=Path(sys.argv[1])
|
||||
def positions(name):
|
||||
result={}
|
||||
def visit(text,cm,tm,font,size):
|
||||
if text.strip():result[text.strip()]=tm[4]*cm[0]+tm[5]*cm[2]+cm[4]
|
||||
for page in PdfReader(folder/name).pages:page.extract_text(visitor_text=visit)
|
||||
return result
|
||||
for engine in ('builtin','python-docx','pandoc'):
|
||||
quote=positions(f'{engine}-quote-text.pdf')
|
||||
assert abs(quote['InnerText']-quote['OuterText']-15)<.3,(engine,quote)
|
||||
mixed=positions(f'{engine}-mixed.pdf')
|
||||
values=[mixed[x] for x in ('Inner','Continued','Heading','CodeLine')]
|
||||
assert max(values)-min(values)<.3,(engine,mixed)
|
||||
tables=[positions(f'{engine}-table-{d}.pdf')['Head'] for d in range(3)]
|
||||
assert all(abs(tables[d]-tables[d-1]-15)<.3 for d in (1,2)),(engine,tables)
|
||||
print(engine,'actual Word quote/table layout PASS')
|
||||
'@ | & $Python -B - $folder
|
||||
if($LASTEXITCODE -ne 0){throw 'Word PDF layout failed'}
|
||||
Write-Output "Fixtures: $folder"
|
||||
} finally {
|
||||
if($word){$word.Quit();[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($word)}
|
||||
Pop-Location
|
||||
}
|
||||
Reference in New Issue
Block a user