Files
mentor-export/mentorexport/environment.py
T

179 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Discover locally installed Mentor tools without starting Designer."""
from pathlib import Path
import os
import re
from .core import sha256
TOOL_PATHS = {
"ascii": "iCDB/win32/bin/icdb2ascii.exe",
"csv": "iCDB/win32/bin/icdb2csv.exe",
"keyin": "wv/win32/bin/KeyinNetlist.exe",
"rinf": "wv/win32/bin/RinfNetlist.exe",
"edif": "wv/win32/bin/edifExporter.exe",
"wir": "wv/win32/bin/icdb2wir.exe",
"pxr": "wv/win32/bin/icdb2pxr.exe",
"constraints_xml": "ces/win32/bin/cons2xml.exe",
}
VALIDATED_DLLS = {
"PartsDB40.dll": "f24d44eaa13f28550317711df6a6241e227ae56805baa73c8f3020bde513ad0d",
"CellDB40.dll": "e3fb93a0b5e5d2d027a82f71d1ee13d497598f709ced54c9145a781af6a54d26",
}
def _registry_module(progid):
if os.name != "nt":
return None
import winreg
try:
view = winreg.KEY_READ | winreg.KEY_WOW64_32KEY
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, progid + r"\CLSID", 0, view) as key:
clsid = winreg.QueryValue(key, None)
for server in ("InprocServer32", "LocalServer32"):
try:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID\\" + clsid + "\\" + server, 0, view) as key:
command = os.path.expandvars(winreg.QueryValue(key, None)).strip()
match = re.match(r'^"([^"]+)"', command) or re.match(r"^(.+?\.(?:dll|exe|ocx))(?:\s|$)", command, re.I)
return str(Path(match[1] if match else command).resolve())
except OSError:
continue
except OSError:
pass
return None
def _root_from_path(path):
path = Path(os.path.expandvars(str(path))).expanduser().resolve()
for candidate in (path, *path.parents):
if (candidate / TOOL_PATHS["ascii"]).is_file():
return candidate
if (path / "SDD_HOME").is_dir():
return path / "SDD_HOME"
return path
def inspect_installation(path):
root = _root_from_path(path)
tools = {name: str(root / relative) for name, relative in TOOL_PATHS.items() if (root / relative).is_file()}
version = root.parent.name
file_version = None
if os.name == "nt":
try:
import win32api
info = win32api.GetFileVersionInfo(str(root / "wv/win32/bin/viewdraw.exe"), "\\")
ms, ls = info["FileVersionMS"], info["FileVersionLS"]
file_version = f"{ms >> 16}.{ms & 65535}.{ls >> 16}.{ls & 65535}"
except Exception:
pass
hashes = {}
for name in VALIDATED_DLLS:
file = root / "common/win32/lib" / name
if file.is_file():
hashes[name] = sha256(file)
com = {}
for name, progid in (("cms", "CMS.CeObjectDefsICDB"), ("central", "CentralLibSvr.LibPart.1")):
registered = _registry_module(progid)
matches = bool(registered and Path(registered).is_relative_to(root))
com[name] = {"registered_path": registered, "matches": matches}
return {"root": str(root), "version": version, "file_version": file_version, "tools": tools,
"native_compatible": hashes == VALIDATED_DLLS, "dll_hashes": hashes, "com": com}
def _registry_candidates():
if os.name != "nt":
return []
import winreg
paths = []
for progid in ("ViewDraw.Application", "ViewDraw.Application.1", "CMS.CeObjectDefsICDB", "CentralLibSvr.LibPart.1"):
value = _registry_module(progid)
if value:
paths.append(value)
for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
for view in (winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
try:
with winreg.OpenKey(hive, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, winreg.KEY_READ | view) as parent:
for index in range(winreg.QueryInfoKey(parent)[0]):
try:
with winreg.OpenKey(parent, winreg.EnumKey(parent, index)) as key:
display = str(winreg.QueryValueEx(key, "DisplayName")[0])
if re.search(r"mentor|xpedition|expedition|dxdesigner", display, re.I):
value = str(winreg.QueryValueEx(key, "InstallLocation")[0])
if value:
paths.append(value)
except OSError:
continue
except OSError:
continue
return paths
def _conventional_candidates():
candidates = []
for drive in "CDEFG":
for name in ("Mentor", "MentorGraphics", "Siemens", "Program Files/MentorGraphics", "Program Files/Siemens", "Program Files (x86)/MentorGraphics"):
root = Path(f"{drive}:/{name}")
if not root.is_dir():
continue
seen = 0
for folder, names, files in os.walk(root, followlinks=False):
path = Path(folder)
seen += 1
if path.name.casefold() == "sdd_home":
candidates.append(path)
names[:] = []
elif len(path.relative_to(root).parts) >= 3 or seen >= 500:
names[:] = []
else:
names[:] = [name for name in names if not (path / name).is_junction() and not (path / name).is_symlink()]
return candidates
def discover_installations(explicit=None, cached=None):
if explicit:
candidate = inspect_installation(explicit)
if "ascii" not in candidate["tools"]:
raise ValueError("该目录没有可用的 icdb2ascii.exe,请选择完整 Mentor 的 SDD_HOME:" + str(explicit))
return [candidate]
values = [path for path in (cached, os.environ.get("SDD_HOME")) if path]
values.extend(_registry_candidates())
values.extend(_conventional_candidates())
results, seen = [], set()
for value in values:
try:
root = _root_from_path(value)
identity = os.path.normcase(str(root))
if identity in seen:
continue
seen.add(identity)
if not (root / TOOL_PATHS["ascii"]).is_file():
continue
results.append(inspect_installation(root))
except (OSError, ValueError):
continue
return results
def preflight_installation(installation, log_dir, runner=None):
"""Execute a harmless help request with the same private process boundary."""
from .exports import _environment, _run
from .core import read_text
runner = runner or _run
log_dir = Path(log_dir)
log_dir.parent.mkdir(parents=True, exist_ok=True)
log_dir = log_dir.parent.resolve() / log_dir.name
tool = installation.get("tools", {}).get("ascii")
if not tool:
return {"status": "failed", "reason": "没有 icdb2ascii.exe"}
result = runner([tool, "-help"], log_dir.parent, _environment(installation), log_dir,
stop_event=None, timeout=10)
text = ""
for name in ("stdout.txt", "stderr.txt"):
path = log_dir / name
if path.is_file():
text += read_text(path)
valid = (result.get("exit_code") == 0 and not result.get("timed_out")
and not result.get("error") and not result.get("cleanup_uncertain")
and not result.get("cleanup", {}).get("errors")
and "iCDB2Ascii" in text and "-snap=" in text and "-offline" in text)
return {"status": "success" if valid else "failed", "run": result, "log_dir": str(log_dir),
"reason": "" if valid else "Mentor 工具无法正常显示预期帮助;检查安装/DLL,详见预检日志"}