fix: bridge long CAD project paths and normalize COM path getters

This commit is contained in:
阿白叔 committed 2026-10-15 17:09:56 +08:00
1 parent e655797e32
commit ff06f86f62
9 files changed
+242 -10

No files matched your search

@@ -66,3 +66,12 @@ def verify_application(app, binding=None, *, require_view=True):
if not handle or window_pid(handle) != binding.pid:
raise ValueError('CAD view PID does not match its owned session')
return binding
def project_file_path(app):
"""COM type libraries expose this getter as either a property or a method."""
value = app.GetProjectData().GetProjectFilePath
value = value() if callable(value) else value
if not isinstance(value, str):
raise ValueError('CAD returned an invalid project path')
return value
@@ -8,7 +8,7 @@ import sys
import time
from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
from .isolated_desktop import PrivateDesktop
from .worker_monitor import WorkerMonitorError
@@ -227,7 +227,7 @@ def native_action(action, evidence, expected_pid):
# ActiveViewHandle can retain a destroyed/reused HWND after closing
# the last project. The private ROT/GUID binds this empty instance.
verify_application(app, binding, require_view=False)
if app.GetProjectData().GetProjectFilePath():
if project_file_path(app):
raise ValueError('owned CAD still has a project open; no implicit save or discard')
app.Quit()
else:
@@ -3,6 +3,7 @@ from __future__ import annotations
import atexit
import ctypes
import csv
import hashlib
import os
from pathlib import Path
@@ -87,6 +88,8 @@ atexit.register(cleanup_worker_aliases)
def worker_paths(script: Path, root: Path) -> tuple[str, str]:
if os.name == 'nt':
_prepare_project_access(root)
if os.name != 'nt' or _fits(root):
return str(script), str(root)
canonical = root.resolve(strict=True)
@@ -99,3 +102,55 @@ def worker_paths(script: Path, root: Path) -> tuple[str, str]:
raise TaskCenterError('quick_run_path_length',
f'无法建立长路径兼容入口:{error};尚未启动 CAD 操作。') from error
return str(alias / script.name), str(alias)
def _prepare_project_access(root: Path):
"""Keep command identities canonical while giving legacy CAD short entry paths."""
command = root / 'command.tsv'
if not command.is_file():
return
rows = []
with command.open(encoding='utf-8-sig', newline='') as stream:
for row in csv.DictReader(stream, delimiter='\t'):
value = row.get('project_path')
if not value:
continue
project = Path(value).resolve(strict=False)
if (_fits(project.parent) and len(str(project)) < 260) or not project.is_file():
continue
short = _short_path(project)
if short and _fits(Path(short).parent) and len(short) < 260:
access = Path(short)
else:
access = _aliases.alias(project.parent) / project.name
if not _fits(access.parent) or len(str(access)) >= 260 or access.resolve(strict=True) != project:
raise TaskCenterError('quick_run_path_length', '工程短路径入口不能与原工程身份对应,未启动 CAD 操作。')
pair = (str(project), str(access))
if pair not in rows:
rows.append(pair)
target = root / 'project-access.tsv'
if rows or target.exists():
temporary = target.with_suffix('.tmp')
with temporary.open('w', encoding='utf-8', newline='') as stream:
writer = csv.writer(stream, delimiter='\t', lineterminator='\n')
writer.writerow(('project_path', 'access_path'))
writer.writerows(rows)
temporary.replace(target)
def validate_project_access(root: Path):
"""Reject disappeared/redirected entry paths before and after a native worker."""
target = Path(root) / 'project-access.tsv'
if not target.is_file():
return
with target.open(encoding='utf-8-sig', newline='') as stream:
reader = csv.DictReader(stream, delimiter='\t')
if reader.fieldnames != ['project_path', 'access_path']:
raise TaskCenterError('target_identity', '工程路径入口清单格式已改变')
for row in reader:
try:
same = Path(row['access_path']).resolve(strict=True) == Path(row['project_path']).resolve(strict=True)
except (OSError, ValueError, KeyError):
same = False
if not same:
raise TaskCenterError('target_identity', '工程短路径入口已失效或指向其他工程,拒绝使用采集或替换结果')
@@ -205,7 +205,7 @@ def attach():
api = win32com.client.gencache.EnsureModule(
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
from .cad_identity import verify_application
from .cad_identity import verify_application, project_file_path
verify_application(app)
return app, api
@@ -228,9 +228,9 @@ def components_on_sheet(app, api):
def check_active_context(app, metadata):
from .cad_identity import verify_application
from .cad_identity import verify_application, project_file_path
verify_application(app)
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
if Path(project_file_path(app)).resolve() != Path(metadata[1]).resolve():
raise ValueError("Active project changed")
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
raise ValueError("Active sheet changed")
@@ -1707,9 +1707,13 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]:
from .isolated_cad import run_isolated_process
from .legacy_paths import validate_project_access
return run_isolated_process(command, timeout,
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
validate_project_access(Path(command[3]))
result = run_isolated_process(command, timeout,
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
validate_project_access(Path(command[3]))
return result
def _log_text(value: str) -> str: