Files
dxdesigner-part-replacement/tools/research/probe-native-capabilities.py

158 lines
6.0 KiB
Python

"""Offline comparison of installed DxDesigner typelib and a saved makepy wrapper.
This script loads only the installed .tlb file and reads a saved wrapper. It never
attaches to Viewdraw or starts DxDesigner.
"""
from __future__ import annotations
import argparse
import ast
import hashlib
import json
import re
from pathlib import Path
DEFAULT_WRAPPER = Path(
r"F:\Sync Tool Skyworth\Work Maps\AppTraceRecorder\reference\SiemensEDA_Python_Interface\xpedition_designer\designer_ifc.py"
)
DEFAULT_TLB = Path(r"D:\Mentor\7.9.5EE\SDD_HOME\wv\win32\bin\viewdraw.tlb")
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def extract(wrapper: str) -> dict:
wrapper_major = re.search(r"^MajorVersion\s*=\s*(\d+)", wrapper, re.MULTILINE)
wrapper_minor = re.search(r"^MinorVersion\s*=\s*(\d+)", wrapper, re.MULTILINE)
constants = {}
for name in ("SRP_Project", "SRP_Board", "SRP_Schematic", "SRP_Sheet", "SRP_Selection",
"PinMT_ByName", "PinMT_ByPinNumber", "PropMT_LibraryOnly",
"PropMT_SchematicWins", "PropMT_LibraryWins"):
match = re.search(rf"^\s*{name}\s*=\s*(\d+)\s+# from enum", wrapper, re.MULTILINE)
if match:
constants[name] = int(match.group(1))
methods = []
seen = set()
for owner in ast.parse(wrapper).body:
if not isinstance(owner, ast.ClassDef):
continue
for node in owner.body:
if not isinstance(node, ast.FunctionDef) or node.name not in {
"ReplacePart", "ReplaceSymbol", "ReplaceConnector"
}:
continue
calls = [item for item in ast.walk(node) if isinstance(item, ast.Call)
and isinstance(item.func, ast.Attribute) and item.func.attr == "InvokeTypes"]
if len(calls) != 1:
continue
call = calls[0]
dispid = ast.literal_eval(call.args[0])
key = (owner.name, node.name, dispid)
if key in seen:
continue
seen.add(key)
methods.append({
"interface": owner.name,
"name": node.name,
"dispid": dispid,
"arguments": [item.arg for item in node.args.args if item.arg != "self"],
"makepy_return_type": ast.literal_eval(call.args[3]),
"makepy_argument_types": ast.literal_eval(call.args[4]),
"wrapper_line": node.lineno,
"status": "typelib_candidate",
})
return {
"declared_version": {
"major": int(wrapper_major.group(1)) if wrapper_major else None,
"minor": int(wrapper_minor.group(1)) if wrapper_minor else None,
},
"constants": constants,
"methods": methods,
}
def inspect_installed_typelib(path: Path) -> dict:
import pythoncom
library = pythoncom.LoadTypeLib(str(path))
attr = library.GetLibAttr()
wanted = {
"ExecuteCommand", "ReplacePart", "ReplaceSymbol", "ReplaceConnector",
"ChangeComponent", "ChangeComponentPreserveRefdes", "SelectExactSet",
"Selected", "_SetSelected", "SelectObject", "SelectComponent",
"SelectByName", "DeSelectAll", "QueryPages", "DesignComponents",
"GetProjectData", "OpenReplacePartDialog", "ReplacePartCompleted",
}
interfaces = {}
selected_interfaces = {"IVdApp", "IVdAppProtectionProxy", "IVdBlock", "IVdComp", "IVdView", "ICommandsManager"}
for index in range(library.GetTypeInfoCount()):
name = library.GetDocumentation(index)[0]
if name not in selected_interfaces:
continue
info = library.GetTypeInfo(index)
found = []
for member_index in range(info.GetTypeAttr()[6]):
desc = info.GetFuncDesc(member_index)
names = info.GetNames(desc[0])
if names[0] not in wanted:
continue
found.append({
"name": names[0],
"dispid": desc[0],
"parameters": list(names[1:]),
"argument_types": [list(arg[:2]) for arg in desc[2]],
"return_type": list(desc[8][:2]),
})
if found:
interfaces[name] = found
return {
"guid": str(attr[0]),
"major_version": attr[3],
"minor_version": attr[4],
"type_count": library.GetTypeInfoCount(),
"interfaces": interfaces,
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--wrapper", type=Path, default=DEFAULT_WRAPPER)
parser.add_argument("--tlb", type=Path, default=DEFAULT_TLB)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
wrapper_text = args.wrapper.read_text(encoding="utf-8")
result = {
"format_version": 1,
"mode": "offline_installed_typelib_and_wrapper_comparison",
"attached_to_viewdraw": False,
"mutation_attempted": False,
"wrapper": {"path": str(args.wrapper), "sha256": sha256(args.wrapper)},
"typelib": {"path": str(args.tlb), "exists": args.tlb.is_file()},
"saved_wrapper_candidates": extract(wrapper_text),
}
if args.tlb.is_file():
result["typelib"]["sha256"] = sha256(args.tlb)
result["typelib"]["size"] = args.tlb.stat().st_size
result["installed_typelib"] = inspect_installed_typelib(args.tlb)
result["wrapper_matches_installed_version"] = (
result["saved_wrapper_candidates"]["declared_version"] == {
"major": result["installed_typelib"]["major_version"],
"minor": result["installed_typelib"]["minor_version"],
}
)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2, ensure_ascii=True) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2, ensure_ascii=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())