fix: repair Chinese PDF text and sync native component selection

This commit is contained in:
阿白叔 committed 2026-10-11 10:53:02 +08:00
1 parent 734a10b5c7
commit 12ce0c4140
23 files changed
+988 -5

No files matched your search

@@ -0,0 +1,40 @@
# 中文 PDF 与实时器件选择验收(2026-10-11)
## 修复与验证
| 项目 | 验证结果 |
|---|---|
| 中文根因 | 原生 WinAnsi 字体保存 GBK 字节;旧 `-udx` 还会将部分错误字符绘制为笔画,单纯替换字体无法恢复 |
| 正式导出 | 默认中文兼容模式关闭旧笔画映射,按 GBK 解码,嵌入 Arial / 宋体子集、CIDToGIDMap 和 ToUnicode;原生色彩、矢量图形与文字推进量保持 |
| 1GPHY | 原生副本实际出图,411 段文字转换、25 段中文恢复、2 个字体子集;“输入网络”“输出网络”“靠近CPU放置”“电源输入3V3”显示及提取正常 |
| 冻结 exe | PATH 不含 Python、保留 Mentor 运行库;exe 实际生成中文 PDF,重新打开提取及 Poppler 渲染通过 |
| Audio / PON PDF | Audio 整工程 1 页;PON 当前页 1 页、指定 Block 17 页、整工程 24 页;中文处理完成后再发布 |
| 颜色 | Audio 的 RGB 绘图颜色及出现次数与原工具参考模式一致;文字修复不重绘图形,不改变颜色 |
| 选择根因 | 旧版只在初次快照和手动刷新时读取 selected;打开后点击器件不会更新工具 |
| 原生选择 | 1GPHY 独立实例单选 CE17、改选 LE03、多选、取消选择和收起状态下的选择均同步,无需手动刷新;测试含脚本启动与 UI 自动化共 1.28—1.91 秒 |
| 选择范围 | 位号、属性、可见性和 BOM 的选中范围随原生选择更新;底部显示数量和位号,提示中显示完整名单及当前页 |
| 输入及事务 | 保留仍选中器件的新属性输入和 PDF 表单;应用与恢复进行时暂缓消费选择,结束后读取最新状态;旧快照和其他工程的选择消息拒绝 |
| 运行中的工具 | 旧 GUI 正常退出,新版 GUI PID 43192 从用户宿主 PID 44008 的 PDF 菜单打开;Start 持久入口指向新版,实际显示当前选择 CE18,属性页内容匹配 |
| 当前工程 GUI 出图 | 使用新版 GUI 实际重新导出当前 1GPHY 工程,确认中文显示和提取正常;旧乱码 PDF 先备份为 previous-user-garbled.pdf;详细记录 current-user-pdf-acceptance.json |
| 源码 | 420 passed,build/test-evidence/text-selection-source.xml |
| 便携包 | 16 passed,build/test-evidence/text-selection-packaged.xml |
证据根目录:`%LOCALAPPDATA%/DxProductivity/acceptance/pdf-text-selection-20261011`。
- `source-text-acceptance.json`、`frozen-text-acceptance.json` 和对应 PDF。
- `pdf-scopes/palette-acceptance.json` 和三种范围的输出。
- `live-selection/live-selection-acceptance.json`,五个原生选择用例。
- `latest-package-ui.json`、`current-live-ui.png`,新版菜单、配色、输出目录和当前选择。
- `current-user-pdf-acceptance.json`,当前工程重新导出的结果及旧 PDF 备份。
## 发布包
- 目录:`release/一叶知秋_重构版_中文PDF与实时选择版`。
- ZIP:目录名后增加 `_Win11_x64.zip`。
- ZIP SHA-256:`bc8ecca30ca67259badc4a4f8ff43009010477dd60337fa28b60a33f90c59d99`。
## 已知边界
本次源码及打包后的中文恢复通过 1GPHY、Audio 和 PON PDF 验证。中文兼容模式针对 GBK;西文工程需选择西文兼容,原生字体不修复编码。未支持的复合文字、Form 旧编码文字或无法取得可靠字宽时,导出失败并保留旧文件。工程自身的文字重叠、长行超出图框未做重排。
PON 的 PDF 引擎导出三种范围通过,但同一副本从工具菜单生成完整设计快照时,在原生 DesignComponents 枚举阶段阻塞,无法完成整条 GUI 切页验收。测试实例 PID 80668 不响应关闭请求后已结束;当时执行只读快照,没有设计值写回,用户宿主 PID 44008 保持运行。本项不是已通过的 GUI 功能;切页状态消费由离线回归覆盖。
+4
View File
@@ -14,6 +14,10 @@
PDF 配色默认使用“工程参考配色(mentor_PDF_output)”:红色连线、青绿色引脚、蓝色图形和文字、紫色方框、绿色网络名。颜色通过本次导出进程的独立配置加载;原理图中明确指定的对象颜色仍按原生规则显示。也可选择“原生配色”,配色选择会保存,并用于保存工程后自动导出。
文字处理默认“中文兼容(GBK,推荐)”:原生输出使用可映射文字,再修复本工程的 GBK 中文,并嵌入本机 Arial / 宋体子集及 Unicode 映射。中文可显示、复制和搜索,绘图颜色及矢量图形保持原样。西文工程可选“西文兼容”,保留 WinAnsi 符号;“原生字体”沿用旧映射,不执行编码修复。字体处理无法可靠完成时不会覆盖已有 PDF,页面显示具体原因。
DxDesigner 中切换原理图页后,工具会同步当前页;选择“当前页”导出时,页面显示最新的 Block 和图页名称。
“保存工程后自动导出”默认关闭。EE iCDB 工程会即时保存设计变更,工具收到原生变更事件、等待变更稳定后导出当前数据库;传统文件工程在保存完成后导出。重复通知会合并,已有导出进程结束后才执行下一次导出。监听器按配置中的工程路径绑定实例,关闭开关后自行退出。导出状态显示在 DxDesigner 状态栏,详细记录位于 `%LOCALAPPDATA%\DxProductivity\pdf-runs`。
PDF 使用本机 `sch2pdf.exe`、DxDesigner 配置和许可。原生出图可能更新工程数据库或运行记录;发布 PDF 前工具会检查工程文件变化,未确认的变化会阻止发布。
@@ -1,5 +1,11 @@
# 一叶知秋_重构版 更新说明
## 中文 PDF 与实时选择
- 修复 GBK 中文被按西文输出造成的乱码;默认采用中文兼容模式,嵌入字体及 Unicode 映射,保留图形和颜色。可选西文兼容或原生字体,手动和自动导出共用文字设置。
- DxDesigner 的单选、多选、取消选择及切页会实时同步;底部显示当前选中数量和位号。位号、属性、可见性、BOM 的选中范围同步更新,PDF 的当前页随宿主切页更新。
- 选择同步保留仍选中器件的新属性输入及 PDF 表单;应用或恢复进行时暂缓更新,操作结束后读取最新选择。无法识别的新增器件会自动请求完整快照。
## 紧凑窗口与悬浮入口
- 左侧 PDF 导出移到设置上方。
@@ -35,4 +41,4 @@
## 实机验收
本轮已在 DxDesigner / Expedition 7.9.5 的独立工程副本上验证位号、属性、可见性、历史恢复、器件与网络定位、BOM、PCB 整理和 PDF 导出。逐项结果和适用边界见 `docs/testing/native-acceptance-20261010.md`。原生 PDF 字体缺失造成的中文乱码或裁切仍依赖本机字体和出图配置。
已在 DxDesigner / Expedition 7.9.5 的独立工程副本上验证位号、属性、可见性、历史恢复、器件与网络定位、BOM、PCB 整理和 PDF 导出。逐项结果和适用边界见 `docs/testing/native-acceptance-20261010.md`;中文字体与实时选择的新版结果另有验收记录。
+2 -1
View File
@@ -236,7 +236,8 @@ Sub DxBridgeIdleWait()
Dim shell
On Error Resume Next
Set shell = CreateObject("WScript.Shell")
shell.Run "%ComSpec% /d /s /c ping -n 2 -w 400 127.0.0.1 > nul", 0, True
shell.Run DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _
" bridge-wait --milliseconds 150", 0, True
Err.Clear
On Error GoTo 0
Call DxBridgeYield()
@@ -86,16 +86,22 @@ Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _
Dim resultPath
Dim claimPath
Dim state
Dim lastSelection, pageContext, pageKeys
Set fso = CreateObject("Scripting.FileSystemObject")
resultPath = fso.BuildPath(runRoot, "result.tsv")
claimPath = fso.BuildPath(runRoot, "result.processing")
state = ""
lastSelection = ""
pageContext = ""
pageKeys = "[]"
Do While process.Status = 0
Call DxBridgeConsumeLocate(runRoot, objectMap)
Call DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _
snapshotId)
Call DxBridgePumpBomExport(runRoot)
Call DxBridgePublishSelection(runRoot, runId, snapshotId, _
lastSelection, pageContext, pageKeys)
Call DxWriteProgress(runRoot, "waiting")
If fso.FileExists(resultPath) Then
If DxBridgeClaimFile(fso, resultPath, claimPath) Then
@@ -116,6 +122,98 @@ Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _
DxBridgeMailboxLoop = state
End Function
Sub DxBridgePublishSelection(runRoot, runId, snapshotId, _
ByRef lastSelection, ByRef pageContext, ByRef pageKeys)
Dim designPath, blockName, sheetName, currentContext, selectedKeys
Dim text, numberJson, ready, newPageKeys
On Error Resume Next
designPath = DxBridgeDesignPath()
blockName = DxBridgeCurrentBlockName()
sheetName = DxBridgeCurrentSheetName()
ready = (designPath <> "" And blockName <> "" And sheetName <> "")
currentContext = designPath & vbTab & blockName & vbTab & sheetName & vbTab & snapshotId
If currentContext <> pageContext Then
newPageKeys = DxBridgeSelectionKeys(VD_ALL)
If Err.Number = 0 Then
pageKeys = newPageKeys
pageContext = currentContext
Else
ready = False
Err.Clear
End If
End If
selectedKeys = DxBridgeSelectionKeys(VD_SELECTED)
numberJson = DxBridgeCurrentSheetNumberJson()
If Err.Number <> 0 Then
ready = False
Err.Clear
End If
text = "{""state"":""unavailable"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """}"
If ready Then
text = "{""state"":""ready"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """,""active_block_name"":""" & _
DxToolsJson(blockName) & """,""current_sheet_name"":""" & _
DxToolsJson(sheetName) & """,""current_sheet_number"":" & _
numberJson & ",""selected_keys"":" & selectedKeys & _
",""current_sheet_keys"":" & pageKeys & ",""selected_nets"":" & _
DxBridgeExportSelectedNets() & "}"
End If
If text <> lastSelection Then
Call DxToolsWriteUtf8Atomic(fsoBuildPath(runRoot, "selection.json"), text)
If Err.Number = 0 Then lastSelection = text
Err.Clear
End If
On Error GoTo 0
End Sub
Function DxBridgeSelectionKeys(queryMode)
Dim keys, component, key, values, index, text
Set keys = CreateObject("Scripting.Dictionary")
For Each component In ActiveView.Query(VDM_COMP, queryMode)
key = DxBridgeComponentIdentity(component)
If key <> "" And Not keys.Exists(key) Then keys.Add key, True
Next
text = ""
If keys.Count > 0 Then
values = keys.Keys
If keys.Count > 1 Then Call DxBridgeSortSelectionKeys(values, 0, UBound(values))
For index = 0 To UBound(values)
If text <> "" Then text = text & ","
text = text & """" & DxToolsJson(values(index)) & """"
Next
End If
DxBridgeSelectionKeys = "[" & text & "]"
End Function
Sub DxBridgeSortSelectionKeys(ByRef keys, first, last)
Dim leftIndex, rightIndex, pivot, temporary
leftIndex = first
rightIndex = last
pivot = keys((first + last) \ 2)
Do While leftIndex <= rightIndex
Do While keys(leftIndex) < pivot
leftIndex = leftIndex + 1
Loop
Do While keys(rightIndex) > pivot
rightIndex = rightIndex - 1
Loop
If leftIndex <= rightIndex Then
temporary = keys(leftIndex)
keys(leftIndex) = keys(rightIndex)
keys(rightIndex) = temporary
leftIndex = leftIndex + 1
rightIndex = rightIndex - 1
End If
Loop
If first < rightIndex Then Call DxBridgeSortSelectionKeys(keys, first, rightIndex)
If leftIndex < last Then Call DxBridgeSortSelectionKeys(keys, leftIndex, last)
End Sub
Function DxBridgeClaimFile(fso, sourcePath, claimPath)
DxBridgeClaimFile = False
If fso.FileExists(claimPath) Then
+1
View File
@@ -13,6 +13,7 @@ hiddenimports = (
+ collect_submodules("qtawesome")
+ collect_submodules("cryptography")
+ collect_submodules("pypdf")
+ collect_submodules("fontTools")
+ ["pypdf", "win32job", "win32con", "win32process", "pywintypes",
"pythoncom", "win32com.client", "win32com.client.gencache",
"win32com.client.genpy", "win32com.client.makepy"]
+1
View File
@@ -12,6 +12,7 @@ dependencies = [
"qtawesome>=1.3,<2",
"cryptography>=42,<46",
"pypdf>=5,<7",
"fonttools>=4.55,<5",
"pywin32>=306,<312; sys_platform == 'win32'",
]
+11
View File
@@ -8,6 +8,17 @@ from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
arguments = list(sys.argv[1:] if argv is None else argv)
if arguments and arguments[0] == "bridge-wait":
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument("--milliseconds", type=int, default=150)
options = parser.parse_args(arguments[1:])
if not 0 <= options.milliseconds <= 1000:
parser.error("milliseconds must be between 0 and 1000")
time.sleep(options.milliseconds / 1000)
return 0
if arguments and arguments[0] in ("startup", "start"):
from dx_productivity.bridge.startup import main as startup_main
@@ -0,0 +1,133 @@
"""Embed subsets of installed Windows fonts with explicit Unicode mappings."""
from __future__ import annotations
from dataclasses import dataclass
from io import BytesIO
import os
from pathlib import Path
from pypdf.generic import ArrayObject, DecodedStreamObject, DictionaryObject, NameObject, NumberObject, FloatObject, TextStringObject
@dataclass
class UnicodeFont:
name: str
reference: object
cids: dict[int, int]
widths: dict[int, int]
def encode(self, text: str) -> bytes:
return b''.join(self.cids[ord(char)].to_bytes(2, 'big') for char in text)
def advance(self, text: str, size: float) -> float:
return sum(self.widths[ord(char)] for char in text) * size / 1000
def _load(filename: str):
from fontTools.ttLib import TTFont
path = Path(os.environ.get('WINDIR', 'C:/Windows')) / 'Fonts' / filename
if not path.is_file():
raise ValueError(f'本机缺少 {filename},无法生成可阅读的 PDF 文字')
return TTFont(path, fontNumber=0, recalcTimestamp=False)
def _subset(writer, font, characters: set[str], name: str) -> UnicodeFont:
from fontTools import subset
points = sorted(ord(char) for char in characters)
missing = set(points) - (font.getBestCmap() or {}).keys()
if missing:
raise ValueError('字体缺少字符:' + ', '.join(f'U+{cp:04X}' for cp in sorted(missing)[:12]))
if len(points) > 65534:
raise ValueError('PDF 文字字符集超出单个字体子集容量')
if getattr(font.get('OS/2'), 'fsType', 0) & (0x0002 | 0x0100 | 0x0200):
raise ValueError('本机字体的嵌入限制不支持 PDF 字体子集')
options = subset.Options()
options.recalc_timestamp = False
options.layout_features = []
options.drop_tables.extend(['meta', 'MERG'])
worker = subset.Subsetter(options=options)
worker.populate(unicodes=points)
worker.subset(font)
buffer = BytesIO()
font.flavor = None
font.save(buffer)
units = font['head'].unitsPerEm
cmap = font.getBestCmap()
cids = {cp: index for index, cp in enumerate(points, 1)}
widths = {cp: round(font['hmtx'][cmap[cp]][0] * 1000 / units) for cp in points}
def stream(data: bytes):
obj = DecodedStreamObject()
obj.set_data(data)
return writer._add_object(obj.flate_encode())
payload = buffer.getvalue()
file = DecodedStreamObject()
file.set_data(payload)
file[NameObject('/Length1')] = NumberObject(len(payload))
base_name = '/YYZQAA+' + name
metric = lambda number: NumberObject(round(number * 1000 / units))
head, hhea, os2 = font['head'], font['hhea'], font.get('OS/2')
descriptor = DictionaryObject({
NameObject('/Type'): NameObject('/FontDescriptor'), NameObject('/FontName'): NameObject(base_name),
NameObject('/Flags'): NumberObject(32),
NameObject('/FontBBox'): ArrayObject([metric(number) for number in (head.xMin, head.yMin, head.xMax, head.yMax)]),
NameObject('/ItalicAngle'): FloatObject(font['post'].italicAngle),
NameObject('/Ascent'): metric(hhea.ascent), NameObject('/Descent'): metric(hhea.descent),
NameObject('/CapHeight'): metric(getattr(os2, 'sCapHeight', hhea.ascent)),
NameObject('/StemV'): NumberObject(80), NameObject('/FontFile2'): writer._add_object(file.flate_encode()),
})
# Each Unicode character receives its own CID, even when two characters
# share a glyph outline. This preserves symbols in extracted/search text.
gid_map = b'\x00\x00' + b''.join(font.getGlyphID(cmap[cp]).to_bytes(2, 'big') for cp in points)
descendant = DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/CIDFontType2'),
NameObject('/BaseFont'): NameObject(base_name),
NameObject('/CIDSystemInfo'): DictionaryObject({NameObject('/Registry'): TextStringObject('Adobe'),
NameObject('/Ordering'): TextStringObject('Identity'), NameObject('/Supplement'): NumberObject(0)}),
NameObject('/FontDescriptor'): writer._add_object(descriptor), NameObject('/CIDToGIDMap'): stream(gid_map),
NameObject('/DW'): NumberObject(1000),
NameObject('/W'): ArrayObject([NumberObject(1), ArrayObject([NumberObject(widths[cp]) for cp in points])]),
})
rows = ['/CIDInit /ProcSet findresource begin', '12 dict begin', 'begincmap',
'/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def',
'/CMapName /YiyeUnicode def', '/CMapType 2 def', '1 begincodespacerange', '<0000> <FFFF>', 'endcodespacerange']
for offset in range(0, len(points), 100):
chunk = points[offset:offset + 100]
rows.append(f'{len(chunk)} beginbfchar')
rows.extend(f'<{cids[cp]:04X}> <{chr(cp).encode("utf-16-be").hex().upper()}>' for cp in chunk)
rows.append('endbfchar')
rows.extend(['endcmap', 'CMapName currentdict /CMap defineresource pop', 'end', 'end'])
resource = DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type0'),
NameObject('/BaseFont'): NameObject(base_name), NameObject('/Encoding'): NameObject('/Identity-H'),
NameObject('/DescendantFonts'): ArrayObject([writer._add_object(descendant)]),
NameObject('/ToUnicode'): stream('\n'.join(rows).encode('ascii')),
})
return UnicodeFont('/Yiye' + name, writer._add_object(resource), cids, widths)
def build_fonts(writer, texts: list[str]) -> dict[str, UnicodeFont]:
primary = _load('arial.ttf')
fallback = None
try:
cmap = primary.getBestCmap() or {}
groups = {False: set(), True: set()}
assignments = {}
for text in texts:
needs_cjk = any(ord(char) not in cmap for char in text)
assignments[text] = needs_cjk
groups[needs_cjk].update(text)
fonts = {}
if groups[False]:
fonts[False] = _subset(writer, primary, groups[False], 'Arial')
if groups[True]:
fallback = _load('simsun.ttc')
fonts[True] = _subset(writer, fallback, groups[True], 'SimSun')
return {text: fonts[needs_cjk] for text, needs_cjk in assignments.items()}
finally:
primary.close()
if fallback is not None:
fallback.close()
@@ -18,6 +18,7 @@ from pypdf import PdfReader, PdfWriter
from .engine import discover_engine, run_engine
from .models import ExportScope, PdfExportResult, PdfExportSettings
from .native_profile import prepare_environment
from .text_repair import repair_text
HEADER_LIMIT = 512 * 1024
@@ -310,6 +311,8 @@ def build_command(
output: Path,
scope: ExportScope,
block_name: str = "",
*,
text_mode: str = "chinese",
) -> list[str]:
command = [
str(engine),
@@ -322,8 +325,9 @@ def build_command(
"-p",
"-e",
"-i2s",
"-udx",
]
if text_mode == "original":
command.append("-udx")
if scope is not ExportScope.PROJECT:
if not block_name.strip() or any(char in block_name for char in "\r\n\x00"):
raise ValueError("当前页或指定范围缺少有效 Block 名称")
@@ -423,7 +427,7 @@ def export_project(
else settings.block_name.strip()
)
stage = output_dir / f".{final_path.stem}.{uuid.uuid4().hex[:8]}.partial.pdf"
command = build_command(engine, project, stage, settings.scope, block_name)
command = build_command(engine, project, stage, settings.scope, block_name, text_mode=settings.text_mode)
environment = prepare_environment(run_dir, settings.print_theme)
_write_json(
run_dir / "request.json",
@@ -436,6 +440,7 @@ def export_project(
"output": str(final_path),
"engine": str(engine),
"print_theme": settings.print_theme,
"text_mode": settings.text_mode,
"native_profile": str(run_dir / "native-profile" / "DxDesigner.xml")
if environment is not None else "",
"command": command,
@@ -455,6 +460,9 @@ def export_project(
if settings.scope is ExportScope.CURRENT_PAGE:
emit(f"从原生 PDF 定位当前活动页:{active_sheet_name.strip()}")
_select_current_page(stage, block_name, active_sheet_name)
emit("核验并嵌入 PDF 文字字体")
text_check = repair_text(stage, settings.text_mode, cancel)
_write_json(run_dir / "text-check.json", text_check)
pages, size, sha256 = _validate_pdf(stage)
_write_json(
run_dir / "pdf-check.json",
@@ -20,10 +20,13 @@ class PdfExportSettings:
auto_export: bool = False
engine_path: Path | None = None
print_theme: str = "reference"
text_mode: str = "chinese"
def __post_init__(self) -> None:
if self.print_theme not in {"reference", "original"}:
raise ValueError("不支持的 PDF 配色")
if self.text_mode not in {"chinese", "western", "original"}:
raise ValueError("不支持的 PDF 文字处理模式")
values = [str(self.project_path), str(self.output_dir), self.block_name]
if self.engine_path is not None:
values.append(str(self.engine_path))
@@ -79,6 +79,9 @@ def load_settings(
print_theme = data.get("print_theme", "reference")
if print_theme not in ("reference", "original"):
print_theme = "reference"
text_mode = data.get("text_mode", "chinese")
if text_mode not in ("chinese", "western", "original"):
text_mode = "chinese"
if not isinstance(block_name, str) or not isinstance(output_value, str):
return defaults
if not isinstance(engine_value, str):
@@ -92,6 +95,7 @@ def load_settings(
auto_export=data.get("auto_export") is True,
engine_path=Path(engine_value) if engine_value else None,
print_theme=print_theme,
text_mode=text_mode,
)
except (OSError, TypeError, ValueError):
return defaults
@@ -110,6 +114,7 @@ def save_settings(
"output_dir": str(settings.output_dir.resolve(strict=False)),
"auto_export": bool(settings.auto_export),
"print_theme": settings.print_theme,
"text_mode": settings.text_mode,
"engine_path": str(settings.engine_path.resolve(strict=False))
if settings.engine_path
else "",
@@ -0,0 +1,175 @@
"""Repair native WinAnsi/GBK text while retaining drawing geometry and colors."""
from __future__ import annotations
import os
from pathlib import Path
from threading import Event
import uuid
from pypdf import PdfReader, PdfWriter
from pypdf.generic import ByteStringObject, ContentStream, DictionaryObject, FloatObject, NameObject
from .embedded_fonts import build_fonts
def _cancelled(cancel: Event) -> None:
if cancel.is_set():
raise InterruptedError('导出已取消')
def _raw(value) -> bytes:
if isinstance(value, ByteStringObject):
return bytes(value)
if hasattr(value, 'original_bytes'):
return value.original_bytes
return str(value).encode('cp1252')
def _decode(raw: bytes, mode: str) -> tuple[str, bool]:
if mode == 'chinese':
try:
text = raw.decode('gbk', errors='strict')
return ''.join(char for char in text if ord(char) >= 32), any(byte >= 128 for byte in raw)
except UnicodeDecodeError:
pass
text = raw.decode('cp1252', errors='strict')
return ''.join(char for char in text if ord(char) >= 32), False
def _legacy(font) -> bool:
return (font.get('/Encoding') == '/WinAnsiEncoding'
and font.get('/Subtype') in ('/TrueType', '/Type1') and '/ToUnicode' not in font)
def _text_operations(stream, resources, reader):
font_name, size, scale, char_space, word_space, rendering = None, 12., 100., 0., 0., 0
stack = []
fonts = resources.get('/Font', DictionaryObject()).get_object()
for operands, operator in ContentStream(stream, reader).operations:
if operator == b'q':
stack.append((font_name, size, scale, char_space, word_space, rendering))
elif operator == b'Q' and stack:
font_name, size, scale, char_space, word_space, rendering = stack.pop()
elif operator == b'Tf':
font_name, size = operands[0], float(operands[1])
elif operator == b'Tz': scale = float(operands[0])
elif operator == b'Tc': char_space = float(operands[0])
elif operator == b'Tw': word_space = float(operands[0])
elif operator == b'Tr': rendering = int(operands[0])
font = fonts.get(font_name)
font = font.get_object() if font is not None else None
if operator in (b'Tj', b'TJ', b"'", b'"') and font is not None and _legacy(font):
if operator != b'Tj':
raise ValueError(f'暂不能修复 {operator.decode()} 复合文字,未发布乱码 PDF')
raw = _raw(operands[0])
if str(font.get('/BaseFont', '')).lstrip('/').casefold().startswith('fstroke'):
if rendering == 3 and raw.isascii():
yield operands, operator, None
continue
raise ValueError('原生输出仍含中文笔画文字,无法保证中文修复,未发布 PDF')
if char_space or word_space:
raise ValueError('原生文字使用字符间距或词间距,无法保证字体转换,未发布 PDF')
yield operands, operator, (font, font_name, raw, size, scale)
elif operator == b'Do':
form = resources.get('/XObject', {}).get(operands[0])
if form is not None and form.get_object().get('/Subtype') == '/Form':
form = form.get_object()
for _, _, text in _text_operations(form, form.get('/Resources', resources).get_object(), reader):
if text is not None:
raise ValueError('暂不能转换 Form 内旧编码文字,未发布乱码 PDF')
yield operands, operator, None
else:
yield operands, operator, None
def _old_advance(font, raw: bytes, size: float) -> float:
raw = bytes(byte for byte in raw if byte >= 32)
values = font.get('/Widths')
if values is not None:
values = values.get_object()
first = int(font.get('/FirstChar', 0))
if any(not 0 <= byte - first < len(values) for byte in raw):
raise ValueError('原字体缺少字符宽度,未发布 PDF')
widths = [float(values[byte - first]) for byte in raw]
else:
from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS
from pypdf._codecs import _win_encoding
metrics = CORE_FONT_METRICS.get(str(font.get('/BaseFont', '')).lstrip('/'))
if metrics is None:
raise ValueError('原字体缺少可靠字宽信息,未发布 PDF')
widths = [metrics.character_widths.get(_win_encoding[byte], metrics.character_widths['default']) for byte in raw]
return sum(widths) * size / 1000
def repair_text(path: Path, mode: str, cancel: Event) -> dict:
_cancelled(cancel)
report = {'mode': mode, 'font_strings': 0, 'repaired_strings': 0, 'embedded_fonts': 0}
if mode == 'original':
return report
if mode not in ('chinese', 'western'):
raise ValueError('不支持的 PDF 文字处理模式')
reader = PdfReader(path, strict=True)
decoded = {}
for page in reader.pages:
_cancelled(cancel)
resources = page.get('/Resources', DictionaryObject()).get_object()
for _, _, state in _text_operations(page.get_contents(), resources, reader):
if state is not None:
decoded[state[2]] = _decode(state[2], mode)
if not decoded:
return report
writer = PdfWriter()
writer.clone_document_from_reader(reader)
assignments = build_fonts(writer, [text for text, _ in decoded.values() if text])
fonts = {font.name: font for font in assignments.values()}
report['embedded_fonts'] = len(fonts)
for page in writer.pages:
_cancelled(cancel)
resources = DictionaryObject(dict(page.get('/Resources', DictionaryObject()).get_object()))
page[NameObject('/Resources')] = resources
original_fonts = DictionaryObject(dict(resources.get('/Font', DictionaryObject()).get_object()))
stream = ContentStream(page.get_contents(), writer)
rebuilt = []
for operands, operator, state in _text_operations(stream, resources, writer):
if state is None:
rebuilt.append((operands, operator))
continue
original, name, raw, size, scale = state
text, repaired = decoded[raw]
if not text:
rebuilt.append((operands, operator))
continue
font = assignments[text]
old_width = _old_advance(original, raw, size)
width = font.advance(text, size)
new_scale = scale * old_width / width if width > 0 else scale
rebuilt.extend([([NameObject(font.name), FloatObject(size)], b'Tf'),
([FloatObject(new_scale)], b'Tz'), ([ByteStringObject(font.encode(text))], b'Tj'),
([name, FloatObject(size)], b'Tf'), ([FloatObject(scale)], b'Tz')])
report['font_strings'] += 1
report['repaired_strings'] += int(repaired)
for name, font in fonts.items():
if name in original_fonts:
raise ValueError('嵌入字体名称与原 PDF 冲突')
original_fonts[NameObject(name)] = font.reference
resources[NameObject('/Font')] = original_fonts
stream.operations = rebuilt
stream.get_data()
page[NameObject('/Contents')] = writer._add_object(stream.flate_encode())
temporary = Path(path).with_name(f'.{Path(path).name}.{uuid.uuid4().hex[:8]}.text.tmp')
try:
_cancelled(cancel)
with temporary.open('xb') as output:
writer.write(output)
output.flush()
os.fsync(output.fileno())
verified = PdfReader(temporary, strict=True)
if len(verified.pages) != len(reader.pages):
raise ValueError('文字处理改变了 PDF 页数,未发布 PDF')
for page in verified.pages:
page.get_contents().get_data()
_cancelled(cancel)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
return report
+2
View File
@@ -23,6 +23,7 @@ from dx_productivity.domain.models import RunPaths
from dx_productivity.ui.bom_controller import BomController
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.selection_watcher import SelectionWatcher
from dx_productivity.ui.startup_controller import StartupController
from dx_productivity.ui.property_change_controller import PropertyChangeController
from dx_productivity.ui.property_change_page import PropertyChangePage
@@ -301,6 +302,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
)
if watcher is not None:
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
window.selection_watcher = SelectionWatcher(window, request_path)
window.navigation.setCurrentRow(0)
window.pages.setCurrentIndex(0)
window.page_title.setText("自动位号")
+4
View File
@@ -258,6 +258,10 @@ class MainWindow(QMainWindow):
self.bridge_status = QLabel("桥接待连接")
self.bridge_status.setObjectName("secondaryLabel")
layout.addWidget(self.bridge_status)
self.selection_status = QLabel("选择同步等待宿主")
self.selection_status.setObjectName("secondaryLabel")
self.selection_status.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
layout.addWidget(self.selection_status, 1)
self.operation_status = QLabel("就绪")
self.operation_status.setObjectName("secondaryLabel")
self.operation_status.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
@@ -98,6 +98,19 @@ class PdfExportController(QObject):
return
self.status_changed.emit("保存后自动导出已关闭")
def load_selection_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.page.snapshot = snapshot
self.page._loading = True
try:
if self.page.scope_combo.currentData() == ExportScope.CURRENT_PAGE.value:
self.page.block_input.setText(snapshot.active_block_name)
self.page._scope_changed()
busy = self._thread is not None and self._thread.isRunning()
self.page.set_busy(busy)
finally:
self.page._loading = False
def _ensure_listener(self) -> None:
result = ensure_listener(self.config_path, self.tool_root)
if result:
+11
View File
@@ -60,6 +60,13 @@ class PdfExportPage(QWidget):
self.palette_combo.addItem("原生配色", "original")
form.addRow("PDF 配色", self.palette_combo)
self.text_combo = QComboBox()
self.text_combo.addItem("中文兼容(GBK,推荐)", "chinese")
self.text_combo.addItem("西文兼容(保留西文符号)", "western")
self.text_combo.addItem("原生字体(不修复编码)", "original")
self.text_combo.setToolTip("中文兼容用于 GBK 中文工程;西文兼容保留 WinAnsi 工程符号。兼容模式会嵌入字体,便于分享和搜索。")
form.addRow("文字处理", self.text_combo)
block_row = QHBoxLayout()
self.block_input = QLineEdit()
self.block_input.setPlaceholderText("DxDesigner 原理图或 Block 名称")
@@ -129,6 +136,7 @@ class PdfExportPage(QWidget):
self.scope_combo.currentIndexChanged.connect(self._scope_changed)
self.palette_combo.currentIndexChanged.connect(self._emit_settings)
self.text_combo.currentIndexChanged.connect(self._emit_settings)
self.block_input.editingFinished.connect(self._emit_settings)
self.output_input.editingFinished.connect(self._emit_settings)
self.engine_input.editingFinished.connect(self._emit_settings)
@@ -141,6 +149,7 @@ class PdfExportPage(QWidget):
scope_index = self.scope_combo.findData(settings.scope.value)
self.scope_combo.setCurrentIndex(max(scope_index, 0))
self.palette_combo.setCurrentIndex(max(self.palette_combo.findData(settings.print_theme), 0))
self.text_combo.setCurrentIndex(max(self.text_combo.findData(settings.text_mode), 0))
self.block_input.setText(
settings.block_name
if settings.scope is ExportScope.BLOCK
@@ -177,6 +186,7 @@ class PdfExportPage(QWidget):
auto_export=self.auto_export_checkbox.isChecked(),
engine_path=Path(engine_value) if engine_value else None,
print_theme=self.palette_combo.currentData(),
text_mode=self.text_combo.currentData(),
)
def confirm_overwrite(self, path: str) -> bool:
@@ -211,6 +221,7 @@ class PdfExportPage(QWidget):
self.cancel_button.setEnabled(busy)
self.scope_combo.setEnabled(not busy)
self.palette_combo.setEnabled(not busy)
self.text_combo.setEnabled(not busy)
self.output_input.setEnabled(not busy)
self.output_button.setEnabled(not busy)
self.engine_input.setEnabled(not busy)
@@ -79,6 +79,19 @@ class PropertyChangeController(QObject):
rows.append((component.bridge_id, component.refdes or "(无位号)", current))
self.page.set_rows(rows, editable=True)
def load_selection_snapshot(self, snapshot: DesignSnapshot) -> None:
pending = dict(self.page.settings().overrides)
self.load_snapshot(snapshot)
model = self.page.model
from PySide6.QtCore import Qt
model.blockSignals(True)
for row in range(model.rowCount()):
bridge_id = model.item(row, 0).data(Qt.ItemDataRole.UserRole)
if bridge_id in pending:
model.item(row, 2).setText(pending[bridge_id])
model.blockSignals(False)
self.refresh_plan()
def refresh_plan(self) -> None:
if self._apply_in_flight or self.snapshot is None:
return
+118
View File
@@ -0,0 +1,118 @@
"""Consume lightweight native selection state without rebuilding design data."""
from __future__ import annotations
from dataclasses import replace
import json
import os
from pathlib import Path
import time
from PySide6.QtCore import QObject, QTimer
def identity(component) -> str:
return ('uid:' + component.stable_uid.casefold() if component.stable_uid
else 'path:' + component.full_path.casefold())
class SelectionWatcher(QObject):
def __init__(self, window, request_path: Path) -> None:
super().__init__(window)
self.window = window
self.path = request_path.with_name('selection.json')
self.last_signature = None
self.timer = QTimer(self)
self.timer.setInterval(150)
self.timer.timeout.connect(self._check)
self.timer.start()
self._check()
def _check(self) -> None:
if self.window._closing:
self.timer.stop()
return
controller = self.window.refdes_controller
snapshot = controller.snapshot
if snapshot is None:
return
controllers = tuple(item for item in (
controller, self.window.property_change_controller, self.window.property_visibility_controller,
self.window.inspection_controller, self.window.network_controller, self.window.bom_controller,
self.window.history_controller, self.window.pdf_export_controller,
) if item is not None)
if any(getattr(item, '_apply_in_flight', False) or getattr(item, '_restore_in_flight', False) for item in controllers):
return
heartbeat = self.path.with_name('apply-progress.json')
try:
if heartbeat.exists() and time.time() - heartbeat.stat().st_mtime > 5:
self.window.selection_status.setText('选择同步已暂停')
self.window.selection_status.setToolTip('宿主桥接没有更新,请刷新快照或重新从 DxDesigner 菜单打开工具。')
self.last_signature = None
return
raw = self.path.read_text(encoding='utf-8-sig')
signature = (raw, snapshot.snapshot_id)
if signature == self.last_signature:
return
data = json.loads(raw)
except (OSError, ValueError):
return
if not isinstance(data, dict) or data.get('run_id') != snapshot.run_id:
return
if os.path.normcase(str(data.get('design_path', ''))) != os.path.normcase(snapshot.design_path):
self.window.selection_status.setText('工程已切换,请重新打开工具')
return
if data.get('snapshot_id') != snapshot.snapshot_id:
return
if data.get('state') != 'ready':
fresh = replace(snapshot, components=tuple(replace(component, selected=False, current_sheet=False)
for component in snapshot.components), selected_nets=(), active_block_name='',
current_sheet_name='', current_sheet_number=None)
self._load_snapshot(fresh, controllers)
self.last_signature = signature
self.window.selection_status.setText('未打开原理图页')
return
selected = data.get('selected_keys')
current = data.get('current_sheet_keys')
nets = data.get('selected_nets', [])
if any(not isinstance(value, list) or any(not isinstance(item, str) for item in value) for value in (selected, current, nets)):
return
block = data.get('active_block_name')
sheet = data.get('current_sheet_name')
page = data.get('current_sheet_number')
if not isinstance(block, str) or not isinstance(sheet, str) or (page is not None and type(page) is not int):
return
selected, current = set(selected), set(current)
components = tuple(replace(component, selected=identity(component) in selected,
current_sheet=identity(component) in current) for component in snapshot.components)
fresh = replace(snapshot, components=components, active_block_name=block, current_sheet_name=sheet,
current_sheet_number=page, selected_nets=tuple(nets))
self._load_snapshot(fresh, controllers)
self.last_signature = signature
known = {identity(component) for component in components}
refs = [component.refdes or '未标注器件' for component in components if component.selected]
if selected - known:
self.window.selection_status.setText('所选器件需刷新快照')
refresh = self.path.with_name('refresh.request')
if not refresh.exists():
try:
refresh.write_text('snapshot\n', encoding='utf-8')
except OSError:
pass
else:
summary = '、'.join(refs[:4]) + ('…' if len(refs) > 4 else '')
self.window.selection_status.setText(f'已选 {len(refs)} 个' + (f':{summary}' if summary else '器件'))
self.window.selection_status.setToolTip(
f'当前工程:{fresh.design_path}\n当前页:{block} / {sheet}\n选中器件:' + ('、'.join(refs) or '无')
)
def _load_snapshot(self, fresh, controllers) -> None:
for item in controllers:
load = getattr(item, 'load_selection_snapshot', None)
if load is not None:
load(fresh)
elif item in (self.window.inspection_controller, self.window.network_controller, self.window.history_controller):
# Selection changes must not clear a highlighted inspection
# result or the history entry the user is reviewing.
item.snapshot = fresh
else:
item.load_snapshot(fresh)
+103
View File
@@ -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()
+88
View 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)
+145
View File
@@ -0,0 +1,145 @@
"""Verify live selection on an explicitly opened independent DxDesigner copy."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import time
import win32gui
import win32process
from pywinauto import Application
from dx_productivity.bridge.startup_assets import generate_startup_assets, vbscript_string
from packaged_menu import tools_running, wait_for
def main():
parser = argparse.ArgumentParser()
parser.add_argument('executable', type=Path)
parser.add_argument('--project', required=True, type=Path)
parser.add_argument('--evidence', required=True, type=Path)
options = parser.parse_args()
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
base.mkdir(parents=True, exist_ok=True)
helper = Path(__file__).with_name('run_dx_script.py')
assets = generate_startup_assets(exe.parent, base / 'private-menu')
def run(script):
return subprocess.run([sys.executable, str(helper), '--project', str(project), str(script)],
check=True, timeout=20, capture_output=True)
run(assets.menu_script)
invoke = base / 'open-selection-menu.vbs'
invoke.write_text(f'''
Dim liveBar,liveItem,liveIndex
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project"
Set liveBar=CommandBars("Sheet Menu Bar")
For liveIndex=1 To liveBar.Controls.Count
Set liveItem=liveBar.Controls.Item(liveIndex)
If liveItem.Caption="Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then
Application.ExecuteCommand liveItem.Controls.Item(1).OnAction
Exit For
End If
Next
''', encoding='ascii')
before = {p.pid for p in tools_running()}
log = (base / 'native-menu-call.log').open('wb')
native_call = subprocess.Popen([sys.executable, str(helper), '--project', str(project), str(invoke)], stdout=log, stderr=log)
tool = wait_for(lambda: next((p for p in tools_running() if p.pid not in before and
Path(p.executable).resolve() == exe and '--request' in p.command_line and '--smoke-test-ms' not in p.command_line), None), 30)
args = shlex.split(tool.command_line, posix=False)
request = Path(args[args.index('--request') + 1].strip('"'))
initial = json.loads(request.read_text(encoding='utf-8-sig'))
selection = request.with_name('selection.json')
ui = Application(backend='uia').connect(process=tool.pid, timeout=15)
window = ui.window(title='一叶知秋_重构版')
window.wait('visible', timeout=15)
main_handle = window.handle
refs = {'uid:' + c['stable_uid'].casefold(): c['refdes'] for c in initial['components'] if c['stable_uid']}
evidence = []
def actual_refs():
try:
payload = json.loads(selection.read_text(encoding='utf-8-sig'))
if payload.get('state') != 'ready': return None
return sorted(refs[key] for key in payload['selected_keys'])
except (OSError, ValueError, KeyError): return None
def displayed(expected):
texts = [x.window_text() for x in window.descendants(control_type='Text')]
matches = [text for text in texts if text.startswith(f'已选 {len(expected)} 个')]
return matches[0] if matches and all(ref in matches[0] for ref in expected[:4]) else None
def select(refdes, name):
script = base / f'{name}.vbs'
literals = ','.join(vbscript_string(ref) for ref in refdes)
targets = f'Array({literals})' if refdes else 'Array()'
script.write_text(f'''
Dim liveComp,liveRef,liveTargets,liveTarget
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513, "Acceptance", "Wrong project"
ActiveView.Block.DeSelectAll
liveTargets={targets}
For Each liveComp In ActiveView.Query(VDM_COMP,VD_ALL)
liveRef=CStr(liveComp.Refdes)
For Each liveTarget In liveTargets
If liveRef=liveTarget Then liveComp.Selected=True
Next
Next
ActiveView.Refresh
''', encoding='ascii')
began = time.monotonic()
run(script)
wait_for(lambda: actual_refs() == sorted(refdes), 10)
label = wait_for(lambda: displayed(refdes), 10)
elapsed = time.monotonic() - began
assert elapsed < 2.5, elapsed
assert json.loads(request.read_text(encoding='utf-8-sig'))['snapshot_id'] == initial['snapshot_id']
evidence.append({'case': name, 'selected': refdes, 'label': label, 'elapsed_seconds': round(elapsed, 3),
'without_manual_refresh': True})
print(f'PASS LIVE SELECTION {name} {label} {elapsed:.3f}s', flush=True)
try:
select(['CE17'], 'single-capacitor')
select(['LE03'], 'single-inductor')
select(['CE17', 'LE03'], 'multiple')
window.child_window(title='属性批改', control_type='ListItem').select()
rows = [x.window_text() for x in window.descendants(control_type='Text')]
assert any(text.startswith('已选 2 个') and 'CE17' in text and 'LE03' in text for text in rows)
select([], 'deselected')
window.child_window(title='自动位号', control_type='ListItem').select()
window.child_window(title='收起为悬浮窗', control_type='Button').invoke()
wait_for(lambda: not win32gui.IsWindowVisible(main_handle))
script = base / 'collapsed-select.vbs'
native_name = next(component['stable_uid'] for component in initial['components'] if component['refdes'] == 'CE17')
script.write_text(f'If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase({vbscript_string(str(project))}) Then Err.Raise 513\nActiveView.SelectByName {vbscript_string(native_name)}\nActiveView.Refresh\n', encoding='ascii')
run(script)
wait_for(lambda: actual_refs() == ['CE17'], 10)
handles = []
def inspect(handle, _):
if (win32process.GetWindowThreadProcessId(handle)[1] == tool.pid
and win32gui.GetWindowText(handle) == '一叶知秋悬浮入口'
and win32gui.IsWindowVisible(handle)):
handles.append(handle)
win32gui.EnumWindows(inspect, None)
assert len(handles) == 1
ui.window(handle=handles[0]).wrapper_object().invoke()
window.wait('visible', timeout=15)
wait_for(lambda: displayed(['CE17']), 10)
evidence.append({'case': 'collapsed-selection', 'selected': ['CE17'], 'restored_selection_current': True})
finally:
win32gui.PostMessage(main_handle, 0x10, 0, 0)
assert native_call.wait(timeout=15) == 0
log.close()
report = {'executable': str(exe), 'project': str(project), 'pid': tool.pid,
'request': str(request), 'cases': evidence, 'design_values_written': False}
(base / 'live-selection-acceptance.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('PASS NATIVE LIVE SELECTION', json.dumps(report, ensure_ascii=False), flush=True)
if __name__ == '__main__':
main()
+1 -1
View File
@@ -85,7 +85,7 @@ def main():
reference_run = base / 'original-tool-reference'
reference_run.mkdir(exist_ok=True)
reference_pdf = reference_run / 'reference.pdf'
profile = ExportOptions(print_theme='reference', stop_at='')
profile = ExportOptions(print_theme='reference', font_mapping='arial', legacy_gbk=True, stop_at='')
command = build_command(discover_engine(), options.audio, reference_pdf, profile)
assert run_engine(command, options.audio.parent, reference_run, threading.Event(), 180,
print, env=prepare_native_environment(reference_run, profile)) == 0