fix: repair Chinese PDF text and sync native component selection
This commit is contained in:
1 parent
734a10b5c7
commit
12ce0c4140
23 files changed
+988
-5
No files matched your search
@@ -0,0 +1,103 @@
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
from pypdf.generic import ArrayObject, ByteStringObject, ContentStream, DictionaryObject, FloatObject, NameObject, NumberObject
|
||||
|
||||
from dx_productivity.features.pdf_export import exporter
|
||||
from dx_productivity.features.pdf_export.models import ExportScope, PdfExportSettings
|
||||
|
||||
|
||||
def legacy_pdf(path, text='输入网络 输出网络 Ω μ ± ×', *, raw=None, compound=False):
|
||||
writer = PdfWriter()
|
||||
page = writer.add_blank_page(640, 240)
|
||||
font = DictionaryObject({NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type1'),
|
||||
NameObject('/BaseFont'): NameObject('/Courier'), NameObject('/Encoding'): NameObject('/WinAnsiEncoding')})
|
||||
page[NameObject('/Resources')] = DictionaryObject({NameObject('/Font'): DictionaryObject({NameObject('/F1'): writer._add_object(font)})})
|
||||
stream = ContentStream(None, writer)
|
||||
value = ByteStringObject(raw if raw is not None else text.encode('gbk'))
|
||||
stream.operations = [([NumberObject(1), NumberObject(0), NumberObject(0)], b'RG'),
|
||||
([NumberObject(10), NumberObject(20)], b'm'), ([NumberObject(600), NumberObject(20)], b'l'), ([], b'S'),
|
||||
([], b'BT'), ([NameObject('/F1'), NumberObject(14)], b'Tf'),
|
||||
([FloatObject(80)], b'Tz'), ([NumberObject(20), NumberObject(120)], b'Td'),
|
||||
([ArrayObject([value])], b'TJ') if compound else ([value], b'Tj'), ([], b'ET')]
|
||||
page[NameObject('/Contents')] = writer._add_object(stream)
|
||||
writer.add_outline_item('Main Sheet Analog', 0)
|
||||
with Path(path).open('wb') as output:
|
||||
writer.write(output)
|
||||
|
||||
|
||||
def test_chinese_repair_embeds_unicode_and_keeps_native_vectors_and_bookmark(tmp_path):
|
||||
from dx_productivity.features.pdf_export.text_repair import repair_text
|
||||
file = tmp_path / 'native.pdf'
|
||||
legacy_pdf(file)
|
||||
before = PdfReader(file)
|
||||
geometry = [(a, o) for a, o in ContentStream(before.pages[0].get_contents(), before).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
|
||||
result = repair_text(file, 'chinese', threading.Event())
|
||||
after = PdfReader(file, strict=True)
|
||||
assert '输入网络 输出网络 Ω μ ± ×' in after.pages[0].extract_text()
|
||||
assert after.outline[0].title == 'Main Sheet Analog'
|
||||
assert geometry == [(a, o) for a, o in ContentStream(after.pages[0].get_contents(), after).operations if o in (b'RG', b'rg', b'm', b'l', b'S', b'Td')]
|
||||
assert list(before.pages[0].mediabox) == list(after.pages[0].mediabox)
|
||||
assert result['repaired_strings'] == 1
|
||||
for font in after.pages[0]['/Resources']['/Font'].values():
|
||||
font = font.get_object()
|
||||
if font.get('/Subtype') == '/Type0':
|
||||
assert font['/ToUnicode'].get_data()
|
||||
assert font['/DescendantFonts'][0]['/FontDescriptor']['/FontFile2'].get_data()
|
||||
|
||||
|
||||
def test_western_mode_keeps_engineering_symbols_without_gbk_guess(tmp_path):
|
||||
from dx_productivity.features.pdf_export.text_repair import repair_text
|
||||
file = tmp_path / 'symbols.pdf'
|
||||
legacy_pdf(file, raw='±× µ± ÉÉ'.encode('cp1252'))
|
||||
repair_text(file, 'western', threading.Event())
|
||||
assert '±× µ± ÉÉ' in PdfReader(file).pages[0].extract_text()
|
||||
|
||||
|
||||
def test_unsupported_text_and_cancellation_preserve_staging_bytes(tmp_path):
|
||||
from dx_productivity.features.pdf_export.text_repair import repair_text
|
||||
file = tmp_path / 'compound.pdf'
|
||||
legacy_pdf(file, compound=True)
|
||||
before = file.read_bytes()
|
||||
with pytest.raises(ValueError, match='TJ'):
|
||||
repair_text(file, 'chinese', threading.Event())
|
||||
assert file.read_bytes() == before
|
||||
cancel = threading.Event()
|
||||
cancel.set()
|
||||
with pytest.raises(InterruptedError):
|
||||
repair_text(file, 'chinese', cancel)
|
||||
assert file.read_bytes() == before
|
||||
|
||||
|
||||
def test_native_mode_preserves_bytes_and_uses_original_mapping(tmp_path):
|
||||
from dx_productivity.features.pdf_export.text_repair import repair_text
|
||||
file = tmp_path / 'native.pdf'
|
||||
legacy_pdf(file)
|
||||
before = file.read_bytes()
|
||||
repair_text(file, 'original', threading.Event())
|
||||
assert file.read_bytes() == before
|
||||
assert '-udx' not in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT)
|
||||
assert '-udx' in exporter.build_command(Path('sch2pdf.exe'), Path('Demo.prj'), file, ExportScope.PROJECT, text_mode='original')
|
||||
|
||||
|
||||
def test_exporter_repairs_text_before_publishing(tmp_path, monkeypatch):
|
||||
source = tmp_path / 'source'
|
||||
(source / 'database').mkdir(parents=True)
|
||||
project = source / 'Demo.prj'
|
||||
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir ".\\database"\n')
|
||||
engine = tmp_path / 'sch2pdf.exe'
|
||||
engine.touch()
|
||||
settings = PdfExportSettings(project, ExportScope.CURRENT_PAGE, 'Main', tmp_path / 'output', engine_path=engine)
|
||||
|
||||
def native(command, *_args, **_kwargs):
|
||||
assert '-udx' not in command
|
||||
legacy_pdf(Path(command[command.index('-a') + 1]))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(exporter, 'run_engine', native)
|
||||
result = exporter.export_project(settings, threading.Event(), active_block_name='Main', active_sheet_name='Analog', local_app_data=tmp_path / 'state')
|
||||
assert result.state == 'success', result.message
|
||||
assert '输入网络' in PdfReader(result.output_path).pages[0].extract_text()
|
||||
assert (result.run_dir / 'text-check.json').is_file()
|
||||
@@ -0,0 +1,88 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from dx_productivity.ui.app import create_main_window
|
||||
|
||||
|
||||
def setup_window(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
monkeypatch.setenv('LOCALAPPDATA', str(tmp_path / 'local'))
|
||||
data = json.loads((fixture_path / 'request-basic.json').read_text(encoding='utf-8'))
|
||||
data.update(active_block_name='ROOT', current_sheet_number=1, current_sheet_name='1')
|
||||
for component in data['components']:
|
||||
component['attributes'] = [{'name': 'Value', 'value': component['value'], 'visible': True}]
|
||||
request = tmp_path / 'request.json'
|
||||
request.write_text(json.dumps(data), encoding='utf-8')
|
||||
window = create_main_window(request)
|
||||
qtbot.addWidget(window)
|
||||
return window, data
|
||||
|
||||
|
||||
def publish(tmp_path, data, keys, *, snapshot_id=None, design_path=None, sheet='1', current_keys=None):
|
||||
payload = {'state': 'ready', 'run_id': data['run_id'], 'snapshot_id': snapshot_id or data['snapshot_id'],
|
||||
'design_path': design_path or data['design_path'], 'active_block_name': 'ROOT',
|
||||
'current_sheet_number': int(sheet), 'current_sheet_name': sheet,
|
||||
'selected_keys': keys, 'current_sheet_keys': current_keys or ['uid:uid-r-a', 'uid:uid-c-a'], 'selected_nets': []}
|
||||
(tmp_path / 'selection.json').write_text(json.dumps(payload), encoding='utf-8')
|
||||
|
||||
|
||||
def test_selection_updates_all_feature_scopes_and_reports_clicked_refdes(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
|
||||
publish(tmp_path, data, ['uid:uid-c-a'])
|
||||
window.selection_watcher._check()
|
||||
for controller in (window.refdes_controller, window.property_change_controller,
|
||||
window.property_visibility_controller, window.bom_controller, window.pdf_export_controller):
|
||||
assert [c.refdes for c in controller.snapshot.components if c.selected] == ['C1']
|
||||
assert controller.snapshot.snapshot_id == data['snapshot_id']
|
||||
assert 'C1' in window.selection_status.text()
|
||||
assert window.property_change_controller.page.model.item(0, 0).text() == 'C1'
|
||||
assert 'R?' not in window.selection_status.text()
|
||||
publish(tmp_path, data, [])
|
||||
window.selection_watcher._check()
|
||||
assert not any(c.selected for c in window.refdes_controller.snapshot.components)
|
||||
assert '0' in window.selection_status.text()
|
||||
|
||||
|
||||
def test_selection_preserves_retained_property_edits_and_pending_pdf_form(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
|
||||
page = window.property_change_controller.page
|
||||
page.model.item(0, 2).setText('user pending value')
|
||||
pdf = window.pdf_export_controller.page
|
||||
pdf.output_input.setText('user pending PDF folder')
|
||||
publish(tmp_path, data, ['uid:uid-r-a', 'uid:uid-c-a'])
|
||||
window.selection_watcher._check()
|
||||
assert page.model.item(0, 2).text() == 'user pending value'
|
||||
assert page.model.item(1, 2).text() == '100nF'
|
||||
assert pdf.output_input.text() == 'user pending PDF folder'
|
||||
|
||||
|
||||
def test_selection_rejects_old_snapshot_and_other_project(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
|
||||
original = window.refdes_controller.snapshot
|
||||
for kwargs in ({'snapshot_id': 'stale'}, {'design_path': 'C:/other.prj'}):
|
||||
publish(tmp_path, data, ['uid:uid-c-a'], **kwargs)
|
||||
window.selection_watcher._check()
|
||||
assert window.refdes_controller.snapshot is original
|
||||
|
||||
|
||||
def test_selection_is_deferred_during_apply_then_consumed(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
|
||||
original = window.refdes_controller.snapshot
|
||||
window.refdes_controller._apply_in_flight = True
|
||||
publish(tmp_path, data, ['uid:uid-c-a'])
|
||||
window.selection_watcher._check()
|
||||
assert window.refdes_controller.snapshot is original
|
||||
window.refdes_controller._apply_in_flight = False
|
||||
window.selection_watcher._check()
|
||||
assert [c.refdes for c in window.refdes_controller.snapshot.components if c.selected] == ['C1']
|
||||
|
||||
|
||||
def test_selection_switches_current_sheet_without_overwriting_form(qtbot, fixture_path, tmp_path, monkeypatch):
|
||||
window, data = setup_window(qtbot, fixture_path, tmp_path, monkeypatch)
|
||||
publish(tmp_path, data, [], sheet='2', current_keys=[])
|
||||
# An empty current page must clear the old page's component scope.
|
||||
payload = json.loads((tmp_path / 'selection.json').read_text(encoding='utf-8'))
|
||||
payload['current_sheet_keys'] = []
|
||||
(tmp_path / 'selection.json').write_text(json.dumps(payload), encoding='utf-8')
|
||||
window.selection_watcher._check()
|
||||
assert window.pdf_export_controller.snapshot.current_sheet_name == '2'
|
||||
assert not any(c.current_sheet for c in window.bom_controller.snapshot.components)
|
||||
Reference in new issue
Block a user