commit e422ca8b2a027f75025c756efbbb08a69c71033d Author: 阿白叔 <11794527+absfan@user.noreply.gitee.com> Date: Sat Oct 10 17:10:32 2026 +0800 feat: add complete yiyezhqiu productivity suite diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5375302 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.coverage +htmlcov/ +.venv/ +venv/ +*.egg-info/ +build/ +dist/ +release/ +.zcode/ diff --git a/.zcodeignore b/.zcodeignore new file mode 100644 index 0000000..168314b --- /dev/null +++ b/.zcodeignore @@ -0,0 +1,37 @@ +# ZCode 工作区文件搜索忽略规则(.zcodeignore) +# 语法与 .gitignore 一致,只影响 ZCode 的 @ 文件候选 / Command Center / 文件树搜索, +# 不影响文件树浏览、上传或 Agent 文件访问。 +# 修改 .gitignore 不会自动同步到本文件;可在设置页「从 .gitignore 同步」。 + + +# ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)===== +.git/ +.hg/ +.svn/ +node_modules/ +bower_components/ +jspm_packages/ +__pycache__/ +site-packages/ +venv/ +coverage/ +htmlcov/ +lcov-report/ +cmakefiles/ +cmake-build-*/ +bazel-*/ +pods/ +deriveddata/ +storybook-static/ +playwright-report/ +test-results/ +allure-results/ +allure-report/ +cdk.out/ +*.egg-info/ +*.dist-info/ +eggs/ +pip-wheel-metadata/ +wheels/ +# ----- ↑ 以上为 ZCode 默认排除规则(自定义规则请写在本行下方,不会被同步/恢复改动)----- +# 自定义规则写在下方(本行提示可删除) diff --git a/docs/superpowers/plans/2026-09-01-dxdesigner-795-portable-release.md b/docs/superpowers/plans/2026-09-01-dxdesigner-795-portable-release.md new file mode 100644 index 0000000..f917f65 --- /dev/null +++ b/docs/superpowers/plans/2026-09-01-dxdesigner-795-portable-release.md @@ -0,0 +1,569 @@ +# DxDesigner 7.9.5 Portable Offline Release Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Deliver one portable Windows 11 x64 ZIP that runs the automatic-reference-designator tool offline without a system Python installation and integrates through a root-level `MenuAdd.vbs` imported by DxDesigner 7.9.5. + +**Architecture:** DxDesigner owns all schematic API access through ASCII-only VBS. The bridge exports a versioned UTF-8 snapshot, starts a PyInstaller `onedir` executable beside the scripts, and applies only a validated result schedule after creating a backup. Python/PySide6 owns the UI, planning, validation, immutable result generation, and user-local history. + +**Tech Stack:** Python 3.12, PySide6 Essentials 6.x, qtawesome 1.x, PyInstaller 6.x, VBScript, PowerShell 5.1+, pytest, pytest-qt + +**Spec:** `docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md` + +## Global Constraints + +- Supported schematic integration baseline: DxDesigner/Expedition Enterprise 7.9.5 only. +- Supported release operating system and architecture: Windows 11 x64. +- The target computer requires no Python installation and no network access. +- The release is one portable ZIP; it uses no installer, registry entry, environment variable, administrator privilege, newer Xpedition add-in framework, copied newer-release DLL, COM re-registration, or project-format upgrade. +- The user imports only the root `MenuAdd.vbs` through `Settings -> Run at Startup -> Scripts`. +- `MenuAdd.vbs` resolves bundled files from its own loaded location; there is no fixed drive path or `DXTOOLS_HOME` dependency. +- Every DxDesigner API call remains in VBS; Python never attaches to `ViewDraw.Application` or another DxDesigner COM server. +- Every VBS source is ASCII-only; Chinese captions and messages are assembled with `ChrW`. +- Run mailboxes, backups, history, logs, and preferences live under `%LOCALAPPDATA%\DxProductivity`. +- A live 7.9.5 acceptance failure blocks the 7.9.5 compatibility claim even when all mocked tests pass. + +--- + +## File Structure + +- `src/dx_productivity/bridge/protocol.py`: read/write the versioned snapshot, apply request, schedule, and apply status. +- `src/dx_productivity/bridge/launcher.py`: dispatch packaged probe and UI modes without relying on `py.exe`. +- `src/dx_productivity/ui/refdes_controller.py`: publish backup metadata before the schedule-ready signal. +- `integration/dxdesigner795/BridgeCommon.vbs`: focused ASCII-only UTF-8, JSON, TSV, and atomic-file helpers, packaged under `_runtime/vbs`. +- `integration/dxdesigner795/MenuAdd.vbs`: idempotent 7.9.5 menu registration and portable-root discovery. +- `integration/dxdesigner795/RefDesBridge.vbs`: snapshot export, mailbox loop, stale-state check, write-back, verification, and rollback. +- `integration/dxdesigner795/CompatibilityProbe.vbs`: read-only evidence for menu route, script-path source, API fields, and message-pump method. +- `packaging/DxDesignerTools.spec`: PyInstaller `onedir` definition with `_runtime` contents directory. +- `packaging/build_release.ps1`: reproducible x64 build, portable layout assembly, ZIP creation, and SHA-256 manifest. +- `tests/bridge/`, `tests/integration/`, `tests/vbs/`, `tests/packaging/`: contract, static-safety, mocked transaction, and built-artifact tests. +- `docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx`: offline user guide matching the portable workflow. +- `docs/testing/dxdesigner-795-live.md`: target-machine acceptance record. + +--- + +### Task 1: Complete the Transaction Protocol and Packaged Launcher + +**Files:** +- Create: `src/dx_productivity/bridge/launcher.py` +- Modify: `src/dx_productivity/bridge/protocol.py` +- Modify: `src/dx_productivity/domain/models.py` +- Modify: `src/dx_productivity/ui/refdes_controller.py` +- Modify: `src/dx_productivity/ui/app.py` +- Modify: `src/dx_productivity/__main__.py` +- Test: `tests/bridge/test_protocol.py` +- Test: `tests/bridge/test_launcher.py` +- Test: `tests/ui/test_refdes_controller.py` + +**Interfaces:** +- Consumes: `DesignSnapshot`, `AnnotationPlan`, `RunPaths`, `probe_host.main`, and command-line arguments. +- Produces: `ApplyRequest`, `write_apply_request(path, request)`, `load_apply_request(path)`, `launcher.main(argv) -> int`, and `RunPaths.apply_request`. +- `ApplyRequest` fields are `format_version: int`, `run_id: str`, `snapshot_id: str`, `backup_path: Path`, and `schedule_sha256: str`. + +- [ ] **Step 1: Write failing apply-request protocol tests** + +```python +def test_apply_request_round_trip(tmp_path: Path) -> None: + request = ApplyRequest(1, "run-a", "snapshot-a", tmp_path / "备份.json", "a" * 64) + path = tmp_path / "apply-request.json" + write_apply_request(path, request) + assert load_apply_request(path) == request + + +def test_run_paths_exposes_apply_request(run_paths: RunPaths) -> None: + assert run_paths.apply_request == run_paths.root / "apply-request.json" +``` + +- [ ] **Step 2: Run the focused protocol tests and confirm failure** + +Run: `py -3.12 -m pytest tests/bridge/test_protocol.py -v` + +Expected: FAIL because `ApplyRequest`, its serializers, and `RunPaths.apply_request` do not exist. + +- [ ] **Step 3: Implement immutable apply metadata and strict validation** + +Add `ApplyRequest` to `models.py`. Add an `apply_request` property to `RunPaths` so existing positional construction remains compatible. In `protocol.py`, atomically write UTF-8 JSON with `ensure_ascii=False`, require `format_version == 1`, require matching nonempty run/snapshot IDs, require an absolute nonempty backup path, and require a lowercase 64-character hexadecimal SHA-256. + +Add `schedule_sha256(schedule: tuple[ApplyStep, ...]) -> str` using the exact UTF-8 TSV bytes produced by `write_schedule`. One canonical `_schedule_text` helper must feed both hashing and file output. + +- [ ] **Step 4: Write failing publication-order and launcher-dispatch tests** + +```python +def test_apply_publishes_metadata_before_result(controller, monkeypatch): + calls = [] + monkeypatch.setattr(protocol, "write_apply_request", lambda *args: calls.append("metadata")) + monkeypatch.setattr(protocol, "write_schedule", lambda *args: calls.append("result")) + controller.apply() + assert calls == ["metadata", "result"] + + +def test_launcher_dispatches_probe_without_starting_qt(monkeypatch, tmp_path): + called = [] + monkeypatch.setattr(launcher, "probe_main", lambda argv: called.append(argv) or 0) + assert launcher.main(["probe", "--output", str(tmp_path / "probe.json")]) == 0 + assert called[0][0:2] == ["--output", str(tmp_path / "probe.json")] +``` + +- [ ] **Step 5: Run the focused tests and confirm failure** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/bridge/test_launcher.py tests/ui/test_refdes_controller.py -v` + +Expected: FAIL because the packaged launcher and ordered apply metadata publication are absent. + +- [ ] **Step 6: Implement launcher modes and publication order** + +`launcher.main` accepts exactly two modes: + +- `probe ...` delegates remaining arguments to `probe_host.main` without creating `QApplication`; +- `ui --request ` delegates to `ui.app.main`. + +No mode defaults to `ui` for direct user launches. The UI parser also accepts the packaging-only `--smoke-test-ms ` option; after the window is shown it schedules `QApplication.quit` with `QTimer.singleShot`, while normal launches omit the option and remain interactive. Update `__main__.py` to call `launcher.main`. In `RefDesController.apply`, write the backup, compute the schedule digest, atomically publish `apply-request.json`, then publish `result.tsv` last as the bridge-ready signal. + +- [ ] **Step 7: Run focused and full Python tests** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/bridge tests/ui/test_refdes_controller.py -v` + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 8: Commit the transaction protocol** + +```powershell +git add src/dx_productivity/bridge src/dx_productivity/domain/models.py src/dx_productivity/ui/refdes_controller.py src/dx_productivity/ui/app.py src/dx_productivity/__main__.py tests/bridge tests/ui/test_refdes_controller.py +git commit -m "feat: complete packaged bridge transaction protocol" +``` + +### Task 2: Add Portable Script Discovery, Shared VBS Helpers, and Menu Registration + +**Files:** +- Create: `integration/dxdesigner795/BridgeCommon.vbs` +- Create: `integration/dxdesigner795/MenuAdd.vbs` +- Create: `tests/vbs/test_bridge_common.vbs` +- Create: `tests/integration/test_menu_script.py` +- Modify: `integration/dxdesigner795/CompatibilityProbe.vbs` +- Modify: `tests/integration/test_compatibility_probe.py` + +**Interfaces:** +- Consumes: the loaded startup-script path exposed by the DxDesigner 7.9.5 host and root siblings `RefDesBridge.vbs` and `DxDesignerTools.exe`. +- Produces: menu-local `DxToolsResolveRoot()`, shared `DxToolsQuote(value)`, `DxToolsJson(value)`, `DxToolsReadUtf8(path)`, `DxToolsWriteUtf8Atomic(path, text)`, and the named menu action `DxToolsRunRefDes`. + +- [ ] **Step 1: Write failing static portable-root and menu tests** + +```python +def test_menu_is_ascii_portable_and_uses_795_menu_bar(): + text = Path("integration/dxdesigner795/MenuAdd.vbs").read_text("ascii") + assert 'CommandBars("Sheet Menu Bar")' in text + assert "DxToolsResolveRoot" in text + assert "DXTOOLS_HOME" not in text + assert "D:\\" not in text + assert "WScript.Shell" in text + assert text.isascii() + + +def test_probe_records_script_path_source(): + text = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text("ascii") + assert '"script_path_source"' in text + assert '"portable_root_valid"' in text +``` + +- [ ] **Step 2: Run the menu/probe tests and confirm failure** + +Run: `py -3.12 -m pytest tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py -v` + +Expected: FAIL because the release menu and self-location evidence are absent and the probe still depends on `DXTOOLS_HOME` and `py -3.12`. + +- [ ] **Step 3: Write cscript tests for pure VBS helpers** + +`tests/vbs/test_bridge_common.vbs` loads `BridgeCommon.vbs` and asserts JSON escaping for quote, slash, CR, LF, and tab; quoting of a path containing Chinese characters and spaces; UTF-8 round-trip; atomic replacement; and rejection of a malformed five-field schedule row. + +Run: `cscript //nologo tests\vbs\test_bridge_common.vbs` + +Expected: FAIL because `BridgeCommon.vbs` does not exist. + +- [ ] **Step 4: Implement isolated ASCII-only helpers** + +`BridgeCommon.vbs` keeps `On Error Resume Next` inside individual compatibility probes only and restores normal error handling immediately. UTF-8 functions use `ADODB.Stream`; atomic output writes a same-directory `.tmp` and then replaces the destination. All command arguments use one double-quote helper. It is loaded from `_runtime\vbs\BridgeCommon.vbs` by `MenuAdd.vbs` before either root bridge script is evaluated. + +`DxToolsResolveRoot` tests these loaded-script full-name candidates in order, with each attempt wrapped in its own immediate `Err` check: `WScript.ScriptFullName`, `Scripting.CurrentScriptFullName`, and `Scripting.ScriptFullName`. The compatibility probe records the winning property name or an empty value. A candidate is accepted only when both sibling files exist: + +```text +\RefDesBridge.vbs +\DxDesignerTools.exe +``` + +It does not accept the current working directory, recursively scan drives, or consult an environment variable. If no candidate validates, it returns an empty string and the menu displays a concise path error without adding a broken command. + +- [ ] **Step 5: Implement idempotent menu registration** + +`MenuAdd.vbs` contains the small self-location resolver because it must discover the root before shared helpers can be loaded. It removes only an existing top-level menu with the exact suite caption before adding one replacement to `CommandBars("Sheet Menu Bar")`; it does not depend on an unproven `Tag` property. It adds `自动位号`, `兼容性检测`, and `打开使用说明` entries. Captions and errors use `ChrW`; `OnAction` routes invoke named procedures defined in the imported script so the in-process DxDesigner objects remain available. The named procedures load `_runtime\vbs\BridgeCommon.vbs` and then the root bridge/probe source with `ExecuteGlobal`, and call their explicit entry procedure; they never run a second script host process. + +- [ ] **Step 6: Make the compatibility probe launch the bundled executable** + +Replace both `py -3.12 -m dx_productivity.bridge.probe_host` commands with the root sibling `DxDesignerTools.exe probe ...`. Refactor the probe so loading it defines `DxToolsRunCompatibilityProbe` without creating another menu. Add `script_path_source`, resolved absolute script path, `portable_root_valid`, executable existence, and VBS yield method to `compatibility.json`. The probe remains read-only. + +- [ ] **Step 7: Run VBS, static, and Python tests** + +Run: `cscript //nologo tests\vbs\test_bridge_common.vbs` + +Run: `py -3.12 -m pytest tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py -v` + +Expected: all tests pass; `rg -n "DXTOOLS_HOME|py -3.12|D:\\NET_CHECK" integration/dxdesigner795` returns no release-script match. + +- [ ] **Step 8: Commit portable script discovery and menu registration** + +```powershell +git add integration/dxdesigner795 tests/vbs tests/integration/test_menu_script.py tests/integration/test_compatibility_probe.py +git commit -m "feat: add self-locating DxDesigner 7.9.5 menu" +``` + +### Task 3: Implement DxDesigner Snapshot, Write-Back, Verification, and Rollback + +**Files:** +- Create: `integration/dxdesigner795/RefDesBridge.vbs` +- Create: `tests/integration/test_vbs_bridge.py` +- Create: `tests/integration/mock_bridge.py` +- Create: `tests/integration/test_end_to_end.py` +- Modify: `integration/dxdesigner795/BridgeCommon.vbs` + +**Interfaces:** +- Consumes: root `DxDesignerTools.exe`, `RunPaths` mailbox names, the probe-confirmed 7.9.5 component properties, `apply-request.json`, and `result.tsv`. +- Produces: a version-1 `request.json`, locate handling, ordered reference-designator writes, `apply-status.json`, full-design verification, and verified rollback. + +- [ ] **Step 1: Write failing static bridge-safety tests** + +```python +def test_bridge_has_required_transaction_stages(): + text = Path("integration/dxdesigner795/RefDesBridge.vbs").read_text("ascii") + for name in ( + "DxExportSnapshot", "DxLaunchUi", "DxPreflightApply", + "DxApplySchedule", "DxVerifyDesign", "DxRollback", + ): + assert f"Sub {name}" in text or f"Function {name}" in text + assert "ViewDraw.Application" not in text + assert "GetActiveObject" not in text + assert "DXTOOLS_HOME" not in text + assert text.isascii() +``` + +- [ ] **Step 2: Run the static test and confirm failure** + +Run: `py -3.12 -m pytest tests/integration/test_vbs_bridge.py -v` + +Expected: FAIL because `RefDesBridge.vbs` does not exist. + +- [ ] **Step 3: Implement snapshot export with an in-memory object map** + +Create a unique `%LOCALAPPDATA%\DxProductivity\runs\-` directory. Enumerate the full design through `Application.GetProjectData()` and `Application.DesignComponents`, assign contiguous IDs `c000001`, retain each component in a `Scripting.Dictionary`, and record selection/current-sheet membership without changing the design. + +Write every field required by `ComponentRecord`. A missing UID uses full path; a missing symbol default becomes JSON `null`; an unavailable lock flag becomes `false`. Missing both UID and full path aborts before launching the UI. Coordinate values use locale-independent decimal points. + +- [ ] **Step 4: Implement the packaged UI launch and mailbox loop** + +Launch exactly: + +```text +"\DxDesignerTools.exe" ui --request "\request.json" +``` + +Use `WScript.Shell.Exec`, retain the object dictionary, and pump the first method proven by the compatibility probe. Consume atomically published `locate.tsv` once and select/zoom only the mapped component. Treat `result.tsv` as ready only when `apply-request.json` also exists. Closing the UI without a result leaves the design unchanged. + +- [ ] **Step 5: Implement strict preflight and ordered write-back** + +Before the first write, verify active design identity, snapshot ID, run ID, component count in scope, every `bridge_id`, every `expected_refdes`, the absolute backup file existence, and the SHA-256 of the exact result TSV bytes. Reject unknown IDs, noncontiguous sequences, more than two steps per ID, illegal control characters, and mismatched expected-current chains. + +Apply rows in sequence. After each assignment, immediately read `comp.Refdes` and require a case-insensitive match. After all rows, re-enumerate the full design, verify each final value, and reject duplicate formal reference designators. + +- [ ] **Step 6: Implement rollback and machine-readable status** + +On any write or verification failure, restore every touched object to the original value stored in the snapshot, then re-read every restored value. Atomically write `apply-status.json` with state `applied`, `rolled-back`, or `rollback-failed`, including `run_id`, changed count, backup path, failing sequence, error text, and rollback state. Never suppress an assignment error or report success before full-design verification. + +- [ ] **Step 7: Build a mocked bridge transaction harness** + +`MockBridge` loads a real fixture snapshot, waits for a real controller result, validates the same sequence/current-value/digest invariants as VBS, applies to an in-memory map, and can inject a stale value or assignment failure. Tests assert successful fill-only apply, cycle schedules, cancel-without-result, stale-state rejection, verified rollback, and rollback failure status parsing. + +- [ ] **Step 8: Run transaction and full regression tests** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/integration/test_vbs_bridge.py tests/integration/test_end_to_end.py -v` + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 9: Commit the safe write-back bridge** + +```powershell +git add integration/dxdesigner795/BridgeCommon.vbs integration/dxdesigner795/RefDesBridge.vbs tests/integration +git commit -m "feat: add verified refdes write-back and rollback" +``` + +### Task 4: Add Operation History and Verified Restore + +**Files:** +- Create: `src/dx_productivity/domain/restore.py` +- Create: `src/dx_productivity/ui/history_page.py` +- Create: `src/dx_productivity/ui/history_controller.py` +- Create: `tests/domain/test_restore.py` +- Create: `tests/ui/test_history_page.py` +- Create: `tests/ui/test_history_controller.py` +- Modify: `src/dx_productivity/ui/app.py` +- Modify: `src/dx_productivity/ui/main_window.py` + +**Interfaces:** +- Consumes: current `DesignSnapshot`, `RunStore.list_history`, `RunStore.build_restore_settings`, `build_apply_schedule`, `write_apply_request`, and `write_schedule`. +- Produces: `build_restore_plan(snapshot, request) -> AnnotationPlan`, `HistoryPage`, and `HistoryController.restore_latest() -> Path`. + +- [ ] **Step 1: Write failing restore-plan tests** + +```python +def test_restore_plan_requires_current_values_to_match(snapshot, restore_request): + plan = build_restore_plan(snapshot, restore_request) + assert plan.can_apply + assert plan.rows[0].old_refdes == "R1" + assert plan.rows[0].new_refdes == "R?" + + +def test_restore_plan_blocks_stale_component(snapshot, restore_request): + stale = replace(snapshot, components=(replace(snapshot.components[0], refdes="R9"),)) + plan = build_restore_plan(stale, restore_request) + assert not plan.can_apply + assert any(issue.code == "restore-stale" for issue in plan.issues) +``` + +- [ ] **Step 2: Run restore domain tests and confirm failure** + +Run: `py -3.12 -m pytest tests/domain/test_restore.py -v` + +Expected: FAIL because `build_restore_plan` does not exist. + +- [ ] **Step 3: Implement identity-safe restore planning** + +Match each restore item first by nonempty stable UID, then by exact hierarchical full path. Require one unambiguous component, require its current reference designator to equal `expected_refdes` case-insensitively, and reject collisions against every component outside the restore set. Convert validated items to `PlanRow` values and call `build_apply_schedule`, including placeholder cycle breaks. Return blocking issues `restore-missing`, `restore-ambiguous`, `restore-stale`, or `restore-collision` instead of guessing. + +- [ ] **Step 4: Write failing history UI/controller tests** + +```python +def test_history_page_shows_latest_entry_first(qtbot, entries): + page = HistoryPage() + qtbot.addWidget(page) + page.set_entries(entries) + assert page.row_run_id(0) == entries[0].run_id + assert page.restore_button.isEnabled() + + +def test_restore_creates_second_backup_before_result(controller, monkeypatch): + calls = [] + monkeypatch.setattr(controller.run_store, "write_backup", lambda *args: calls.append("backup") or Path("backup.json")) + monkeypatch.setattr(protocol, "write_apply_request", lambda *args: calls.append("metadata")) + monkeypatch.setattr(protocol, "write_schedule", lambda *args: calls.append("result")) + controller.restore_latest() + assert calls == ["backup", "metadata", "result"] +``` + +- [ ] **Step 5: Run history UI tests and confirm failure** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_history_page.py tests/ui/test_history_controller.py -v` + +Expected: FAIL because the history page and controller do not exist. + +- [ ] **Step 6: Implement the history page and restore controller** + +Replace navigation page index 6 with an unframed history table showing time, operation state, changed count, design, and backup path. Provide a `恢复上次位号` command with a confirmation dialog naming the affected count and backup timestamp. Disable it when no verified applicable entry exists. + +`HistoryController` filters history by the active design, builds the restore plan against the current full snapshot, creates a fresh backup of the current values, writes apply metadata, and publishes `result.tsv` last. It polls the same `apply-status.json` contract as automatic annotation and refreshes history exactly once after success or verified rollback. + +- [ ] **Step 7: Run focused and full UI regression tests** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/domain/test_restore.py tests/ui/test_history_page.py tests/ui/test_history_controller.py -v` + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 8: Commit operation history and restore** + +```powershell +git add src/dx_productivity/domain/restore.py src/dx_productivity/ui/history_page.py src/dx_productivity/ui/history_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py tests/domain/test_restore.py tests/ui/test_history_page.py tests/ui/test_history_controller.py +git commit -m "feat: add verified annotation restore workflow" +``` + +### Task 5: Build the Portable PyInstaller Release and Offline ZIP + +**Files:** +- Create: `packaging/DxDesignerTools.spec` +- Create: `packaging/build_release.ps1` +- Create: `tests/packaging/test_release_definition.py` +- Create: `tests/packaging/test_built_release.py` +- Modify: `pyproject.toml` +- Modify: `.gitignore` + +**Interfaces:** +- Consumes: Python 3.12 x64, PyInstaller 6.x, application launcher, root VBS scripts, the DOCX guide, and application resources. +- Produces: `release/DxDesigner效率工具/`, `release/DxDesigner效率工具_Win11_x64.zip`, and `release/SHA256SUMS.txt`. The internal VBS helper is stored at `_runtime/vbs/BridgeCommon.vbs`; only the user-importable and directly dispatched scripts remain at the root. + +- [ ] **Step 1: Write failing release-definition tests** + +```python +def test_spec_is_onedir_with_runtime_subdirectory(): + text = Path("packaging/DxDesignerTools.spec").read_text("utf-8") + assert "COLLECT(" in text + assert 'contents_directory="_runtime"' in text + assert "onefile" not in text.lower() + + +def test_build_script_copies_only_importable_root_scripts(): + text = Path("packaging/build_release.ps1").read_text("utf-8") + assert "MenuAdd.vbs" in text + assert "RefDesBridge.vbs" in text + assert "CompatibilityProbe.vbs" in text + assert "BridgeCommon.vbs" in text + assert "_runtime\\vbs" in text + assert "Compress-Archive" in text +``` + +- [ ] **Step 2: Run release-definition tests and confirm failure** + +Run: `py -3.12 -m pytest tests/packaging/test_release_definition.py -v` + +Expected: FAIL because packaging files do not exist. + +- [ ] **Step 3: Pin the build dependency and implement the spec** + +Add `pyinstaller>=6.11,<7` to the `build` optional dependency group. `DxDesignerTools.spec` targets console-disabled Windows x64 `onedir`, uses `src/dx_productivity/bridge/launcher.py` as entry point, names the executable `DxDesignerTools.exe`, and sets `contents_directory="_runtime"`. Collect the PySide6 platform plug-in, image-format plug-ins, styles, and qtawesome font data explicitly. + +- [ ] **Step 4: Implement a deterministic PowerShell release build** + +`build_release.ps1` verifies 64-bit Python 3.12, removes only the repository-owned `build/pyinstaller`, `dist/DxDesignerTools`, and `release/DxDesigner效率工具` paths after resolving them under the worktree, runs PyInstaller, assembles the root VBS scripts and `docs` directory, checks every expected file, creates the ZIP, and writes SHA-256 hashes. It must not invoke pip, download a package, or modify the target computer. + +- [ ] **Step 5: Install build dependencies on the build computer and build** + +Run: `py -3.12 -m pip install -e ".[dev,build]"` + +Run: `powershell -NoProfile -ExecutionPolicy Bypass -File packaging\build_release.ps1` + +Expected: build succeeds and produces the directory, ZIP, and hash manifest. + +- [ ] **Step 6: Test the built application without system Python on PATH** + +Copy the release to a temporary path containing Chinese characters and spaces. Start the copied EXE with a sanitized `PATH` containing only Windows system directories: + +```powershell +& "$releaseRoot\DxDesignerTools.exe" probe --output "$tempRoot\兼容性 结果.json" --route packaged --payload-json '{"portable":true}' +$env:QT_QPA_PLATFORM = "offscreen" +& "$releaseRoot\DxDesignerTools.exe" ui --request "$fixture" --smoke-test-ms 750 +``` + +Expected: both processes exit `0`, the probe JSON is valid UTF-8, and the UI loads the request, icons, and Qt platform plug-in without consulting `py.exe`, `python.exe`, or the network. + +- [ ] **Step 7: Run built-release structure and isolation tests** + +Run: `py -3.12 -m pytest tests/packaging/test_built_release.py -v --release-root "release/DxDesigner效率工具"` + +Expected: root scripts and EXE exist; `_runtime/python312.dll`, Qt plug-ins, and qtawesome fonts exist; no source `.py` is required at the portable root; no file contains `DXTOOLS_HOME`, `D:\NET_CHECK`, or a build-machine absolute path. + +- [ ] **Step 8: Commit reproducible packaging definitions** + +```powershell +git add packaging tests/packaging pyproject.toml .gitignore +git commit -m "build: add portable offline Windows release" +``` + +Do not commit `build/`, `dist/`, or generated `release/` binaries. + +### Task 6: Update the DOCX Guide and Add Live 7.9.5 Acceptance Instructions + +**Files:** +- Modify: `docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx` +- Create: `docs/testing/dxdesigner-795-live.md` +- Test: `tests/docs/test_user_guide.py` + +**Interfaces:** +- Consumes: the final portable folder names, root scripts, menu captions, backup location, and compatibility limitations. +- Produces: a visually verified offline guide and a target-machine evidence checklist. + +- [ ] **Step 1: Write failing document-content tests** + +Extract DOCX paragraph/table text and assert it includes `解压整个目录`, `MenuAdd.vbs`, `无需安装 Python`, `%LOCALAPPDATA%\DxProductivity`, `兼容性检测`, `自动回滚`, and `重新导入`. Assert it does not instruct users to run an installer, install Python, set `DXTOOLS_HOME`, or use `D:\NET_CHECK`. + +Run: `py -3.12 -m pytest tests/docs/test_user_guide.py -v` + +Expected: FAIL because the current guide predates the portable offline workflow. + +- [ ] **Step 2: Update the DOCX with the portable workflow** + +Use the existing document theme and page structure. Replace installation sections with: extract the complete ZIP, keep the directory stable, import the root `MenuAdd.vbs`, restart DxDesigner, run `兼容性检测`, then use `自动位号`. Add upgrade-in-place, folder relocation/re-import, removal, missing-runtime recovery, backup location, rollback result meanings, and offline-use statements. + +- [ ] **Step 3: Render and visually inspect every DOCX page** + +Use the documents skill render workflow to generate page PNGs and a PDF. Inspect every page for missing Chinese glyphs, clipped tables, orphan headings, broken numbering, overlap, inconsistent margins, and stale installer/Python screenshots or text. Iterate until the rendered document is clean. + +- [ ] **Step 4: Add the live 7.9.5 checklist** + +The checklist records Windows build, DxDesigner build, extracted root, script-path source, menu route, yield method, probe JSON path, date, project fixture, and tester. It covers menu idempotency, Chinese/space path, selected/current/full scope, continuous/page numbering, four coordinate orders, multi-unit grouping, collision blocking, cancel, successful apply, stale-state rejection, injected-failure rollback, restore, and full-design duplicate verification. + +- [ ] **Step 5: Run documentation tests** + +Run: `py -3.12 -m pytest tests/docs/test_user_guide.py -v` + +Expected: all tests pass and the visual inspection has no unresolved issue. + +- [ ] **Step 6: Commit user and acceptance documentation** + +```powershell +git add docs/user/DxDesigner_7.9.5_自动位号工具使用说明.docx docs/testing/dxdesigner-795-live.md tests/docs/test_user_guide.py +git commit -m "docs: document portable offline workflow" +``` + +### Task 7: Final Regression, Release Rebuild, and Handoff + +**Files:** +- Modify only files required by demonstrated verification failures. + +**Interfaces:** +- Consumes: all source, tests, VBS scripts, packaging definitions, documentation, and the target-machine checklist. +- Produces: a reproducible offline ZIP, checksum, automated verification record, and clearly separated pending live-7.9.5 evidence. + +- [ ] **Step 1: Run the complete source verification suite** + +```powershell +$env:QT_QPA_PLATFORM = "offscreen" +py -3.12 -m pytest -q +cscript //nologo tests\vbs\test_bridge_common.vbs +git diff --check +``` + +Expected: all tests and VBS assertions pass; `git diff --check` reports no error. + +- [ ] **Step 2: Scan for forbidden dependencies and unsafe bridge patterns** + +Run: `rg -n "DXTOOLS_HOME|D:\\NET_CHECK|ViewDraw\.Application|GetActiveObject|py -3\.12|python\.exe" integration packaging src docs/user docs/testing` + +Expected: no release-time fixed path, system-Python command, direct Python COM attachment, or newer-release dependency. Any documentation mention of “no Python installation” is allowed. + +- [ ] **Step 3: Rebuild from the committed packaging definition** + +Run: `powershell -NoProfile -ExecutionPolicy Bypass -File packaging\build_release.ps1` + +Run: `py -3.12 -m pytest tests/packaging/test_built_release.py -v --release-root "release/DxDesigner效率工具"` + +Expected: rebuilt artifacts pass structure, packaged-probe, sanitized-PATH UI, Chinese-path, and checksum tests. + +- [ ] **Step 4: Record current-machine limitations explicitly** + +Confirm whether a live DxDesigner 7.9.5 installation is discoverable. If absent, leave `docs/testing/dxdesigner-795-live.md` unchecked and label the ZIP `offline build verified; live 7.9.5 acceptance pending`. Do not mark script self-location, real API property mapping, live write-back, or rollback as target-verified from mocked evidence. + +- [ ] **Step 5: Review the complete diff and release contents** + +Run: `git status --short` + +Run: `Get-FileHash -Algorithm SHA256 "release\DxDesigner效率工具_Win11_x64.zip"` + +Expected: only intentional source/document changes remain; the printed ZIP hash matches `release/SHA256SUMS.txt`; generated binaries remain ignored by git. + +- [ ] **Step 6: Commit only fixes demonstrated by final verification** + +When Step 1 through Step 5 exposes a failure, return to that owning task, add a focused regression test, implement the minimum correction, rerun the owning task and full suite, and use that task's explicit `git add` paths. Skip this step when final verification requires no correction. + +- [ ] **Step 7: Hand off the offline archive and target checklist** + +Provide the absolute ZIP path, SHA-256, uncompressed size, compressed size, root `MenuAdd.vbs` path after extraction, automated test count, and the exact unchecked live-acceptance items. The first target run starts with `兼容性检测`; its JSON evidence determines whether the named procedure and self-location candidates are genuinely supported by DxDesigner 7.9.5. diff --git a/docs/superpowers/plans/2026-09-01-dxdesigner-795-refdes-implementation.md b/docs/superpowers/plans/2026-09-01-dxdesigner-795-refdes-implementation.md new file mode 100644 index 0000000..56c39d1 --- /dev/null +++ b/docs/superpowers/plans/2026-09-01-dxdesigner-795-refdes-implementation.md @@ -0,0 +1,1128 @@ +# DxDesigner 7.9.5 Automatic Reference Designator Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Deliver a polished automatic reference designator tool that is imported through the DxDesigner 7.9.5 startup-script mechanism, previews deterministic annotation changes in Python, and applies them through a validated VBS bridge with backup and rollback. + +**Architecture:** DxDesigner 7.9.5 imports `MenuAdd.vbs`; an internal VBS bridge owns all application API access and exchanges a versioned UTF-8 request plus an ordered TSV apply schedule with a PySide6 application. Pure Python modules own identity grouping, ordering, numbering, validation, scheduling, backup metadata, and UI state so the core behavior is testable without a live DxDesigner installation. + +**Tech Stack:** Python 3.12, PySide6 6.x, qtawesome 1.x, pytest 8.x, pytest-qt 4.x, VBScript/cscript, PowerShell 7 or Windows PowerShell 5.1, JSON, UTF-8 TSV, Git. + +**Spec:** `docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md` + +## Global Constraints + +- DxDesigner/Expedition Enterprise 7.9.5 is the only schematic integration baseline for phase one. +- Installation must use `Settings -> Run at Startup -> Scripts` with one imported `MenuAdd.vbs`. +- Do not require a newer Xpedition add-in framework, copied release DLLs, COM re-registration, or a project-format upgrade. +- All DxDesigner application access remains inside the internal VBS host; Python must not attach directly to `ViewDraw.Application`. +- `MenuAdd.vbs` resolves paths through the user-level `DXTOOLS_HOME` environment variable and contains no fixed drive path. +- Every `.vbs` source file remains ASCII-only; Chinese captions and messages are assembled with `ChrW` so the DxDesigner 7.9.5 script host never has to decode UTF-8 source text. +- Python source must run under Python 3.12. +- The default behavior changes only blank or question-mark placeholder reference designators. +- Apply must be blocked on duplicate output, occupied output, missing prefix, stale snapshot, or invalid schedule. +- Every apply and restore operation creates a timestamped backup and verifies the complete result. +- Normal text contrast is at least 4.5:1; default content text is 13 pt; essential text is never below 10 pt. +- The UI must remain usable at 100%, 125%, and 150% Windows display scaling with no clipping or overlap. +- Live compatibility is not claimed until the read-only probe and acceptance checklist pass in DxDesigner 7.9.5. + +--- + +## Planned File Structure + +```text +pyproject.toml Python package, dependencies, entry points, pytest settings +src/dx_productivity/ + __init__.py Package version + __main__.py `python -m dx_productivity` entry point + domain/ + __init__.py Domain package boundary + models.py Immutable request, settings, plan, issue, and schedule types + identity.py Scope filtering, prefix resolution, logical-unit grouping + ordering.py Page/row/column coordinate ordering + numbering.py Continuous and page-based allocation + planner.py End-to-end plan construction + validation.py Source and proposed-plan validation + schedule.py Ordered direct, dependency, and cycle apply steps + bridge/ + __init__.py Bridge package boundary + protocol.py Versioned JSON/TSV parsing and writing + run_store.py Run directories, atomic files, backups, history, restore inputs + ui/ + __init__.py UI package boundary + app.py QApplication creation and command-line request loading + theme.py Light/dark/high-contrast tokens and icon helper + main_window.py Shared suite shell and navigation + refdes_page.py Approved automatic-reference-designator view + refdes_controller.py UI state to planner/result protocol orchestration +integration/dxdesigner795/ + MenuAdd.vbs Startup-imported menu script + CompatibilityProbe.vbs Read-only in-host capability probe + ProbeAction.vbs Safe external-launch marker for route testing + BridgeCommon.vbs Pure escaping, parsing, schedule, and path helpers + RefDesBridge.vbs DxDesigner snapshot, launch, apply, verify, rollback + Install.ps1 User-level environment/config installer + Uninstall.ps1 User-level environment/config removal +tests/ + conftest.py Shared factories, fixture paths, settings, and PowerShell fixture + fixtures/request-basic.json Representative 7.9.5 request + fixtures/request-multiunit.json Multi-unit and hierarchical request + domain/ Pure annotation tests + bridge/ JSON/TSV and run-store tests + ui/ pytest-qt tests + integration/ Static VBS, installer, and mocked workflow tests + vbs/test_bridge_common.vbs cscript assertions for pure VBS helpers +docs/user/refdes-tool.md Installation and operator guide +docs/testing/dxdesigner-795-live.md Target-version acceptance checklist +``` + +### Task 1: Python Foundation and 7.9.5 Read-Only Compatibility Probe + +**Files:** +- Create: `pyproject.toml` +- Create: `src/dx_productivity/__init__.py` +- Create: `src/dx_productivity/bridge/__init__.py` +- Create: `src/dx_productivity/bridge/probe_host.py` +- Create: `integration/dxdesigner795/CompatibilityProbe.vbs` +- Create: `integration/dxdesigner795/ProbeAction.vbs` +- Create: `tests/integration/test_compatibility_probe.py` + +**Interfaces:** +- Consumes: `DXTOOLS_HOME`, injected DxDesigner 7.9.5 globals `Scripting`, `CommandBars`, `Application`, and `ActiveView`. +- Produces: `probe_host.write_probe_marker(output_path: Path, route: str, payload: dict[str, object]) -> None`, `probe_host.main(argv: Sequence[str] | None = None) -> int`, and `%LOCALAPPDATA%\DxProductivity\compatibility.json` with `menu_route`, readable capabilities, yield method, and timestamp. + +- [ ] **Step 1: Write the failing foundation and probe tests** + +```python +from pathlib import Path + +from dx_productivity.bridge.probe_host import write_probe_marker + + +def test_probe_marker_is_versioned_json(tmp_path: Path) -> None: + output = tmp_path / "compatibility.json" + write_probe_marker(output, "named", {"selected_query": True}) + assert output.read_text(encoding="utf-8") == ( + '{"format_version":1,"route":"named","selected_query":true}\n' + ) + + +def test_probe_cli_merges_capability_payload(tmp_path: Path) -> None: + output = tmp_path / "compatibility.json" + exit_code = main([ + "--output", str(output), "--route", "named", "--payload-json", + '{"yield_method":"Scripting.DoEvents","retained_reference":true}', + ]) + assert exit_code == 0 + assert json.loads(output.read_text(encoding="utf-8"))["yield_method"] == ( + "Scripting.DoEvents" + ) + + +def test_startup_probe_uses_only_795_menu_primitives() -> None: + text = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text( + encoding="utf-8" + ) + assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text + assert 'CommandBars("Sheet Menu Bar")' in text + assert text.isascii() + assert "D:\\NET_CHECK" not in text +``` + +- [ ] **Step 2: Run the tests and verify the missing package failure** + +Run: `py -3.12 -m pytest tests/integration/test_compatibility_probe.py -v` + +Expected: collection fails with `ModuleNotFoundError: No module named 'dx_productivity'`. + +- [ ] **Step 3: Create package metadata and the deterministic probe marker** + +```toml +[build-system] +requires = ["setuptools>=75"] +build-backend = "setuptools.build_meta" + +[project] +name = "dx-productivity" +version = "0.1.0" +requires-python = ">=3.12,<3.13" +dependencies = ["PySide6>=6.7,<7", "qtawesome>=1.3,<2"] + +[project.optional-dependencies] +dev = ["pytest>=8,<9", "pytest-qt>=4.4,<5", "coverage>=7,<8", "build>=1.2,<2"] + +[project.scripts] +dx-productivity = "dx_productivity.ui.app:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra" +``` + +```python +def write_probe_marker(output_path: Path, route: str, payload: dict[str, object]) -> None: + data = {"format_version": 1, "route": route, **payload} + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + payload = json.loads(args.payload_json) + if not isinstance(payload, dict): + raise ValueError("probe payload must be a JSON object") + write_probe_marker(args.output, args.route, payload) + return 0 +``` + +`build_parser()` requires `--output`, `--route` (`named`, `run`, or `form`), and `--payload-json`; the module ends with `raise SystemExit(main())` so `py -3.12 -m dx_productivity.bridge.probe_host` is directly launchable from VBS. + +- [ ] **Step 4: Add the importable probe menu with two safe action routes** + +```vbscript +Dim DxToolsHome +DxToolsHome = Scripting.GetEnvVariable("DXTOOLS_HOME") + +Set DxProbeMenu = CommandBars("Sheet Menu Bar").Controls.Add(cmdControlPopup) +DxProbeMenu.Caption = "Dx " & ChrW(&H517C) & ChrW(&H5BB9) & ChrW(&H6027) & _ + ChrW(&H68C0) & ChrW(&H6D4B) + +Set DxNamedButton = DxProbeMenu.Controls.Add +DxNamedButton.Caption = ChrW(&H68C0) & ChrW(&H6D4B) & ChrW(&H5185) & _ + ChrW(&H90E8) & ChrW(&H56DE) & ChrW(&H8C03) +DxNamedButton.OnAction = "DxToolsProbeNamed" + +Set DxRunButton = DxProbeMenu.Controls.Add +DxRunButton.Caption = ChrW(&H68C0) & ChrW(&H6D4B) & " Run " & _ + ChrW(&H811A) & ChrW(&H672C) +DxRunButton.OnAction = "Run " & DxToolsHome & "\integration\dxdesigner795\ProbeAction.vbs" + +Sub DxToolsProbeNamed() + Call DxToolsWriteProbe("named") +End Sub +``` + +`DxToolsWriteProbe` launches `py -3.12 -m dx_productivity.bridge.probe_host` through `WScript.Shell` and records only capability names, booleans, version strings, and the selected route. It must not serialize schematic content or change the active design. The probe also records the exact host method that can yield/pump messages while the Python process remains active. All VBS files are ASCII-only and assemble localized captions with `ChrW`. + +- [ ] **Step 5: Install the editable package and verify automated tests pass** + +Run: `py -3.12 -m pip install -e ".[dev]"` + +Run: `py -3.12 -m pytest tests/integration/test_compatibility_probe.py -v` + +Expected: both tests pass. + +- [ ] **Step 6: Run the probe through the documented 7.9.5 import path** + +Import `integration/dxdesigner795/CompatibilityProbe.vbs` through `Settings -> Run at Startup -> Scripts`, restart DxDesigner 7.9.5, and click the two probe actions in order. Record `named` when the first action writes `compatibility.json`; otherwise record `run` when the second action succeeds. If neither action succeeds, adapt a copy of the supplied 7.9.5 EFM in the 7.9.5 Form Editor to call `ProbeAction.vbs`, set the menu action to `Form `, and record `form`. + +Expected: exactly one route launches Python, the probe reports selected/full-design enumeration and readable component fields, retained component references remain valid, a working host yield/message-pump method is recorded, and the schematic remains unchanged. The live probe is incomplete until that yield method works while Python remains active. + +- [ ] **Step 7: Commit the foundation and probe** + +```bash +git add pyproject.toml src/dx_productivity integration/dxdesigner795 tests/integration/test_compatibility_probe.py +git commit -m "feat: add DxDesigner 7.9.5 compatibility probe" +``` + +### Task 2: Immutable Domain Models and Versioned Bridge Protocol + +**Files:** +- Create: `src/dx_productivity/domain/__init__.py` +- Create: `src/dx_productivity/domain/models.py` +- Create: `src/dx_productivity/bridge/protocol.py` +- Create: `tests/conftest.py` +- Create: `tests/fixtures/request-basic.json` +- Create: `tests/bridge/test_protocol.py` + +**Interfaces:** +- Consumes: version-1 `request.json` generated by VBS. +- Produces: `load_request(path: Path) -> DesignSnapshot`, `write_schedule(path: Path, schedule: tuple[ApplyStep, ...]) -> None`, and `load_apply_status(path: Path) -> ApplyStatus`. + +- [ ] **Step 1: Write failing request and result protocol tests** + +```python +def test_load_request_parses_decimal_coordinates(fixture_path: Path) -> None: + snapshot = load_request(fixture_path / "request-basic.json") + assert snapshot.format_version == 1 + assert snapshot.components[0].bridge_id == "c0001" + assert snapshot.components[0].x == Decimal("125.400") + assert snapshot.components[0].selected is True + + +def test_write_schedule_is_contiguous_utf8_tsv(tmp_path: Path) -> None: + output = tmp_path / "result.tsv" + write_schedule(output, (ApplyStep(1, "c0001", "R?", "R1", "R1"),)) + assert output.read_text(encoding="utf-8") == "1\tc0001\tR?\tR1\tR1\n" +``` + +- [ ] **Step 2: Run the focused tests and confirm missing model failures** + +Run: `py -3.12 -m pytest tests/bridge/test_protocol.py -v` + +Expected: fails because `DesignSnapshot` and `ApplyStep` are undefined. + +- [ ] **Step 3: Define exact immutable types and enums** + +```python +from dataclasses import dataclass +from datetime import datetime +from decimal import Decimal +from enum import Enum +from pathlib import Path + + +class Scope(str, Enum): + SELECTED = "selected" + CURRENT_SHEET = "current-sheet" + FULL_DESIGN = "full-design" + + +class ProcessingMode(str, Enum): + FILL_ONLY = "fill-only" + REANNOTATE = "reannotate" + + +class NumberingMode(str, Enum): + CONTINUOUS = "continuous" + PAGE = "page" + + +class SortOrder(str, Enum): + TOP_DOWN_LEFT_RIGHT = "top-down-left-right" + TOP_DOWN_RIGHT_LEFT = "top-down-right-left" + LEFT_RIGHT_TOP_DOWN = "left-right-top-down" + RIGHT_LEFT_TOP_DOWN = "right-left-top-down" + + +class Severity(str, Enum): + INFORMATIONAL = "informational" + WARNING = "warning" + BLOCKING = "blocking" + + +@dataclass(frozen=True, slots=True) +class ComponentRecord: + bridge_id: str + stable_uid: str | None + full_path: str + logical_group_key: str + sheet_name: str + sheet_number: int | None + x: Decimal + y: Decimal + y_axis_up: bool + refdes: str + symbol_refdes_default: str | None + selected: bool + current_sheet: bool + part_number: str + value: str + locked: bool + + +@dataclass(frozen=True, slots=True) +class ApplyStep: + sequence: int + bridge_id: str + expected_refdes: str + new_refdes: str + final_refdes: str + + +@dataclass(frozen=True, slots=True) +class PrefixResolution: + prefix: str | None + resolved: bool + issue_code: str | None + + +@dataclass(frozen=True, slots=True) +class LogicalComponent: + key: str + members: tuple[ComponentRecord, ...] + prefix: str | None + sheet_number: int | None + x: Decimal + normalized_y: Decimal + + +@dataclass(frozen=True, slots=True) +class Issue: + code: str + severity: Severity + message: str + bridge_ids: tuple[str, ...] = () + + +@dataclass(frozen=True, slots=True) +class AnnotationSettings: + scope: Scope = Scope.SELECTED + processing_mode: ProcessingMode = ProcessingMode.FILL_ONLY + numbering_mode: NumberingMode = NumberingMode.CONTINUOUS + sort_order: SortOrder = SortOrder.TOP_DOWN_LEFT_RIGHT + start_number: int = 1 + page_step: int = 100 + page_start: int = 1 + row_tolerance: Decimal = Decimal("5") + + +@dataclass(frozen=True, slots=True) +class PlanRow: + logical_key: str + bridge_ids: tuple[str, ...] + full_path: str + prefix: str | None + old_refdes: str + new_refdes: str | None + status: str + changed: bool + + +@dataclass(frozen=True, slots=True) +class AnnotationPlan: + snapshot_id: str + rows: tuple[PlanRow, ...] + issues: tuple[Issue, ...] + schedule: tuple[ApplyStep, ...] + + @property + def can_apply(self) -> bool: + return bool(self.schedule) and not any( + issue.severity is Severity.BLOCKING for issue in self.issues + ) + + +@dataclass(frozen=True, slots=True) +class DesignSnapshot: + format_version: int + run_id: str + snapshot_id: str + design_id: str + design_path: str + components: tuple[ComponentRecord, ...] + + +@dataclass(frozen=True, slots=True) +class ApplyStatus: + format_version: int + run_id: str + state: str + changed_count: int + backup_path: Path | None + failing_sequence: int | None = None + error: str | None = None + rollback_state: str | None = None + + +@dataclass(frozen=True, slots=True) +class RunPaths: + run_id: str + root: Path + request: Path + result: Path + locate: Path + apply_status: Path + + +@dataclass(frozen=True, slots=True) +class HistoryEntry: + timestamp: datetime + design_id: str + backup_path: Path + state: str + changed_count: int + + +@dataclass(frozen=True, slots=True) +class RestoreRequest: + design_id: str + source_backup: Path + expected: tuple[tuple[str, str, str], ...] +``` + +These types form the one canonical model source for all later tasks. `tests/conftest.py` defines the shared `fixture_path`, `component_factory`, `group_factory`, `settings`, `snapshot_factory`, `plan_row_factory`, and `powershell` fixtures used by later tasks. + +- [ ] **Step 4: Implement strict versioned parsing and atomic TSV writing** + +`load_request` rejects an unsupported format version, duplicate bridge IDs, invalid decimal strings, absent identity fields, and non-boolean state fields. `write_schedule` rejects tabs/newlines, noncontiguous sequence numbers, and more than two steps for one bridge ID before replacing the destination atomically. + +- [ ] **Step 5: Run protocol tests and the complete suite** + +Run: `py -3.12 -m pytest tests/bridge/test_protocol.py -v` + +Run: `py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 6: Commit the protocol contract** + +```bash +git add src/dx_productivity/domain src/dx_productivity/bridge/protocol.py tests/conftest.py tests/fixtures tests/bridge/test_protocol.py +git commit -m "feat: define refdes bridge protocol" +``` + +### Task 3: Scope, Prefix Resolution, and Multi-Unit Identity Grouping + +**Files:** +- Create: `src/dx_productivity/domain/identity.py` +- Create: `tests/fixtures/request-multiunit.json` +- Create: `tests/domain/test_identity.py` + +**Interfaces:** +- Consumes: `tuple[ComponentRecord, ...]`, `Scope`, and `ProcessingMode`. +- Produces: `select_scope(records, scope) -> tuple[ComponentRecord, ...]`, `resolve_prefix(record) -> PrefixResolution`, and `group_logical_components(records) -> tuple[LogicalComponent, ...]`. + +- [ ] **Step 1: Write failing placeholder, blank-prefix, scope, and multi-unit tests** + +```python +@pytest.mark.parametrize( + ("refdes", "symbol_default", "prefix", "resolved"), + [("R?", None, "R", True), ("tp??", None, "TP", True), ("", "C?", "C", True), ("", None, None, False)], +) +def test_resolve_prefix(refdes, symbol_default, prefix, resolved, component_factory): + result = resolve_prefix(component_factory(refdes=refdes, symbol_refdes_default=symbol_default)) + assert (result.prefix, result.resolved) == (prefix, resolved) + + +def test_multiunit_symbols_form_one_logical_component(multiunit_records): + groups = group_logical_components(multiunit_records) + assert len(groups) == 1 + assert {r.bridge_id for r in groups[0].members} == {"u1a", "u1b"} +``` + +- [ ] **Step 2: Run tests and verify missing identity functions** + +Run: `py -3.12 -m pytest tests/domain/test_identity.py -v` + +Expected: fails on imports from `domain.identity`. + +- [ ] **Step 3: Implement strict placeholder matching and scope selection** + +```python +PLACEHOLDER_RE = re.compile(r"^([A-Za-z]+)\?+$") + + +def resolve_prefix(record: ComponentRecord) -> PrefixResolution: + for candidate in (record.refdes.strip(), (record.symbol_refdes_default or "").strip()): + match = PLACEHOLDER_RE.fullmatch(candidate) + if match: + return PrefixResolution(match.group(1).upper(), True, None) + return PrefixResolution(None, False, "missing-prefix") +``` + +`select_scope` returns selected records, current-sheet records, or all records without fallback. `group_logical_components` prefers `stable_uid`, then uses a nonempty `logical_group_key`; duplicate or empty fallback keys produce an ambiguous group issue rather than merging by reference designator. + +- [ ] **Step 4: Implement processing-mode eligibility** + +Fill-only eligibility accepts blank and placeholder values. Reannotation eligibility accepts unlocked logical components with a resolved prefix. Locked records remain in the plan as preserved rows and never enter the allocator. + +- [ ] **Step 5: Run identity tests and full suite** + +Run: `py -3.12 -m pytest tests/domain/test_identity.py -v` + +Run: `py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 6: Commit identity behavior** + +```bash +git add src/dx_productivity/domain/identity.py tests/domain/test_identity.py tests/fixtures/request-multiunit.json +git commit -m "feat: resolve refdes identity and prefixes" +``` + +### Task 4: Coordinate Ordering and Number Allocation + +**Files:** +- Create: `src/dx_productivity/domain/ordering.py` +- Create: `src/dx_productivity/domain/numbering.py` +- Create: `tests/domain/test_ordering.py` +- Create: `tests/domain/test_numbering.py` + +**Interfaces:** +- Consumes: `tuple[LogicalComponent, ...]`, `AnnotationSettings`, and occupied formal reference designators. +- Produces: `order_components(components, settings) -> tuple[LogicalComponent, ...]` and `allocate_numbers(components, occupied, settings) -> dict[str, str]` keyed by logical group key. + +- [ ] **Step 1: Write failing default Z-order tests** + +```python +def test_default_order_is_sheet_top_to_bottom_then_left_to_right(group_factory): + groups = ( + group_factory("b", sheet=1, x="30", y="100"), + group_factory("a", sheet=1, x="10", y="100"), + group_factory("c", sheet=1, x="5", y="80"), + group_factory("d", sheet=2, x="1", y="500"), + ) + ordered = order_components(groups, settings(row_tolerance=Decimal("5"))) + assert [g.key for g in ordered] == ["a", "b", "c", "d"] +``` + +- [ ] **Step 2: Write failing continuous and page allocation tests** + +```python +def test_continuous_allocation_skips_occupied(group_factory): + groups = (group_factory("a", prefix="R"), group_factory("b", prefix="R")) + result = allocate_numbers(groups, {"R1", "r3"}, settings(start_number=1)) + assert result == {"a": "R2", "b": "R4"} + + +def test_page_mode_starts_sheet_three_at_301(group_factory): + groups = (group_factory("a", prefix="C", sheet=3),) + result = allocate_numbers(groups, set(), settings(numbering_mode=NumberingMode.PAGE)) + assert result == {"a": "C301"} +``` + +- [ ] **Step 3: Run focused tests and verify missing implementations** + +Run: `py -3.12 -m pytest tests/domain/test_ordering.py tests/domain/test_numbering.py -v` + +Expected: fails on missing `order_components` and `allocate_numbers`. + +- [ ] **Step 4: Implement normalized row clustering and all four sort orders** + +Normalize API Y direction before sorting. Within each numeric sheet, create a new row when the distance from the current row anchor exceeds `row_tolerance`; sort each row by X. Use logical group key as the final tie-breaker. Reject page mode when any eligible component lacks a numeric sheet mapping. + +- [ ] **Step 5: Implement case-insensitive per-prefix allocators** + +Continuous mode starts at `start_number` for each prefix and advances until it finds a value absent from the uppercase occupied set. Page mode starts at `sheet_number * page_step + page_start`. Allocation order is the result from `order_components` and never depends on input collection order. + +- [ ] **Step 6: Run focused tests, randomized determinism test, and full suite** + +Run: `py -3.12 -m pytest tests/domain/test_ordering.py tests/domain/test_numbering.py -v` + +Run: `py -3.12 -m pytest -q` + +Expected: all tests pass, including a test that shuffles equal-coordinate input 50 times and receives identical output. + +- [ ] **Step 7: Commit ordering and allocation** + +```bash +git add src/dx_productivity/domain/ordering.py src/dx_productivity/domain/numbering.py tests/domain/test_ordering.py tests/domain/test_numbering.py +git commit -m "feat: add deterministic refdes allocation" +``` + +### Task 5: Plan Validation and Ordered Apply Scheduling + +**Files:** +- Create: `src/dx_productivity/domain/validation.py` +- Create: `src/dx_productivity/domain/schedule.py` +- Create: `src/dx_productivity/domain/planner.py` +- Create: `tests/domain/test_validation.py` +- Create: `tests/domain/test_schedule.py` +- Create: `tests/domain/test_planner.py` + +**Interfaces:** +- Consumes: `DesignSnapshot` and `AnnotationSettings`. +- Produces: `build_annotation_plan(snapshot, settings) -> AnnotationPlan`, `validate_plan(snapshot, rows) -> tuple[Issue, ...]`, and `build_apply_schedule(rows) -> tuple[ApplyStep, ...]`. + +- [ ] **Step 1: Write failing collision and missing-prefix plan tests** + +```python +def test_plan_blocks_collision_with_component_outside_scope(snapshot_factory): + snapshot = snapshot_factory(target_ref="R?", outside_ref="R1") + plan = build_annotation_plan(snapshot, settings(start_number=1)) + assert plan.rows[0].new_refdes == "R2" + assert not [issue for issue in plan.issues if issue.severity is Severity.BLOCKING] + + +def test_plan_blocks_unresolved_prefix(snapshot_factory): + plan = build_annotation_plan(snapshot_factory(target_ref=""), settings()) + assert any(issue.code == "missing-prefix" for issue in plan.issues) + assert plan.can_apply is False +``` + +- [ ] **Step 2: Write failing two-component cycle schedule test** + +```python +def test_schedule_breaks_refdes_swap_with_prefix_placeholder(plan_row_factory): + rows = ( + plan_row_factory("a", "R1", "R2"), + plan_row_factory("b", "R2", "R1"), + ) + steps = build_apply_schedule(rows) + assert [(s.bridge_id, s.expected_refdes, s.new_refdes) for s in steps] == [ + ("a", "R1", "R?"), + ("b", "R2", "R1"), + ("a", "R?", "R2"), + ] + assert [s.sequence for s in steps] == [1, 2, 3] +``` + +- [ ] **Step 3: Run planner tests and confirm missing functions** + +Run: `py -3.12 -m pytest tests/domain/test_validation.py tests/domain/test_schedule.py tests/domain/test_planner.py -v` + +Expected: fails on missing planner modules. + +- [ ] **Step 4: Implement source and proposed-plan validation** + +Validation emits stable issue codes for duplicate source formal reference designators, duplicate proposed output, occupied output, missing prefix, ambiguous logical identity, locked target, nonnumeric sheet in page mode, and multiple outputs for one logical component. `AnnotationPlan.can_apply` is false when any issue has `Severity.BLOCKING`. + +- [ ] **Step 5: Implement dependency scheduling with cycle breaking** + +Direct placeholder-to-formal changes are emitted first. For formal-to-formal changes, repeatedly emit rows whose target is not an unprocessed current value. When no row is available, choose the lexicographically smallest bridge ID, move it to `?`, continue the now-acyclic chain, and finally move the temporary component to its final value. Emit `final_refdes` on every step and assert each bridge ID appears no more than twice. + +- [ ] **Step 6: Compose the end-to-end planner** + +`build_annotation_plan` selects scope, groups logical components, resolves prefixes, preserves locked/formal rows according to mode, orders eligible groups, computes the occupied set outside the target set, allocates new values, validates rows, and builds a schedule only when no blocking issue exists. + +- [ ] **Step 7: Run planner tests and complete suite** + +Run: `py -3.12 -m pytest tests/domain -v` + +Run: `py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 8: Commit the planner** + +```bash +git add src/dx_productivity/domain tests/domain +git commit -m "feat: validate and schedule refdes plans" +``` + +### Task 6: Atomic Run Store, Backup History, and Restore Inputs + +**Files:** +- Create: `src/dx_productivity/bridge/run_store.py` +- Create: `tests/bridge/test_run_store.py` + +**Interfaces:** +- Consumes: `DesignSnapshot`, `AnnotationPlan`, `ApplyStatus`, and `%LOCALAPPDATA%`. +- Produces: `RunStore.create_run() -> RunPaths`, `RunStore.write_backup(snapshot, plan) -> Path`, `RunStore.record_status(status) -> None`, `RunStore.list_history(design_id) -> tuple[HistoryEntry, ...]`, and `RunStore.build_restore_settings(entry) -> RestoreRequest`. + +- [ ] **Step 1: Write failing atomic-backup and history tests** + +```python +def test_backup_contains_complete_old_and_new_mapping(tmp_path, snapshot, plan): + store = RunStore(tmp_path) + path = store.write_backup(snapshot, plan) + data = json.loads(path.read_text(encoding="utf-8")) + assert data["format_version"] == 1 + assert data["design_id"] == snapshot.design_id + assert data["changes"][0] == { + "bridge_id": "c0001", "full_path": "ROOT\\R_A", "old_refdes": "R?", "new_refdes": "R1" + } + + +def test_history_ignores_incomplete_temporary_files(tmp_path): + store = RunStore(tmp_path) + (store.backup_root / "orphan.tmp").write_text("partial", encoding="utf-8") + assert store.list_history("design-a") == () +``` + +- [ ] **Step 2: Run tests and confirm missing run store** + +Run: `py -3.12 -m pytest tests/bridge/test_run_store.py -v` + +Expected: fails on missing `RunStore`. + +- [ ] **Step 3: Implement run paths and atomic JSON replacement** + +Use `tempfile.NamedTemporaryFile(delete=False, dir=destination.parent)` followed by `Path.replace` so a crash cannot leave a valid-looking partial request, backup, status, or history file. Sanitize design IDs for filenames while retaining the original design ID inside JSON. + +- [ ] **Step 4: Implement history and restore preflight data** + +History entries include timestamp, design ID, source backup path, success/rollback state, and changed count. Restore uses stable UID/full path plus the currently expected new reference designator; it refuses to construct a result when identity or current value does not match the backup. + +- [ ] **Step 5: Run bridge tests and full suite** + +Run: `py -3.12 -m pytest tests/bridge -v` + +Run: `py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 6: Commit run persistence** + +```bash +git add src/dx_productivity/bridge/run_store.py tests/bridge/test_run_store.py +git commit -m "feat: add atomic refdes backup history" +``` + +### Task 7: VBS Snapshot, Schedule Validation, Write-Back, and Rollback + +**Files:** +- Create: `integration/dxdesigner795/BridgeCommon.vbs` +- Create: `integration/dxdesigner795/RefDesBridge.vbs` +- Create: `tests/vbs/test_bridge_common.vbs` +- Create: `tests/integration/test_vbs_bridge.py` + +**Interfaces:** +- Consumes: injected 7.9.5 application objects, `DXTOOLS_HOME`, `compatibility.json`, and version-1 `result.tsv`. +- Produces: version-1 `request.json`, `apply-status.json`, a verified schematic mutation, and rollback on any failure. + +- [ ] **Step 1: Write failing cscript helper assertions** + +```vbscript +ExecuteGlobal CreateObject("Scripting.FileSystemObject").OpenTextFile( _ + "integration\dxdesigner795\BridgeCommon.vbs", 1, False).ReadAll + +Call AssertEqual("quote", DxJsonEscape("a" & Chr(34) & "b"), _ + "a" & Chr(92) & Chr(34) & "b") +Call AssertEqual("newline", DxJsonEscape("a" & vbLf & "b"), "a\nb") +Call AssertEqual("valid schedule", DxValidateSchedule( _ + "1" & vbTab & "c1" & vbTab & "R1" & vbTab & "R?" & vbTab & "R2" & vbCrLf & _ + "2" & vbTab & "c2" & vbTab & "R2" & vbTab & "R1" & vbTab & "R1" & vbCrLf & _ + "3" & vbTab & "c1" & vbTab & "R?" & vbTab & "R2" & vbTab & "R2"), True) +``` + +- [ ] **Step 2: Run cscript and confirm missing helper failure** + +Run: `cscript //nologo tests\vbs\test_bridge_common.vbs` + +Expected: fails because `BridgeCommon.vbs` does not exist. + +- [ ] **Step 3: Implement locale-safe UTF-8 and schedule helpers** + +`BridgeCommon.vbs` supplies `DxJsonEscape`, invariant coordinate formatting, ADODB.Stream UTF-8 read/write, TSV row parsing, contiguous sequence validation, allowed one/two-step bridge-ID validation, expected-current chaining, environment path resolution, and atomic replace through a same-directory temporary file. + +- [ ] **Step 4: Implement snapshot export with an in-memory object map** + +`RefDesBridge.vbs` obtains the top-level design through `Application.GetProjectData`, enumerates full-design components through the probe-confirmed API, assigns `c000001` bridge IDs, retains component objects in a `Scripting.Dictionary`, marks selected and current-sheet membership, and writes only the fields defined by `ComponentRecord`. + +When a probed property is unavailable, the compatibility adapter writes its specified fallback: empty stable UID, full path identity, empty symbol default, or `false` lock state. Missing both stable UID and unambiguous full path aborts export. + +- [ ] **Step 5: Implement nonblocking Python launch, mailbox processing, stale-state preflight, and ordered apply** + +Launch the configured Python executable with quoted arguments through `WScript.Shell.Exec`. Retain the `bridge_id -> component object` dictionary and run a throttled mailbox loop using the exact yield/message-pump method proven by the compatibility probe. While Python remains active, consume each atomically published `locate.tsv` and `result.tsv` exactly once: locate selects and zooms the mapped component; result triggers stale-state preflight and the ordered apply. Before each apply step, confirm the mapped object still exists and `comp.Refdes` equals `expected_refdes`, then assign `new_refdes`. Write `apply-status.json` before Python exits so the live UI can display the outcome. If Python exits without publishing a result, leave the design unchanged. + +- [ ] **Step 6: Implement verification and rollback** + +After the final step, verify every mapped component equals `final_refdes`, re-enumerate the full design, and check case-insensitive uniqueness of formal reference designators. On any error, restore the original in-memory mapping, verify restoration, and write `apply-status.json` with `state`, failing sequence, error number/description, rollback result, and backup path. + +- [ ] **Step 7: Run cscript and static bridge tests** + +Run: `cscript //nologo tests\vbs\test_bridge_common.vbs` + +Run: `py -3.12 -m pytest tests/integration/test_vbs_bridge.py -v` + +Expected: helper assertions pass; static tests confirm every VBS source is ASCII-only and `RefDesBridge.vbs` contains no direct Python COM attachment, fixed drive path, `On Error Resume Next` around the full operation, or writes before backup creation. + +- [ ] **Step 8: Commit the VBS bridge** + +```bash +git add integration/dxdesigner795/BridgeCommon.vbs integration/dxdesigner795/RefDesBridge.vbs tests/vbs tests/integration/test_vbs_bridge.py +git commit -m "feat: add safe DxDesigner 7.9.5 VBS bridge" +``` + +### Task 8: Apple-Inspired PySide6 Shell and Design Tokens + +**Files:** +- Create: `src/dx_productivity/ui/__init__.py` +- Create: `src/dx_productivity/__main__.py` +- Create: `src/dx_productivity/ui/theme.py` +- Create: `src/dx_productivity/ui/main_window.py` +- Create: `src/dx_productivity/ui/app.py` +- Create: `tests/ui/test_main_window.py` + +**Interfaces:** +- Consumes: command-line `--request `, system palette, and `RunStore`. +- Produces: `create_application(argv) -> QApplication`, `MainWindow`, `apply_theme(app, Theme) -> None`, and a navigation signal for module pages. + +`theme.py` defines `class Theme(str, Enum)` with exact values `LIGHT = "light"`, `DARK = "dark"`, and `HIGH_CONTRAST = "high-contrast"`; all token maps are keyed by this enum. + +- [ ] **Step 1: Write failing shell layout and accessibility tests** + +```python +def test_main_window_has_approved_minimum_and_navigation(qtbot): + window = MainWindow() + qtbot.addWidget(window) + assert window.minimumWidth() == 1100 + assert window.minimumHeight() == 700 + assert window.navigation.item_texts()[:3] == ["自动位号", "属性批改", "属性显示"] + + +def test_icon_buttons_have_accessible_names(qtbot): + window = MainWindow() + qtbot.addWidget(window) + for button in window.findChildren(QToolButton): + assert button.accessibleName() + assert button.toolTip() +``` + +- [ ] **Step 2: Run UI tests in offscreen mode and confirm missing UI classes** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_main_window.py -v` + +Expected: fails on missing `MainWindow`. + +- [ ] **Step 3: Implement centralized light, dark, and high-contrast tokens** + +Define semantic tokens for canvas, window, sidebar, surface, borders, primary/secondary text, accent, success, warning, danger, and focus. Use 13 pt default text, 10 pt minimum secondary text, 30 logical-pixel action buttons, 16 logical-pixel icons, 6-pixel control radii, and no decorative animation. + +Use qtawesome icons with one consistent Font Awesome weight. Map familiar semantics such as refresh, preview, apply, search, filter, locate, history, settings, success, warning, and lock. Do not place visible text inside an icon-only tool button. + +- [ ] **Step 4: Implement the shared window shell** + +Build the 52-pixel title bar, 218-pixel navigation rail, resizable content area, project context, bridge state, theme toggle, refresh, preview, and Apply actions. Keep Apply at the top-right. The shell exposes page/action signals and does not import annotation algorithms. + +- [ ] **Step 5: Run keyboard focus and theme tests** + +Test Tab traversal, accessible names, light/dark token application, 1100x700 minimum layout, and absence of clipped child geometry at 100%, 125%, and 150% logical test scales. + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_main_window.py -v` + +Expected: all tests pass. + +- [ ] **Step 6: Commit the UI shell** + +```bash +git add src/dx_productivity/__main__.py src/dx_productivity/ui tests/ui/test_main_window.py +git commit -m "feat: add polished productivity suite shell" +``` + +### Task 9: Automatic Reference Designator Page and Controller + +**Files:** +- Create: `src/dx_productivity/ui/refdes_page.py` +- Create: `src/dx_productivity/ui/refdes_controller.py` +- Create: `tests/ui/test_refdes_page.py` +- Create: `tests/ui/test_refdes_controller.py` + +**Interfaces:** +- Consumes: `DesignSnapshot`, `AnnotationSettings`, `build_annotation_plan`, `RunStore`, and `write_schedule`. +- Produces: `RefDesPage.settings_changed`, `RefDesPage.apply_requested`, `RefDesController.refresh_plan()`, `RefDesController.apply() -> Path`, and preview selection/location signals. + +- [ ] **Step 1: Write failing default-control and Apply-state tests** + +```python +def test_refdes_defaults_match_approved_design(qtbot): + page = RefDesPage() + qtbot.addWidget(page) + assert page.scope() is Scope.SELECTED + assert page.processing_mode() is ProcessingMode.FILL_ONLY + assert page.numbering_mode() is NumberingMode.CONTINUOUS + assert page.sort_order() is SortOrder.TOP_DOWN_LEFT_RIGHT + assert page.start_number() == 1 + assert page.row_tolerance() == Decimal("5") + + +def test_blocking_issue_disables_apply(qtbot, controller, unresolved_snapshot): + controller.load_snapshot(unresolved_snapshot) + assert controller.page.apply_button.isEnabled() is False + assert controller.page.issue_text() == "1 个前缀待确认" +``` + +- [ ] **Step 2: Run focused UI tests and confirm missing page/controller** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui/test_refdes_page.py tests/ui/test_refdes_controller.py -v` + +Expected: fails on missing `RefDesPage` and `RefDesController`. + +- [ ] **Step 3: Implement the approved rules panel and preview table** + +Use segmented controls for scope and processing mode, combo boxes for numbering and order, numeric controls for start/page step/page start/row tolerance, checkboxes for preservation rules, a prefix summary, search/filter toolbar, and a fixed-column preview model. Preview status always includes icon plus text: `待更新`, `已保留`, `需确认`, or `阻断`. + +- [ ] **Step 4: Implement controller-driven live recomputation** + +The controller converts widget state into immutable `AnnotationSettings`, calls `build_annotation_plan`, updates rows/issues/counts without mutating the snapshot, and enables Apply only when `plan.can_apply` and at least one changed row are true. Search filters the presentation model only and never changes the plan. + +- [ ] **Step 5: Implement preview, Apply, cancel, and locate signals** + +Preview runs automatically after a valid request loads and explicitly when Refresh/Generate Preview is clicked. Python remains open throughout the transaction. Apply first writes the backup and then atomically publishes the ordered `result.tsv`; a `QTimer` polls for the VBS-written `apply-status.json`, updates history exactly once, and displays success, verified rollback, or rollback failure without closing the window. Cancel before result creation exits without writing `result.tsv` and therefore cannot change the design. + +Double-clicking a row atomically writes a `locate.tsv` request containing its bridge ID; the active VBS mailbox loop consumes it exactly once and selects/zooms the mapped component without applying annotation changes. + +- [ ] **Step 6: Run UI/controller tests and full suite** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/ui -v` + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest -q` + +Expected: all tests pass. + +- [ ] **Step 7: Commit the automatic-reference-designator UI** + +```bash +git add src/dx_productivity/ui/refdes_page.py src/dx_productivity/ui/refdes_controller.py tests/ui +git commit -m "feat: add automatic refdes preview workflow" +``` + +### Task 10: Installer, Startup Menu, and Verified Route Adapter + +**Files:** +- Create: `integration/dxdesigner795/MenuAdd.vbs` +- Create: `integration/dxdesigner795/Install.ps1` +- Create: `integration/dxdesigner795/Uninstall.ps1` +- Create: `tests/integration/test_installer.py` +- Create: `tests/integration/test_menu_script.py` + +**Interfaces:** +- Consumes: probe-selected route, resolved Python 3.12 executable, project installation root, and user-level environment/config storage. +- Produces: `DXTOOLS_HOME`, `%LOCALAPPDATA%\DxProductivity\settings.json`, one importable `MenuAdd.vbs`, and a menu action that invokes `RefDesBridge.vbs` through the proven 7.9.5 route. + +- [ ] **Step 1: Write failing dry-run installer and menu tests** + +```python +def test_installer_dry_run_handles_spaces_and_chinese(tmp_path, powershell): + install_root = tmp_path / "效率 工具" + result = powershell("integration/dxdesigner795/Install.ps1", "-InstallRoot", str(install_root), "-WhatIf") + assert result.returncode == 0 + assert f'DXTOOLS_HOME={install_root.resolve()}' in result.stdout + + +def test_menu_script_uses_environment_and_795_sheet_bar(): + text = Path("integration/dxdesigner795/MenuAdd.vbs").read_text(encoding="utf-8") + assert 'Scripting.GetEnvVariable("DXTOOLS_HOME")' in text + assert 'CommandBars("Sheet Menu Bar")' in text + assert "D:\\" not in text +``` + +- [ ] **Step 2: Run installer tests and confirm missing files** + +Run: `py -3.12 -m pytest tests/integration/test_installer.py tests/integration/test_menu_script.py -v` + +Expected: fails because installer and release menu files do not exist. + +- [ ] **Step 3: Implement nonadmin user-level installation** + +`Install.ps1` validates Python is exactly major/minor 3.12, confirms the package imports, stores the resolved executable and probe-selected route in UTF-8 `settings.json`, and sets `DXTOOLS_HOME` with `[Environment]::SetEnvironmentVariable(..., "User")`. `-WhatIf` prints all intended values without changing the environment or filesystem outside a temporary test root. + +`Uninstall.ps1` removes only the user-level environment variable and user-local DxProductivity configuration after confirming their resolved paths belong to the configured install. It prints the exact DxDesigner Scripts-list entry the user must remove manually. + +- [ ] **Step 4: Implement idempotent menu registration** + +`MenuAdd.vbs` removes only an existing menu control with the exact suite tag/caption before adding one replacement. It reads the verified route from settings and generates one `自动位号` action. The source remains ASCII-only and constructs all Chinese captions/messages with `ChrW`. Missing home/config shows one concise message and does not add a broken action. + +- [ ] **Step 5: Test paths, idempotency, and route rendering** + +Run: `py -3.12 -m pytest tests/integration/test_installer.py tests/integration/test_menu_script.py -v` + +Expected: tests pass for paths with spaces/Chinese characters and for `named`, `run`, and `form` route fixtures. + +- [ ] **Step 6: Repeat the live startup-import smoke test** + +Import only `integration/dxdesigner795/MenuAdd.vbs` through `Settings -> Run at Startup -> Scripts`, restart DxDesigner twice, and confirm exactly one suite menu appears each time. Invoke `自动位号` and confirm the Python UI receives a request without modifying the design before Apply. + +- [ ] **Step 7: Commit installation and menu integration** + +```bash +git add integration/dxdesigner795/MenuAdd.vbs integration/dxdesigner795/Install.ps1 integration/dxdesigner795/Uninstall.ps1 tests/integration/test_installer.py tests/integration/test_menu_script.py +git commit -m "feat: install through DxDesigner 7.9.5 startup scripts" +``` + +### Task 11: Mocked End-to-End Workflow, Visual QA, and Operator Documentation + +**Files:** +- Create: `tests/integration/mock_dxdesigner.py` +- Create: `tests/integration/test_end_to_end.py` +- Create: `docs/user/refdes-tool.md` +- Create: `docs/testing/dxdesigner-795-live.md` +- Modify: `src/dx_productivity/__main__.py` + +**Interfaces:** +- Consumes: the complete version-1 bridge protocol and all phase-one modules. +- Produces: a repeatable mock workflow, release verification commands, installation/operator guide, and live 7.9.5 acceptance record. + +- [ ] **Step 1: Write the failing mocked end-to-end test** + +```python +def test_fill_only_end_to_end_creates_verified_schedule(tmp_path, basic_request): + mock = MockDxDesigner(tmp_path, basic_request) + result = mock.run_app( + scope="selected", + mode="fill-only", + numbering="continuous", + auto_apply=True, + ) + assert result.exit_code == 0 + assert result.final_refdes == {"c0001": "R1", "c0002": "C1", "c0003": "U1"} + assert result.status.state == "applied" + assert result.backup.exists() +``` + +- [ ] **Step 2: Run the end-to-end test and confirm missing mock harness** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest tests/integration/test_end_to_end.py -v` + +Expected: fails because `MockDxDesigner` is undefined. + +- [ ] **Step 3: Implement the mock bridge process** + +The mock writes a real `request.json`, launches `python -m dx_productivity --request --test-auto-apply`, validates `result.tsv` through the same constraints as VBS, applies every expected-current step to an in-memory component map, writes `apply-status.json`, and verifies final values. It supports injected stale-state and assignment-failure cases to exercise rollback UI. + +- [ ] **Step 4: Add operator and live-acceptance documentation** + +`docs/user/refdes-tool.md` documents Python installation, `Install.ps1`, the exact 7.9.5 startup-script import steps, restart requirement, scope/mode/order controls, preview statuses, Apply, backup location, Restore Last Annotation, diagnostics, and uninstall. + +`docs/testing/dxdesigner-795-live.md` contains checkboxes for menu idempotency, selected/current/full scope, page and continuous numbering, top-down/left-right coordinate order, multi-unit components, collisions, Chinese/space paths, cancel, stale-state rejection, successful apply, injected failure rollback, restore, and full-design duplicate scan. It records DxDesigner build, Windows version, Python version, probe route, date, project fixture, and tester. + +- [ ] **Step 5: Run automated tests and coverage** + +Run: `$env:QT_QPA_PLATFORM='offscreen'; py -3.12 -m pytest --cov=dx_productivity --cov-report=term-missing` + +Expected: all tests pass; domain and bridge Python modules have at least 90% line coverage; no uncovered branch remains in collision, cycle scheduling, stale-state, or rollback-plan tests. + +- [ ] **Step 6: Run visual acceptance at required window/scaling combinations** + +Capture and inspect light, dark, warning, blocking, empty-selection, and populated-preview states at 1100x700 and 1440x900 logical sizes under 100%, 125%, and 150% Windows scaling. Verify no clipped text, overlapping controls, truncated longest Chinese label, unstable table columns, missing icon, invisible focus, or color-only status. + +- [ ] **Step 7: Run the live 7.9.5 checklist and record evidence** + +Execute every item in `docs/testing/dxdesigner-795-live.md` on the target installation. A failed item remains a release blocker and records the observed API value/error plus the fixture used. Mark compatibility complete only when the checklist contains no unresolved failure. + +- [ ] **Step 8: Build and smoke-test the distributable Python package** + +Run: `py -3.12 -m build` + +Run: `py -3.12 -m pip install --force-reinstall dist\dx_productivity-0.1.0-py3-none-any.whl` + +Run: `dx-productivity --request tests\fixtures\request-basic.json --test-auto-apply` + +Expected: wheel builds, installs, opens the fixture, writes a valid schedule, and exits successfully. + +- [ ] **Step 9: Commit end-to-end verification and documentation** + +```bash +git add src/dx_productivity/__main__.py tests/integration docs/user docs/testing +git commit -m "test: verify automatic refdes workflow end to end" +``` + +### Task 12: Final Regression and Release Review + +**Files:** +- Modify only files required by failures discovered in this task. + +**Interfaces:** +- Consumes: all phase-one deliverables and the completed live acceptance record. +- Produces: a clean working tree at a tested release commit. + +- [ ] **Step 1: Run every automated verification command from a clean environment** + +```powershell +py -3.12 -m pip install -e ".[dev]" +$env:QT_QPA_PLATFORM = "offscreen" +py -3.12 -m pytest --cov=dx_productivity --cov-report=term-missing +cscript //nologo tests\vbs\test_bridge_common.vbs +git diff --check +git status --short +``` + +Expected: tests and VBS assertions pass, `git diff --check` is empty, and status contains only deliberately untracked local acceptance artifacts covered by `.gitignore`. + +- [ ] **Step 2: Verify requirement-to-test traceability** + +Check every section of `docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md` against a named automated test or a checked live-acceptance item. Add a concrete test when a requirement lacks evidence; do not close the phase with prose-only assurance. + +- [ ] **Step 3: Review the final diff for version leakage and unsafe operations** + +Run: `rg -n "D:\\NET_CHECK|ViewDraw\.Application|GetActiveObject|newer|On Error Resume Next" src integration tests docs/user docs/testing` + +Expected: no fixed legacy path, direct Python COM attachment, newer-release dependency, or operation-wide error suppression. Any narrowly scoped `On Error Resume Next` has an immediate `Err` check and restoration of normal error handling. + +- [ ] **Step 4: Commit only regression fixes when needed** + +```bash +git add +git commit -m "fix: address automatic refdes release checks" +``` + +Skip this commit when Step 1 through Step 3 require no file changes. diff --git a/docs/superpowers/plans/2026-09-11-yiyezhqiu-legacy-migration.md b/docs/superpowers/plans/2026-09-11-yiyezhqiu-legacy-migration.md new file mode 100644 index 0000000..3c12a03 --- /dev/null +++ b/docs/superpowers/plans/2026-09-11-yiyezhqiu-legacy-migration.md @@ -0,0 +1,344 @@ +# 一叶知秋_重构版旧功能迁移实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 将原始“一叶知秋”中的旧 EFM/VBS 功能以可回滚、可验收的兼容模块接入当前自动位号工具宿主。 + +**Architecture:** 保留原始 EFM/VBS 的行为作为第一阶段兼容层,由当前启动资产生成器提供工具根目录和菜单动作;旧模块与 RefDes 使用独立资源、日志和状态边界。每个模块先达到兼容接入,再单独决定是否迁移到现代 Python/VBS 桥接。 + +**Tech Stack:** Python 3.12, PySide6, 7.9.5 内部 VBS, EFM, pytest, cscript, PyInstaller onedir。 + +**Spec:** `docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md` + +## Global Constraints + +- 用户可见产品名统一为“一叶知秋_重构版”,当前 Python 包名和内部协议标识暂不改名。 +- 只支持 DxDesigner/Expedition Enterprise 7.9.5 的已验证接口,不引入新版 Xpedition API 或 DLL。 +- 旧资源必须从工具自身目录解析,不使用 `D:\NET_CHECK`、持久化 `SKY_MT` 或其他固定安装路径。 +- 旧 EFM/VBS 兼容接入不等同于现代化重构;未完成 7.9.5 副本工程验收的模块不得标记为 stable。 +- 当前自动位号、预览、应用、历史和恢复行为保持不变。 +- 任何旧模块失败都不得静默修改原理图,也不得修改 RefDes 运行目录中的快照、应用状态或历史记录。 +- 所有新增 VBS 源文件保持 ASCII;中文菜单文本使用 `ChrW` 构造。 + +--- + +### Task 1: 固化旧资产清单与模块支持矩阵 + +**Files:** +- Create: `src/dx_productivity/legacy/__init__.py` +- Create: `src/dx_productivity/legacy/manifest.py` +- Create: `tests/legacy/test_manifest.py` +- Create: `integration/dxdesigner795/legacy/yiyezhqiu/` assets copied from `Z:\dxdesigner-795-refdes\MENTOR效率工具一叶知秋.zip` +- Modify: `packaging/DxDesignerTools.spec` +- Modify: `packaging/build_release.ps1` +- Modify: `tests/packaging/test_release_definition.py` + +**Interfaces:** +- Produces `LegacyModule(module_id: str, display_name: str, host: str, action_kind: str, entrypoint: str, assets: tuple[str, ...], status: str)`. +- Produces `legacy_modules() -> tuple[LegacyModule, ...]` with IDs `bom`, `value`, `value1`, `part-number`, `property-visibility`, `network`, and `pcb-assembly-refdes`. +- Produces `validate_legacy_assets(root: Path) -> tuple[str, ...]`; it returns missing relative paths in deterministic order and never raises for an absent optional module. + +- [ ] **Step 1: Write the failing test** + +```python +def test_manifest_lists_only_original_yiyezhqiu_modules(): + from dx_productivity.legacy.manifest import legacy_modules + + modules = legacy_modules() + assert [item.module_id for item in modules] == [ + "bom", "value", "value1", "part-number", + "property-visibility", "network", "pcb-assembly-refdes", + ] + assert all(item.status == "compatibility" for item in modules) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/legacy/test_manifest.py::test_manifest_lists_only_original_yiyezhqiu_modules -v` + +Expected: FAIL with `ModuleNotFoundError: No module named 'dx_productivity.legacy'`. + +- [ ] **Step 3: Write minimal implementation** + +Define the frozen dataclass and return the seven entries. Use relative entrypoints such as `legacy/yiyezhqiu/NET_CHECK/PART_Ref_CHA.efm` and `legacy/yiyezhqiu/NET_CHECK/BOM_output/Bom.efm`; do not store an absolute path in the manifest. + +Copy only the original functional assets required by the manifest. Keep the original documents outside the executable runtime unless a later user-guide task explicitly references them. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/legacy/test_manifest.py -v` + +Expected: PASS, including tests for deterministic ordering, missing asset reporting, and no absolute `D:\NET_CHECK` path. + +- [ ] **Step 5: Add release assertions** + +Extend `DxDesignerTools.spec` and `build_release.ps1` so the onedir release copies the legacy asset tree. Add a packaging test that requires the seven manifest entrypoints in the release directory and rejects any runtime path containing `D:\NET_CHECK`. + +- [ ] **Step 6: Commit** + +```bash +git add src/dx_productivity/legacy tests/legacy integration/dxdesigner795/legacy packaging/DxDesignerTools.spec packaging/build_release.ps1 tests/packaging/test_release_definition.py +git commit -m "feat: inventory legacy yiyezhqiu modules" +``` + +**Approval gate:** review the generated module matrix and confirm which of the seven modules may be marked `compatibility` for the first release. + +### Task 2: Generate portable legacy menu actions + +**Files:** +- Create: `src/dx_productivity/legacy/menu.py` +- Create: `tests/legacy/test_menu.py` +- Create: `integration/dxdesigner795/modules/legacy/LegacyMenu.vbs` +- Modify: `src/dx_productivity/bridge/startup_assets.py` +- Modify: `integration/dxdesigner795/MenuAdd.vbs` +- Modify: `tests/bridge/test_startup.py` +- Modify: `tests/integration/test_menu_script.py` + +**Interfaces:** +- `render_legacy_menu(tool_root: Path, modules: tuple[LegacyModule, ...]) -> str` returns ASCII VBS that uses only `ChrW` for Chinese captions and builds each action from `tool_root`. +- `legacy_action_name(module_id: str) -> str` returns the string `DxLegacy_` plus the module ID with hyphens converted to underscores plus `.vbs`. +- `generate_startup_assets()` adds the legacy action scripts to `StartupAssets.action_scripts` without changing the four existing RefDes/compatibility/guide/diagnostic keys. + +- [ ] **Step 1: Write the failing test** + +```python +def test_render_legacy_menu_has_relative_runtime_actions(tmp_path): + from dx_productivity.legacy.manifest import legacy_modules + from dx_productivity.legacy.menu import render_legacy_menu + + text = render_legacy_menu(tmp_path / "一叶知秋 重构版", legacy_modules()) + assert text.isascii() + assert 'OnAction = "run DxLegacy_bom.vbs"' in text + assert 'OnAction = "run DxLegacy_network.vbs"' in text + assert "D:\\NET_CHECK" not in text +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/legacy/test_menu.py::test_render_legacy_menu_has_relative_runtime_actions -v` + +Expected: FAIL because `dx_productivity.legacy.menu` does not exist. + +- [ ] **Step 3: Write minimal implementation** + +Render one top-level “一叶知秋_重构版” menu and a “旧版功能” submenu. Each generated action script receives `DxToolsHome` as an escaped ASCII/`ChrW` expression and calls a named legacy entry procedure. Do not place the resolved user path in the checked-in template. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/legacy/test_menu.py tests/bridge/test_startup.py::test_generate_startup_assets_uses_vendor_run_actions_from_local_startup -v` + +Expected: PASS; existing RefDes action names and menu routes remain unchanged. + +- [ ] **Step 5: Add VBS contract assertions** + +`LegacyMenu.vbs` must resolve the generated root, reject missing files with a message and diagnostic entry, and never write `SKY_MT`. Add `cscript //nologo tests/vbs/test_legacy_menu.vbs` covering duplicate top-level menu removal, all seven action captions, and missing-asset handling. + +- [ ] **Step 6: Commit** + +```bash +git add src/dx_productivity/legacy/menu.py tests/legacy/test_menu.py integration/dxdesigner795/modules/legacy/LegacyMenu.vbs src/dx_productivity/bridge/startup_assets.py integration/dxdesigner795/MenuAdd.vbs tests/bridge/test_startup.py tests/integration/test_menu_script.py tests/vbs/test_legacy_menu.vbs +git commit -m "feat: add portable legacy menu actions" +``` + +**Approval gate:** inspect the generated menu captions and approve the grouping before enabling any legacy action in the release package. + +### Task 2A: Build the modern compatibility UI shell + +**Files:** +- Create: `src/dx_productivity/ui/legacy_page.py` +- Create: `src/dx_productivity/ui/legacy_controller.py` +- Create: `tests/ui/test_legacy_page.py` +- Create: `tests/ui/test_legacy_controller.py` +- Modify: `src/dx_productivity/ui/app.py` +- Modify: `src/dx_productivity/ui/main_window.py` +- Modify: `src/dx_productivity/ui/theme.py` + +**Interfaces:** +- `LegacyModulePage(module_ids: tuple[str, ...], title: str)` renders a consistent module-card grid with display name, host, compatibility status, resource status, and an action note. +- `LegacyController.modules() -> tuple[LegacyModule, ...]` returns the manifest entries and `resource_status(module_id: str, tool_root: Path) -> str` returns `ready`, `missing`, or `host-only`. +- `LegacyModulePage.launch_requested` emits the module ID; the initial compatibility action shows the DxDesigner menu route and never attempts to execute an EFM outside the 7.9.5 host. + +- [ ] **Step 1: Write the failing Qt test** + +```python +def test_legacy_page_groups_modules_and_shows_compatibility_state(qtbot): + from dx_productivity.ui.legacy_page import LegacyModulePage + + page = LegacyModulePage(("value", "value1", "part-number"), "属性批改") + qtbot.addWidget(page) + assert page.card_titles() == ("Value 修改", "Value1 修改", "Part Number 修改") + assert page.status_for("value") == "兼容接入" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/ui/test_legacy_page.py::test_legacy_page_groups_modules_and_shows_compatibility_state -v` + +Expected: FAIL because the legacy UI page does not exist. + +- [ ] **Step 3: Write minimal implementation** + +Add a reusable page with fixed card geometry, clear host labels, an explicit compatibility badge, resource state, and a single “在 DxDesigner 中打开” action note. Wire navigation indices 1 through 5 to module groups while preserving the existing RefDes and history pages. Keep the old EFM form as the execution surface until a module has a modern adapter. + +- [ ] **Step 4: Run tests to verify it passes** + +Run: `pytest tests/ui/test_legacy_page.py tests/ui/test_legacy_controller.py tests/ui/test_main_window.py -v` + +Expected: PASS for grouping, status text, missing resources, keyboard focus, light/dark themes, and navigation page titles. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/ui/legacy_page.py src/dx_productivity/ui/legacy_controller.py tests/ui/test_legacy_page.py tests/ui/test_legacy_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py src/dx_productivity/ui/theme.py +git commit -m "feat: add legacy compatibility UI shell" +``` + +**Approval gate:** review the five UI groups and confirm that legacy EFM execution remains explicitly host-only until modern adapters are validated. + +### Task 3: Add the EFM/VBS compatibility dispatcher + +**Files:** +- Create: `src/dx_productivity/legacy/dispatcher.py` +- Create: `tests/legacy/test_dispatcher.py` +- Create: `integration/dxdesigner795/modules/legacy/LegacyDispatch.vbs` +- Modify: `src/dx_productivity/bridge/startup_assets.py` +- Modify: `tests/integration/test_vbs_bridge.py` + +**Interfaces:** +- `LegacyAction(module: LegacyModule, resolved_entrypoint: Path, available: bool, error: str | None)`. +- `resolve_legacy_action(tool_root: Path, module_id: str) -> LegacyAction` checks the manifest path and keeps the result inside `tool_root`. +- `render_legacy_action(module_id: str, tool_root: Path) -> str` returns an ASCII Run-action VBS wrapper. + +- [ ] **Step 1: Write the failing test** + +```python +def test_resolve_legacy_action_rejects_escape_and_missing_files(tmp_path): + from dx_productivity.legacy.dispatcher import resolve_legacy_action + + missing = resolve_legacy_action(tmp_path, "bom") + assert missing.available is False + assert missing.error == "missing-entrypoint" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/legacy/test_dispatcher.py::test_resolve_legacy_action_rejects_escape_and_missing_files -v` + +Expected: FAIL because the dispatcher module and result type do not exist. + +- [ ] **Step 3: Write minimal implementation** + +Resolve the manifest entry with `Path.resolve()`, require `resolved.is_relative_to(tool_root.resolve())`, and return a structured unavailable result for missing or escaping entries. Generate wrappers that call `Form` with the resolved absolute entrypoint only after checking `FileSystemObject.FileExists`. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/legacy/test_dispatcher.py -v` + +Expected: PASS for valid paths, missing paths, path escapes, unsupported action kinds, and Chinese/space-containing tool roots. + +- [ ] **Step 5: Add bridge isolation tests** + +Assert that generated legacy actions do not import `RefDesApply.vbs`, do not write `apply-status.json`, and log `legacy.` plus the concrete module ID to the common diagnostics path. Add a VBS test that a missing EFM displays an error and exits before opening a form. + +- [ ] **Step 6: Commit** + +```bash +git add src/dx_productivity/legacy/dispatcher.py tests/legacy/test_dispatcher.py integration/dxdesigner795/modules/legacy/LegacyDispatch.vbs src/dx_productivity/bridge/startup_assets.py tests/integration/test_vbs_bridge.py +git commit -m "feat: isolate legacy form dispatch" +``` + +**Approval gate:** approve the compatibility-only behavior and confirm that legacy actions remain outside the RefDes apply/restore transaction. + +### Task 4: Add module-specific compatibility checks and user support matrix + +**Files:** +- Create: `tests/integration/test_legacy_modules.py` +- Create: `src/dx_productivity/legacy/acceptance.py` +- Create: `docs/testing/yiyezhqiu-legacy-acceptance.md` +- Create: `docs/user/一叶知秋_重构版_模块支持矩阵.md` +- Modify: `docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx` through the existing document update script +- Modify: `tests/docs/test_user_guide.py` + +**Interfaces:** +- `legacy_acceptance_cases() -> tuple[LegacyAcceptanceCase, ...]` returns one case per module with `module_id`, `host`, `expected_entrypoint`, `read_only`, and `requires_live_795`. +- The support matrix records `兼容接入`, `重构中`, or `已验证` and never infers live support from Python mocks. + +- [ ] **Step 1: Write the failing test** + +```python +def test_acceptance_matrix_has_one_case_per_manifest_module(): + from dx_productivity.legacy.manifest import legacy_modules + from dx_productivity.legacy.acceptance import legacy_acceptance_cases + + assert {case.module_id for case in legacy_acceptance_cases()} == { + item.module_id for item in legacy_modules() + } + assert all(case.requires_live_795 for case in legacy_acceptance_cases()) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/integration/test_legacy_modules.py::test_acceptance_matrix_has_one_case_per_manifest_module -v` + +Expected: FAIL because the acceptance-case module does not exist. + +- [ ] **Step 3: Write minimal implementation** + +Add explicit acceptance cases. Mark BOM, Value, Value1, Part Number, property visibility, and network actions as DxDesigner host cases; mark PCB assembly reference movement as an Expedition PCB case. Keep all cases `兼容接入` until the live checklist is completed. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/integration/test_legacy_modules.py tests/docs/test_user_guide.py -v` + +Expected: PASS and the guide contains the product name, module matrix, backup warning, and “实机验收待完成” wording. + +- [ ] **Step 5: Write the live acceptance checklist** + +For each DxDesigner module record startup import, menu click, sample-project result, save behavior, error path, and repeat-start behavior. For PCB record the required host, menu section, active-document precondition, and no-DxDesigner fallback. Do not mark a case verified without a real 7.9.5 run. + +- [ ] **Step 6: Commit** + +```bash +git add src/dx_productivity/legacy/acceptance.py tests/integration/test_legacy_modules.py docs/testing/yiyezhqiu-legacy-acceptance.md docs/user/一叶知秋_重构版_模块支持矩阵.md docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx tests/docs/test_user_guide.py +git commit -m "docs: add legacy module acceptance matrix" +``` + +**Approval gate:** approve each module's live acceptance result before its status changes from `兼容接入`. + +### Task 5: Optional modernization of one validated module at a time + +**Files:** +- Create per-module adapter under `src/dx_productivity/legacy/adapters/` +- Create per-module domain/UI tests under `tests/legacy/adapters/` +- Modify the corresponding VBS bridge and `src/dx_productivity/ui/main_window.py` only after the module compatibility case is accepted + +**Interfaces:** +- Each adapter exposes `snapshot()`, `build_preview()`, `apply()`, and `rollback()` with module-specific dataclasses; it must not reuse RefDes-specific `AnnotationPlan` for non-RefDes data. +- A module is promoted to `重构中` only after a behavior comparison against its original EFM/VBS result on the same sample design. + +- [ ] **Step 1: Write a behavior-capture test** + +Capture one known input/output pair from the validated legacy module and assert the adapter produces the same visible result, including row counts and changed fields. + +- [ ] **Step 2: Run the capture test before implementation** + +Run the concrete adapter test for the selected module, for example `pytest tests/legacy/adapters/test_bom.py -v` when migrating BOM. + +Expected: FAIL because the adapter has not been created. + +- [ ] **Step 3: Implement the smallest adapter** + +Reuse common diagnostics, path handling, and backup helpers. Keep the old EFM action available as a fallback until the adapter passes both automated and live acceptance. + +- [ ] **Step 4: Run automated and live checks** + +Run the module test, the complete existing test suite, and the matching section in `docs/testing/yiyezhqiu-legacy-acceptance.md`. + +- [ ] **Step 5: Commit and request module approval** + +```bash +git add src/dx_productivity/legacy/adapters tests/legacy/adapters src/dx_productivity/ui/main_window.py integration/dxdesigner795/modules +git commit -m "feat: modernize validated legacy module" +``` + +Do not start the next module until the current module is approved for `已验证` or explicitly returned to `兼容接入`. diff --git a/docs/superpowers/plans/2026-09-11-yiyezhqiu-online-update.md b/docs/superpowers/plans/2026-09-11-yiyezhqiu-online-update.md new file mode 100644 index 0000000..d6fa361 --- /dev/null +++ b/docs/superpowers/plans/2026-09-11-yiyezhqiu-online-update.md @@ -0,0 +1,351 @@ +# 一叶知秋_重构版在线更新实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 在便携式 Windows 发布包中加入可配置的版本检查、校验下载、旁路切换和失败回滚能力。 + +**Architecture:** 更新检查与主程序 UI 解耦,使用标准库 HTTP/文件读取和后台线程获取 manifest;更新器以当前同一个 EXE 的 `update` 子命令运行,等待主程序退出后在旁路目录完成替换。版本包永远先下载、校验和备份,再经过人工确认切换。 + +**Tech Stack:** Python 3.12, PySide6, `urllib.request`, `hashlib`, `json`, `tempfile`, `zipfile`, PyInstaller onedir, pytest, pytest-qt。 + +**Spec:** `docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md` + +## Global Constraints + +- 用户可见产品名为“一叶知秋_重构版”;Python 包名和现有 RefDes 协议标识保持不变。 +- 版本比较使用 SemVer,不按文件名或文件修改时间判断新旧。 +- 默认行为是自动检查、人工安装;不做静默安装和运行中覆盖自身 EXE。 +- 下载包必须验证 SHA-256;生产 stable 清单必须验证 Ed25519 签名,签名失败不可绕过。 +- 更新失败只能恢复版本目录,不修改 DxDesigner 原理图工程。 +- 不保存账号密码、访问令牌或私有存储凭据。 +- 兼容 HTTPS、`file://` 本地模拟源和 Windows 只读/共享目录;联网实测等待用户提供真实地址。 +- 所有新增 UI、网络和更新操作必须有离线/失败状态和诊断日志。 + +--- + +### Task 1: 固化产品版本与 manifest 数据模型 + +**Files:** +- Create: `src/dx_productivity/update/__init__.py` +- Create: `src/dx_productivity/update/models.py` +- Create: `tests/update/test_models.py` +- Modify: `src/dx_productivity/__init__.py` +- Modify: `src/dx_productivity/ui/main_window.py` + +**Interfaces:** +- `PRODUCT_ID = "yiyezhqiu-refactored"` and `DISPLAY_NAME = "一叶知秋_重构版"`. +- `SemVer.parse(value: str) -> SemVer` and `SemVer.is_newer_than(other: SemVer) -> bool`. +- `UpdateManifest.from_mapping(data: Mapping[str, object]) -> UpdateManifest` with fields `product`, `version`, `channel`, `min_supported_version`, `package_url`, `sha256`, `release_notes`, `published_at`, and optional `signature`. +- `UpdateManifest.is_compatible_with(current: SemVer) -> bool` rejects a current version below `min_supported_version` and mismatched `product`. + +- [ ] **Step 1: Write the failing test** + +```python +def test_manifest_parses_semver_and_rejects_wrong_product(): + from dx_productivity.update.models import UpdateManifest + + manifest = UpdateManifest.from_mapping({ + "product": "yiyezhqiu-refactored", + "version": "1.1.0", + "channel": "stable", + "min_supported_version": "1.0.0", + "package_url": "file:///release.zip", + "sha256": "a" * 64, + "release_notes": "模块迁移", + "published_at": "2026-09-11", + }) + assert manifest.version.is_newer_than(manifest.min_supported_version) + assert manifest.is_compatible_with("1.0.0") +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/update/test_models.py::test_manifest_parses_semver_and_rejects_wrong_product -v` + +Expected: FAIL with `ModuleNotFoundError: No module named 'dx_productivity.update'`. + +- [ ] **Step 3: Write minimal implementation** + +Implement strict three-part SemVer parsing with optional prerelease identifiers, lowercase product/channel normalization, 64-hex SHA-256 validation, and explicit `ValueError` messages for missing or malformed fields. Keep `__version__` as the current package source of truth. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/update/test_models.py -v` + +Expected: PASS for stable/prerelease ordering, invalid versions, wrong product, invalid digest, and minimum-version rejection. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/update src/dx_productivity/__init__.py src/dx_productivity/ui/main_window.py tests/update/test_models.py +git commit -m "feat: add update manifest model" +``` + +**Approval gate:** approve the product ID and SemVer policy before any network code is added. + +### Task 2: Implement manifest loading and update checks + +**Files:** +- Create: `src/dx_productivity/update/service.py` +- Create: `tests/update/test_service.py` +- Modify: `src/dx_productivity/update/models.py` + +**Interfaces:** +- `UpdateCheckResult(status: str, current: SemVer, manifest: UpdateManifest | None, message: str)`. +- `UpdateService.fetch_manifest(source: str, timeout: float = 10.0) -> UpdateManifest`. +- `UpdateService.check(source: str, current: SemVer, channel: str = "stable") -> UpdateCheckResult`. +- Test helper `write_manifest(path: Path, package_url: str, version: str = "1.1.0") -> None` writes a valid UTF-8 manifest fixture. + +- [ ] **Step 1: Write the failing test** + +```python +def test_check_returns_available_for_file_manifest(tmp_path): + manifest_path = tmp_path / "manifest.json" + write_manifest(manifest_path, "file:///release.zip") + + from dx_productivity.update.service import UpdateService + result = UpdateService().check(manifest_path.as_uri(), "1.0.0") + assert result.status == "available" + assert result.manifest is not None + assert str(result.manifest.version) == "1.1.0" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/update/test_service.py::test_check_returns_available_for_file_manifest -v` + +Expected: FAIL because `UpdateService` is not defined. + +- [ ] **Step 3: Write minimal implementation** + +Use `urllib.request.urlopen` with a 10-second timeout for HTTPS and `Path.from_uri` handling for `file://` sources. Decode UTF-8 JSON, pass the mapping to `UpdateManifest.from_mapping`, filter by channel, and return `up-to-date`, `available`, `incompatible`, or `error` without raising network exceptions to the UI. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/update/test_service.py -v` + +Expected: PASS for offline errors, malformed JSON, wrong product, prerelease channel filtering, and equal/current versions. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/update/service.py src/dx_productivity/update/models.py tests/update/test_service.py +git commit -m "feat: check remote update manifests" +``` + +**Approval gate:** approve the manifest URL forms and error behavior before adding downloads. + +### Task 3: Add package download, digest/signature verification, and staging + +**Files:** +- Create: `src/dx_productivity/update/verification.py` +- Create: `src/dx_productivity/update/stager.py` +- Create: `tests/update/test_verification.py` +- Create: `tests/update/test_stager.py` +- Modify: `pyproject.toml` to add `cryptography>=42,<46` +- Modify: `packaging/DxDesignerTools.spec` + +**Interfaces:** +- `sha256_file(path: Path) -> str`. +- `verify_ed25519(public_key: bytes, payload: bytes, signature: bytes) -> bool`. +- `UpdateStager.download_and_verify(manifest: UpdateManifest, destination: Path) -> Path` returns a verified ZIP path and raises `UpdateVerificationError` before any install action. +- Test helper `_make_manifest(package_url: str, sha256: str, signature: str | None = None) -> UpdateManifest` constructs a validated manifest for staging tests. + +- [ ] **Step 1: Write the failing tests** + +```python +def test_download_and_verify_rejects_digest_mismatch(tmp_path): + from dx_productivity.update.stager import UpdateStager, UpdateVerificationError + package_path = tmp_path / "release.zip" + package_path.write_bytes(b"PK\\x03\\x04test") + manifest = _make_manifest(package_path.as_uri(), "0" * 64) + with pytest.raises(UpdateVerificationError, match="sha256"): + UpdateStager().download_and_verify(manifest, tmp_path / "download") +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `pytest tests/update/test_verification.py tests/update/test_stager.py -v` + +Expected: FAIL because the verification and staging modules do not exist. + +- [ ] **Step 3: Write minimal implementation** + +Stream downloads to a `.part` file under the requested destination, compute SHA-256 while writing, atomically rename the verified ZIP, and reject non-ZIP content, path traversal entries, digest mismatch, invalid signatures, or destination paths outside `%LOCALAPPDATA%\\DxProductivity\\updates`. + +Use `cryptography` Ed25519 verification when `manifest.signature` is present. Stable manifests without a valid signature are rejected; local development manifests may omit signatures only when the caller explicitly selects the `development` channel. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pytest tests/update/test_verification.py tests/update/test_stager.py -v` + +Expected: PASS for matching/mismatching digests, valid/invalid signatures, interrupted downloads, ZIP traversal, duplicate destination versions, and Chinese/space-containing paths. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/update/verification.py src/dx_productivity/update/stager.py tests/update/test_verification.py tests/update/test_stager.py pyproject.toml packaging/DxDesignerTools.spec +git commit -m "feat: verify and stage update packages" +``` + +**Approval gate:** inspect the signature/public-key handling and approve the stable-channel rejection rule. + +### Task 4: Implement the post-exit updater and rollback transaction + +**Files:** +- Create: `src/dx_productivity/update/installer.py` +- Create: `tests/update/test_installer.py` +- Modify: `src/dx_productivity/bridge/launcher.py` +- Modify: `tests/bridge/test_launcher.py` +- Modify: `packaging/build_release.ps1` + +**Interfaces:** +- `InstallPlan(current_root: Path, staged_zip: Path, backup_root: Path, restart_command: tuple[str, ...])`. +- `UpdateInstaller.install(plan: InstallPlan) -> InstallResult` where `InstallResult.state` is `installed`, `rolled-back`, or `failed`. +- Launcher dispatches `DxDesignerTools.exe update --plan %LOCALAPPDATA%\\DxProductivity\\updates\\install-plan.json` without importing Qt. +- Test helper `make_plan(tmp_path: Path, restart_probe_exit_code: int) -> InstallPlan` creates old/new portable roots and a restart probe command that exits with the requested code. + +- [ ] **Step 1: Write the failing test** + +```python +def test_install_plan_restores_previous_root_when_restart_probe_fails(tmp_path): + from dx_productivity.update.installer import UpdateInstaller + plan = make_plan(tmp_path, restart_probe_exit_code=1) + result = UpdateInstaller().install(plan) + assert result.state == "rolled-back" + assert (plan.current_root / "DxDesignerTools.exe").read_bytes() == b"old" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/update/test_installer.py::test_install_plan_restores_previous_root_when_restart_probe_fails -v` + +Expected: FAIL because the installer transaction is not implemented. + +- [ ] **Step 3: Write minimal implementation** + +Write a JSON install plan, wait for the parent PID to exit, copy the current portable directory to a timestamped backup, extract the staged ZIP into a sibling directory, validate required files, atomically rename current to backup and staged to current, run a short `--smoke-test-ms 1000` restart probe, and restore backup on a nonzero exit or missing executable. + +The updater must never delete the only known-good directory. Retain the most recent two backups and record every state transition under `%LOCALAPPDATA%\\DxProductivity\\updates\\install.log`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pytest tests/update/test_installer.py tests/bridge/test_launcher.py -v` + +Expected: PASS for install, already-running parent, missing ZIP, failed smoke probe, rollback, repeated install, and UNC/Chinese paths. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/update/installer.py tests/update/test_installer.py src/dx_productivity/bridge/launcher.py tests/bridge/test_launcher.py packaging/build_release.ps1 +git commit -m "feat: add rollbackable portable updater" +``` + +**Approval gate:** approve the backup retention count and smoke-probe rollback rule before wiring the UI. + +### Task 5: Add Settings update UI and background coordination + +**Files:** +- Create: `src/dx_productivity/ui/settings_page.py` +- Create: `src/dx_productivity/ui/settings_controller.py` +- Create: `tests/ui/test_settings_page.py` +- Create: `tests/ui/test_settings_controller.py` +- Modify: `src/dx_productivity/ui/app.py` +- Modify: `src/dx_productivity/ui/main_window.py` +- Modify: `src/dx_productivity/ui/theme.py` + +**Interfaces:** +- `SettingsController.check_updates(source: str, channel: str) -> None` emits `check_started`, `check_finished(UpdateCheckResult)`, and `install_requested(UpdateManifest)`. +- `SettingsPage` exposes `source_input`, `channel_combo`, `auto_check_checkbox`, `check_button`, `install_button`, `version_label`, `status_label`, and `release_notes_view`. +- Settings persist only non-secret values under `%LOCALAPPDATA%\\DxProductivity\\settings.json`. +- Test helper `make_manifest(version: str) -> UpdateManifest` returns a stable-channel manifest with a valid digest and release notes. + +- [ ] **Step 1: Write the failing Qt tests** + +```python +def test_settings_page_requires_second_confirmation_before_install(qtbot): + from dx_productivity.ui.settings_page import SettingsPage + page = SettingsPage(current_version="1.0.0") + qtbot.addWidget(page) + page.show_update(make_manifest("1.1.0")) + assert page.install_button.isEnabled() + assert page.install_requested_emissions == 0 +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `pytest tests/ui/test_settings_page.py tests/ui/test_settings_controller.py -v` + +Expected: FAIL because the settings page/controller do not exist. + +- [ ] **Step 3: Write minimal implementation** + +Add the Settings page at the existing navigation index 7. On check, show `检查中`, then `已是最新`, `发现新版本`, `离线`, or `检查失败`. On install, show release notes and a first confirmation; after download and verification require a second confirmation before launching the updater. Disable install on incompatible, unsigned stable, digest-failed, or missing-package results. + +Use a worker `QThread` or `QRunnable` for network and staging work so the Qt event loop remains responsive. Auto-check once after the main window is shown only when the checkbox is enabled and the last check is older than 24 hours. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pytest tests/ui/test_settings_page.py tests/ui/test_settings_controller.py tests/ui/test_main_window.py -v` + +Expected: PASS for state transitions, double confirmation, disabled install, persistence, theme refresh, and no-network UI behavior. + +- [ ] **Step 5: Commit** + +```bash +git add src/dx_productivity/ui/settings_page.py src/dx_productivity/ui/settings_controller.py tests/ui/test_settings_page.py tests/ui/test_settings_controller.py src/dx_productivity/ui/app.py src/dx_productivity/ui/main_window.py src/dx_productivity/ui/theme.py +git commit -m "feat: add update controls to settings" +``` + +**Approval gate:** review the settings wording and confirm auto-check does not imply silent installation. + +### Task 6: Package, document, and validate with a local update source + +**Files:** +- Create: `tests/update/test_local_update_flow.py` +- Create: `docs/testing/yiyezhqiu-update-acceptance.md` +- Create: `docs/user/一叶知秋_重构版_更新说明.md` +- Modify: `packaging/DxDesignerTools.spec` +- Modify: `packaging/build_release.ps1` +- Modify: `tests/packaging/test_built_release.py` +- Modify: `tests/docs/test_user_guide.py` + +**Interfaces:** +- `packaging/build_release.ps1` emits the current version, `SHA256SUMS.txt`, and a manifest template with `package_url` and `sha256` filled only when a release artifact exists. +- The acceptance document records local `file://` update success, digest failure, offline behavior, rollback, and stable signature rejection. +- Test helpers `make_local_release_pair(tmp_path: Path) -> tuple[Path, Path, Path]`, `run_update_check_and_install(root: Path, manifest: Path) -> InstallResult`, and `read_version(root: Path) -> str` create and exercise a complete local update fixture. + +- [ ] **Step 1: Write the failing end-to-end test** + +```python +def test_local_manifest_updates_older_portable_copy(tmp_path): + old_root, new_zip, manifest = make_local_release_pair(tmp_path) + result = run_update_check_and_install(old_root, manifest) + assert result.state == "installed" + assert read_version(old_root) == "1.1.0" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/update/test_local_update_flow.py -v` + +Expected: FAIL because the packaged updater and manifest generation are not wired together. + +- [ ] **Step 3: Write minimal packaging and documentation implementation** + +Add version metadata to the release root, generate the checksum file, document how to host the ZIP and manifest on HTTPS or a read-only share, and include explicit warnings that live DxDesigner 7.9.5 compatibility is independent from updater success. + +- [ ] **Step 4: Run the full verification set** + +Run: `pytest tests/update tests/bridge/test_launcher.py tests/packaging tests/docs/test_user_guide.py -v` and then `powershell -ExecutionPolicy Bypass -File packaging/build_release.ps1 -Clean`. + +Expected: all tests PASS, the release ZIP contains updater code and manifest metadata, and a local file-source update installs then rolls back correctly. + +- [ ] **Step 5: Commit and request release approval** + +```bash +git add tests/update/test_local_update_flow.py docs/testing/yiyezhqiu-update-acceptance.md docs/user/一叶知秋_重构版_更新说明.md packaging/DxDesignerTools.spec packaging/build_release.ps1 tests/packaging/test_built_release.py tests/docs/test_user_guide.py +git commit -m "test: validate local portable update flow" +``` + +**Approval gate:** approve the local-source evidence before using the real storage address and publishing a stable manifest. diff --git a/docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md b/docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md new file mode 100644 index 0000000..5ae7997 --- /dev/null +++ b/docs/superpowers/specs/2026-09-01-dxdesigner-795-refdes-design.md @@ -0,0 +1,334 @@ +# DxDesigner 7.9.5 Automatic Reference Designator Tool + +Date: 2026-09-01 + +## 1. Purpose + +Build the first module of a maintainable DxDesigner 7.9.5 productivity suite: automatic reference designator assignment with preview, validation, safe write-back, and recovery. + +The tool replaces the legacy workflow that copies selected reference designators to Excel, generates values manually, and pastes them back. Excel is not part of the new annotation workflow. + +## 2. Compatibility Baseline + +DxDesigner/Expedition Enterprise 7.9.5 is the only supported schematic integration baseline for this phase. + +The installation and import flow must remain compatible with the method demonstrated by the supplied legacy tool: + +1. The user opens DxDesigner 7.9.5. +2. The user opens `Settings -> Run at Startup`. +3. The user adds one `MenuAdd.vbs` file to the Scripts list. +4. After DxDesigner restarts, one `Dx Productivity` menu appears on the Sheet Menu Bar. + +The integration must not require a newer Xpedition add-in framework, a copied DLL from another release, COM re-registration, or a project-format upgrade. + +`MenuAdd.vbs` uses only interfaces already demonstrated in the legacy package: + +- `Scripting.GetEnvVariable` +- `CommandBars("Sheet Menu Bar").Controls.Add` +- menu control captions and `OnAction` +- the 7.9.5 internal scripting host + +The release is a portable directory distributed as one ZIP archive. It does not use an installer, registry entries, environment variables, administrator privileges, or a system Python installation. `MenuAdd.vbs` is placed at the root of the portable directory and resolves every bundled file from its own loaded script location; it contains no `D:\NET_CHECK` or other fixed installation path. + +The user extracts the complete directory to a stable location and imports the root `MenuAdd.vbs`. Moving the directory later requires selecting the script again in `Settings -> Run at Startup`; replacing the files in place does not require re-importing the script. + +## 3. Compatibility Probe + +The first implementation milestone is a read-only 7.9.5 probe imported through the exact startup-script flow above. It must not change a schematic. + +The probe verifies: + +- the imported script can add and remove its own menu entries without duplication; +- the 7.9.5 script host exposes a reliable loaded-script location that can be used as the portable-directory root; +- a menu item can enter the internal VBS bridge and launch the bundled executable by a path relative to that root; +- `ActiveView.Query(VDM_COMP, VD_SELECTED)` returns selected components; +- `Application.DesignComponents` enumerates the full design; +- component reference designator, sheet number, X/Y position, attributes, full path, and stable identity are readable; +- the bridge can hold component object references while the Python process is open; +- UTF-8 snapshot and result files can be exchanged through the user-local run directory. + +The release menu action uses the first 7.9.5-native route proven by the probe. The permitted routes, in order, are: + +1. a named bridge procedure in the imported startup VBS; +2. the 7.9.5 `Run` script action; +3. the proven `Form` action with a minimal 7.9.5 EFM launcher. + +No unverified route is shipped. If the first two routes are unavailable, the launcher EFM is created or adapted using the 7.9.5 form format; it is not copied from a newer release. + +## 4. Architecture + +```text +DxDesigner 7.9.5 + -> imported MenuAdd.vbs + -> internal VBS bridge + -> UTF-8 snapshot + in-memory component map + -> bundled DxDesignerTools.exe/PySide6 application + -> validated bridge_id/new_refdes result + -> VBS write-back and full-design verification +``` + +### 4.1 VBS integration layer + +The VBS layer owns every DxDesigner COM/API call. It reads the current design, launches Python, waits for the result, revalidates the snapshot, applies changes, verifies the design, and rolls back on failure. + +Python does not attach directly to `ViewDraw.Application`. This avoids 32-bit versus 64-bit COM registration and licensing incompatibilities between DxDesigner 7.9.5 and modern Python. + +### 4.2 Python domain layer + +The Python domain layer is independent of DxDesigner. It parses snapshots, groups components, computes deterministic annotation plans, validates collisions, and produces an immutable change set. + +This layer has no GUI imports and can be exhaustively unit tested with fixtures. + +### 4.3 Python UI layer + +The desktop UI uses PySide6 and a local style sheet. It implements the approved three-column workbench: + +- suite navigation on the left; +- annotation rules in the center; +- live old-to-new preview on the right. + +The source remains runnable with Python 3.12 for development. The release application is packaged as a Windows x64 PyInstaller `onedir` distribution containing Python 3.12, PySide6, Qt plug-ins, qtawesome, and all application modules. Packaging does not change the VBS bridge protocol. + +### 4.4 Portable release layout + +The release archive expands to this structure: + +```text +DxDesigner productivity tools\ + MenuAdd.vbs + RefDesBridge.vbs + DxDesignerTools.exe + _runtime\ + docs\ + resources\ +``` + +`MenuAdd.vbs`, `RefDesBridge.vbs`, and `DxDesignerTools.exe` remain at the portable root so path resolution and user support stay simple. `_runtime` contains the bundled interpreter and dependencies and is not user-editable. The complete directory may contain Chinese characters and spaces. + +Transient run files, backups, history, logs, and per-user preferences remain under `%LOCALAPPDATA%\DxProductivity`. The portable directory therefore remains replaceable and may be read-only at runtime. + +## 5. Bridge Protocol + +Each run uses a unique directory: + +```text +%LOCALAPPDATA%\DxProductivity\runs\\ + request.json + result.tsv + apply-status.json +``` + +VBS writes `request.json` as UTF-8 using a deterministic JSON escaping helper. Python writes an ordered `result.tsv` apply schedule with five constrained fields: `sequence`, `bridge_id`, `expected_refdes`, `new_refdes`, and `final_refdes`. Tabs and line breaks are illegal in every result field. + +Each sequence number is unique and contiguous from 1. A bridge ID normally appears once. It may appear twice only when a validated reannotation cycle requires a temporary placeholder step followed by the final assignment. VBS verifies `expected_refdes` immediately before every step and verifies `final_refdes` after the complete schedule. + +Each snapshot component contains: + +- ephemeral `bridge_id` assigned by the current VBS run; +- stable UID when exposed by 7.9.5; +- hierarchical full path as an identity fallback; +- sheet number and current-view membership; +- X and Y schematic coordinates; +- current reference designator; +- symbol-level default reference designator or prefix when available; +- selection state; +- part number and Value for preview; +- lock or protection state when exposed by 7.9.5. + +VBS retains an in-memory `bridge_id -> component object` map while Python is open. Result rows never rely on COM enumeration order. + +Before write-back, VBS confirms that the active design, component identity, component count in scope, and original reference designators still match the snapshot. A mismatch invalidates the plan and requires a refresh. + +## 6. Annotation Behavior + +### 6.1 Scope + +The UI supports three explicit scopes: + +- selected components, which is the default; +- current sheet; +- full design. + +If the selected scope is empty, Apply remains disabled. The tool does not silently fall back to another scope. + +### 6.2 Processing mode + +The default mode fills only unannotated components: + +- blank reference designators; +- placeholders matching a leading alphabetic prefix followed by one or more question marks, such as `R?`, `C??`, or `TP?`. + +Existing formal reference designators are preserved. A separate, explicit mode reannotates every eligible component in scope. + +### 6.3 Prefix resolution + +Prefix resolution is deterministic: + +1. use the alphabetic prefix in the current placeholder; +2. otherwise use the symbol-level default reference designator/prefix exposed by 7.9.5; +3. otherwise require an explicit prefix in the preview table. + +An unresolved prefix is a blocking validation error. Prefix comparison is case-insensitive and output is normalized to uppercase. + +### 6.4 Multi-unit components + +All symbols that represent the same logical component are grouped by stable component identity. They receive one base reference designator. Symbol units or gates do not consume additional sequence numbers. + +If 7.9.5 does not expose a stable UID, the compatibility adapter derives a stable grouping key from the hierarchical component path and validated component metadata. Ambiguous groups are blocked rather than guessed. + +### 6.5 Sorting + +The default order is: + +1. numeric sheet number ascending; +2. schematic Y coordinate from top to bottom; +3. X coordinate from left to right within the same visual row; +4. stable identity as the final deterministic tie-breaker. + +Because schematic Y-axis direction is API-dependent, the compatibility adapter normalizes coordinates so larger visual height always sorts first. Components are grouped into visual rows using a default 5 mm tolerance. The user can change the tolerance. + +Alternative orders are available for left-to-right column scanning and reverse directions. + +### 6.6 Numbering modes + +Continuous mode is the default. Each prefix owns an independent sequence beginning at 1 unless the user changes the start value. Numbers already used anywhere outside the target set are skipped. + +Page mode uses: + +```text +number = numeric_sheet_number * page_step + page_start +``` + +The defaults are `page_step = 100` and `page_start = 1`, so sheet 3 starts at 301. Each prefix has an independent page sequence. Non-numeric sheet identifiers require an explicit numeric mapping before Apply. + +### 6.7 Collision rules + +Validation is case-insensitive and covers: + +- duplicates inside the proposed change set; +- collisions with components outside the target set; +- illegal or empty prefixes; +- invalid numeric ranges; +- duplicate existing formal reference designators in the source design; +- multiple proposed values for one logical component. + +Blocking issues disable Apply. Warnings remain selectable and can locate the affected schematic component. + +## 7. Safe Apply and Recovery + +Every Apply operation follows this sequence: + +1. revalidate the snapshot against the active design; +2. run all collision and format checks again; +3. write a timestamped backup mapping under `%LOCALAPPDATA%\DxProductivity\backups`; +4. apply changes using the in-memory component map; +5. re-enumerate the full design and verify every expected reference designator; +6. write a machine-readable apply status and append an operation-history entry. + +Fill-only plans normally write directly because they cannot swap existing formal identifiers. + +Full reannotation plans are ordered as a dependency graph. Acyclic moves are applied first. Cycles use the component prefix placeholder, such as `R?`, as a temporary value, then complete the cycle. This uses a placeholder format already accepted by DxDesigner 7.9.5 instead of inventing a new temporary reference-designator syntax. + +If any assignment or verification fails, VBS restores every component from the backup mapping and verifies the restoration. A rollback failure is reported prominently with the backup path and the exact remaining mismatch. + +The operation-history view exposes Restore Last Annotation. Restore performs the same preflight, backup, apply, and verification sequence; it is not a blind file replay. + +## 8. User Interface and Visual Acceptance + +The approved mockup is the visual baseline. The release implementation follows these measurable requirements derived from Apple Human Interface Guidelines while remaining a Windows desktop application: + +- 13 pt default content text and no essential text below 10 pt; +- approximately 28 by 28 pt default desktop controls and no interactive target below 20 by 20 pt; +- 16 px simplified line icons with consistent weight and optical alignment; +- tooltips and accessible names for icon-only controls; +- one semantic use per status color; +- text contrast of at least 4.5:1 for normal text; +- icons or text in addition to color for every status; +- light, dark, and increased-contrast-compatible palettes; +- complete keyboard navigation with visible focus; +- no clipping or overlap at 100%, 125%, and 150% Windows display scaling; +- a resizable window with a minimum supported content area of 1100 by 700 logical pixels; +- no required command placed only at the bottom edge of the window; +- no automatic, blinking, bouncing, or decorative motion. + +Interface icons use a cross-platform icon set with Apple-like semantic consistency. Apple SF Symbols are a design reference only and are not redistributed in the Windows application. + +Official design references: + +- [Designing for macOS](https://developer.apple.com/design/human-interface-guidelines/designing-for-macos) +- [Layout](https://developer.apple.com/design/human-interface-guidelines/layout) +- [Typography](https://developer.apple.com/design/human-interface-guidelines/typography) +- [Color](https://developer.apple.com/design/human-interface-guidelines/color) +- [Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility) +- [Icons](https://developer.apple.com/design/human-interface-guidelines/icons) + +## 9. Error Handling + +Errors are divided into three levels: + +- blocking: Apply is disabled, for example duplicate output or missing prefix; +- warning: the plan remains applicable after review, for example a nonstandard existing designator outside scope; +- informational: no action required, for example a locked component preserved by policy. + +The UI shows an icon, short message, affected component count, and location action. Technical details and bridge logs are available in a diagnostics view and retained per run. Normal users do not need to inspect raw JSON, TSV, COM error codes, or Python tracebacks. + +If the bundled executable or runtime is missing, corrupt, or cannot start, the VBS bridge shows a concise message with the resolved executable path and exits without changing the design. + +## 10. Testing Strategy + +### 10.1 Automated domain tests + +Tests cover: + +- placeholder recognition and prefix normalization; +- continuous and page numbering; +- occupied-number skipping; +- row tolerance and every sort direction; +- numeric and non-numeric sheet identifiers; +- multi-unit grouping; +- duplicate and collision detection; +- deterministic output for equal coordinates; +- reannotation dependency graphs and cycles; +- backup and restore plan generation. + +### 10.2 Bridge contract tests + +Pure VBS helpers are tested with `cscript` where possible. Tests cover UTF-8, JSON escaping, result parsing, invalid rows, duplicate or noncontiguous sequence numbers, unknown bridge IDs, illegal repeated bridge steps, stale snapshots, and simulated assignment failures. + +Python contract tests use captured 7.9.5-compatible fixtures and never require a live DxDesigner instance. + +Portable-path tests cover a root containing Chinese characters and spaces, absence of `DXTOOLS_HOME`, relocation followed by script re-import, and a missing or incomplete `_runtime` directory. + +### 10.3 UI tests + +Qt tests cover default selections, scope changes, preview filtering, blocking-error behavior, keyboard tab order, light/dark themes, and Apply confirmation for full reannotation. + +Screenshots are checked at representative 1100 by 700 and 1440 by 900 window sizes under 100%, 125%, and 150% scaling. Text, controls, and tables must not overlap or clip. + +### 10.4 Live 7.9.5 acceptance + +The user runs the compatibility probe and a sample-project acceptance checklist on the target DxDesigner 7.9.5 installation. Live acceptance covers startup-script import, menu creation, selected/current/full scopes, coordinate order, write-back, duplicate prevention, rollback, restoration, Chinese installation paths, and paths containing spaces. + +No release is marked 7.9.5-compatible solely from mocked COM tests. + +### 10.5 Offline release acceptance + +The packaged directory is tested on a clean Windows 11 x64 environment with network access disabled and no Python installation. Acceptance requires startup from the root `MenuAdd.vbs`, successful Qt plug-in and icon loading, correct access to `%LOCALAPPDATA%`, and no dependency on files outside the portable directory other than Windows system components and DxDesigner 7.9.5. + +## 11. Deliverables for Phase One + +- 7.9.5 compatibility probe; +- portable Windows x64 ZIP containing the bundled Python runtime and all dependencies; +- copy, startup-script import, upgrade-in-place, and folder-removal instructions; +- `MenuAdd.vbs` and the verified 7.9.5 bridge adapter; +- Python source and dependency metadata; +- automatic reference designator GUI; +- annotation domain tests and bridge contract tests; +- live 7.9.5 acceptance checklist; +- user guide for installation, annotation, preview, Apply, and Restore. + +## 12. Non-Goals + +This phase does not implement Value/Value1/Part Number editing, attribute visibility, design audits, network navigation, BOM generation, BOM-to-schematic navigation, or Expedition PCB assembly text placement. Those modules reuse the verified bridge and shared application shell in later phase-specific designs. + +This phase does not import code or binaries from newer Xpedition releases and does not modify the DxDesigner project format. diff --git a/docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md b/docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md new file mode 100644 index 0000000..e11eb34 --- /dev/null +++ b/docs/superpowers/specs/2026-09-11-yiyezhqiu-migration-update-design.md @@ -0,0 +1,210 @@ +# 一叶知秋_重构版:旧功能迁移与在线更新设计 + +日期:2026-09-11 + +状态:待审阅 + +## 1. 目标与范围 + +“一叶知秋_重构版”以当前自动位号分配工具为主程序宿主,逐步恢复原始“一叶知秋”中的其他功能,并增加可控的在线更新能力。 + +本阶段的目标不是一次性重写所有旧工具,而是先让旧功能在 DxDesigner 7.9.5 中可用,再按模块逐步迁移到当前的桥接、预览、校验、备份和回滚框架。 + +纳入迁移范围的旧功能: + +- BOM 导出; +- Value / Value1 修改; +- Part Number 修改; +- PartName / PartLabel 显示属性处理; +- 网络跨页互动、网络列表和网络检查; +- Expedition PCB 装配位号移动,作为独立 PCB 模块。 + +当前自动位号分配、预览、应用、历史和恢复功能保持现状,不因旧模块迁移而改变既有行为。 + +不纳入本阶段的内容: + +- 不修改 DxDesigner 7.9.5 的工程格式; +- 不引入新版 Xpedition 专用 API 或 DLL; +- 不把旧 EFM 文件直接当作已验证的现代 Python 模块; +- 不做无提示的静默更新或强制覆盖; +- 不要求中心库、`.lmc` 或额外许可证作为普通 DxDesigner 模块的前置条件。 + +## 2. 产品与版本身份 + +用户可见产品名统一为“一叶知秋_重构版”。当前 Python 包名、模块名和内部协议标识暂不改名,以避免破坏现有脚本、测试和便携发布结构。 + +版本口径分为三类: + +1. 源码版本:Git 提交或发布分支对应的版本; +2. 发布版本:可下载的便携 ZIP 版本; +3. 更新清单版本:远端 manifest 中声明的 SemVer 版本。 + +只有通过本地测试、打包测试和对应模块验收的版本才能标记为 stable。未完成 DxDesigner 7.9.5 实机验收的版本必须保持“实机验收待完成”声明。 + +## 3. 总体架构 + +```text +DxDesigner 7.9.5 + -> 私有启动配置与 MenuAdd.vbs + -> 一叶知秋_重构版菜单 + -> 当前自动位号桥接 / 旧功能兼容适配器 + -> EFM/VBS 或 Python 模块 + -> 结果、日志、备份与回滚 +``` + +### 3.1 兼容层 + +旧 EFM/VBS 资产放在发布目录的独立 legacy 区域。兼容层负责: + +- 从工具自身目录解析资源,不使用 `D:\NET_CHECK`; +- 为旧脚本提供受控的资源路径和必要环境映射; +- 将旧菜单动作注册到同一个产品菜单下; +- 记录模块名称、版本、调用方式和失败原因; +- 不让旧模块直接修改当前自动位号模块的运行目录或历史记录。 + +EFM 兼容接入只证明“旧功能能够被调用”,不等同于现代化重构完成。每个模块都必须在目标 DxDesigner 7.9.5 上用副本工程验收。 + +### 3.2 现代化模块 + +需要安全写回的器件属性模块优先复用当前桥接协议:VBS 负责 DxDesigner 对象访问,Python 负责预览、规则、校验和结果生成。模块逐步获得以下能力: + +- 快照和对象身份确认; +- 变更预览; +- 冲突和格式校验; +- 变更前备份; +- 写回后验证; +- 失败回滚和历史记录。 + +网络、BOM 和 PCB 功能不假设与 RefDes 的对象模型完全相同,必须分别定义适配器和验收项。 + +## 4. 功能迁移顺序 + +迁移顺序按复用程度、风险和用户价值确定: + +1. BOM 导出:先保留原始 EFM 逻辑,解决路径和输出位置; +2. Value / Value1 / Part Number:复用器件遍历和写回框架,逐步加入预览与回滚; +3. PartName / PartLabel:先做兼容调用,再确认属性字段和显示状态的 7.9.5 行为; +4. 网络跨页互动、网络列表和网络检查:单独验证网络枚举、跨页导航和只读检查; +5. PCB 装配位号移动:独立于 DxDesigner 菜单和桥接,按 Expedition PCB 环境单独打包和验收。 + +每个模块都经历以下状态:`兼容接入`、`重构中`、`已验证`。模块未达到 `已验证` 前,不在稳定版说明中声称完整支持。 + +## 5. 菜单与配置 + +菜单顶层使用“一叶知秋_重构版”产品名,当前自动位号作为已验证入口。旧模块使用独立子菜单或清晰的模块分组,避免旧脚本和新脚本同名冲突。 + +启动配置继续使用当前的私有启动目录和备份策略。迁移模块不得要求用户手工设置全局 `SKY_MT`;如旧 EFM 仍需要该语义,兼容层在动作调用时提供等价的临时资源根,不写入持久化系统环境变量。 + +## 6. 在线更新协议 + +### 6.1 远端 manifest + +更新地址由设置提供,默认支持 HTTPS;后续也可适配用户提供的企业存储地址或只读共享路径。manifest 至少包含: + +```json +{ + "product": "yiyezhqiu-refactored", + "version": "1.1.0", + "channel": "stable", + "min_supported_version": "1.0.0", + "package_url": null, + "sha256": null, + "release_notes": "", + "published_at": "2026-09-11" +} +``` + +客户端必须校验产品标识、版本格式、最低支持版本、下载地址协议、文件摘要和发布时间字段。版本比较使用 SemVer,不按文件名或修改时间判断新旧。 + +### 6.2 安全策略 + +SHA-256 是最低完整性校验。生产更新优先增加签名字段和内置公钥,使用签名校验防止“下载包和摘要同时被替换”。签名校验失败时禁止安装,不提供绕过按钮。 + +不保存账号密码、访问令牌或私有存储凭据。需要认证的存储由系统凭据或用户当前网络会话负责。 + +### 6.3 更新流程 + +默认行为是“自动检查、人工安装”: + +1. 启动时或用户手动触发检查 manifest; +2. 无网络、无新版本或检查失败时不影响当前工具使用; +3. 发现新版本后显示版本号、发布时间、更新说明和校验状态; +4. 用户第一次确认下载与安装; +5. 下载到 `%LOCALAPPDATA%\\DxProductivity\\updates\\` 临时目录; +6. 校验摘要和签名; +7. 用户第二次确认切换版本; +8. 启动独立更新器,备份当前版本并执行原子切换; +9. 新版本启动成功后保留可恢复的旧版本; +10. 新版本启动失败、文件不完整或切换异常时恢复旧版本并记录原因。 + +主程序运行期间不覆盖自身 EXE。便携包优先采用旁路新目录切换,兼容只读目录、共享盘和中文路径。 + +### 6.4 设置项 + +设置中提供: + +- 更新源地址; +- 自动检查开关; +- 更新通道; +- 检查更新按钮; +- 当前版本和上次检查结果; +- 更新日志入口; +- 下载、校验、安装和回滚状态。 + +默认不自动安装。更新地址改变后必须重新检查 manifest,不能沿用旧下载结果。 + +## 7. 审批与发布门禁 + +迁移采用多级审批: + +1. 本设计文档审批:确认范围、顺序和更新策略; +2. 实施计划审批:确认具体文件和测试任务; +3. 模块审批:每个旧功能兼容接入后单独验收; +4. 重构审批:兼容模块改为现代桥接前确认行为保持一致; +5. 发布审批:确认版本声明、变更说明、校验文件和回滚包; +6. 在线更新审批:先用本地模拟源,再用真实存储地址做联网验收。 + +任何模块失败只阻断该模块的 stable 标记,不阻断已验证模块继续使用。 + +## 8. 错误处理与回滚 + +错误分为四类: + +- 配置错误:更新地址或模块资源不存在; +- 兼容错误:DxDesigner API、EFM 表单或脚本宿主不支持; +- 数据错误:输入冲突、快照过期、校验失败; +- 更新错误:下载、摘要、签名、切换或启动失败。 + +所有错误必须给出模块名、阶段、可操作建议和诊断日志位置。旧模块不得在资源或执行失败时静默修改工程。更新失败只恢复版本目录,不修改原理图工程。 + +## 9. 测试与验收 + +### 9.1 自动化测试 + +- 旧菜单路径重写和资源枚举; +- 每个兼容模块的动作注册和缺失资源错误; +- manifest 解析、SemVer 比较、协议限制和字段校验; +- SHA-256/签名校验失败; +- 下载中断、临时目录清理和重复安装; +- 旁路切换、启动失败回滚和旧版本保留; +- 中文路径、空格路径、共享盘和离线环境。 + +### 9.2 DxDesigner 7.9.5 实机验收 + +使用副本工程逐模块确认:菜单加载、动作调用、组件/网络枚举、结果写回、工程保存、错误提示和重复启动行为。任何只读模拟测试不能替代实机结论。 + +### 9.3 发布验收 + +发布包必须包含版本声明、更新 manifest 示例、SHA-256 文件、回滚说明和模块支持矩阵。发布前验证 ZIP 解压后的便携启动、更新器独立启动和旧版本恢复。 + +## 10. 交付顺序 + +第一阶段:冻结“一叶知秋_重构版”产品命名和模块支持矩阵,完成旧资产清点。 + +第二阶段:接入兼容菜单和第一个旧模块,验证相对路径、日志和失败隔离。 + +第三阶段:依次迁移器件属性、网络和 BOM 模块,每个模块单独验收。 + +第四阶段:实现更新 manifest、检查 UI、下载校验、旁路切换和回滚。 + +第五阶段:使用用户提供的真实存储地址做在线更新验收,并发布 stable 版本。 diff --git a/docs/testing/dxdesigner-795-live.md b/docs/testing/dxdesigner-795-live.md new file mode 100644 index 0000000..ead8b12 --- /dev/null +++ b/docs/testing/dxdesigner-795-live.md @@ -0,0 +1,97 @@ +# DxDesigner 7.9.5 现场验收记录 + +> 发布状态:离线构建已验证;真实 DxDesigner 7.9.5 验收待完成。所有关键项目通过前,不得把模拟测试结果表述为实机兼容结论。 + +## 1. 测试信息 + +| 字段 | 记录 | +|---|---| +| Windows 版本 / Build | | +| DxDesigner / Expedition Enterprise 完整版本与 Build | | +| 工具 ZIP SHA-256 | | +| 解压根目录 | | +| `script_path_source` | | +| 解析到的脚本完整路径 | | +| 菜单回调路径 | | +| `yield_method` | | +| `compatibility.json` 路径 | | +| 测试工程 / 副本说明 | | +| 测试器 | | +| 日期 | | + +## 2. 发布包与启动脚本 + +- [ ] ZIP 在离线 Win11 x64 目标机完整解压,无需安装 Python、联网、管理员权限或环境变量。 +- [ ] 解压路径包含中文和空格时,`DxDesignerTools.exe` 可启动。 +- [ ] 仅通过 `Settings -> Run at Startup -> Scripts` 导入根目录 `MenuAdd.vbs`。 +- [ ] 首次重启后只出现一个“Dx 效率工具”菜单。 +- [ ] 连续重启两次后仍只有一个同名菜单,没有重复按钮。 +- [ ] 菜单包含“自动位号”“兼容性检测”“使用说明”,三个动作均能打开对应功能。 +- [ ] 移动完整工具目录后,旧路径失效提示明确;删除旧项并重新导入后恢复正常。 + +## 3. 兼容性检测 + +- [ ] 检测过程只读,工程文件时间戳、位号和选择状态未发生非预期变化。 +- [ ] `portable_root_valid=true`,并记录实际命中的 `script_path_source`。 +- [ ] 能枚举当前选择、当前页和全设计器件。 +- [ ] 能读取 RefDes、页号、层级路径和坐标。 +- [ ] 能识别普通器件、多单元器件和锁定器件的所需字段。 +- [ ] `yield_method` 非空,工具界面打开期间 DxDesigner 仍可处理消息。 +- [ ] `retained_reference=true`,等待期间保留的器件对象仍可读写。 +- [ ] `compatibility.json` 为有效 UTF-8 JSON,包含完整 Build、路径来源和检测结果。 + +## 4. 自动位号预览 + +- [ ] “选中器件”范围只包含当前选中的逻辑器件。 +- [ ] “当前页”范围只包含活动页器件。 +- [ ] “全设计”范围包含所有页和层级中的器件。 +- [ ] “仅补空缺”保留正式位号,只处理空白或 `R?`、`C?` 等占位值。 +- [ ] “全部重编”在副本工程产生完整、确定的目标计划。 +- [ ] 连续编号按前缀独立计数,并跳过范围外已占用编号。 +- [ ] 按页编号正确使用页号、每页跨度和页内起始值。 +- [ ] 从上到下、从左到右排序符合坐标预期。 +- [ ] 从上到下、从右到左排序符合坐标预期。 +- [ ] 从左到右、从上到下排序符合坐标预期。 +- [ ] 从右到左、从上到下排序符合坐标预期。 +- [ ] 同行容差变化只影响预览顺序,不直接修改设计。 +- [ ] 多单元器件共用一个逻辑位号,身份歧义或单元值不一致时阻断。 +- [ ] 重复正式位号、目标占用、缺少前缀和锁定对象均产生明确阻断。 +- [ ] 双击预览行能在 DxDesigner 中选择并缩放对应器件,且不触发写回。 + +## 5. 应用、验证与回滚 + +- [ ] 关闭工具或取消应用时不生成写回结果,设计保持不变。 +- [ ] 应用前在 `%LOCALAPPDATA%\DxProductivity\backups` 创建新备份。 +- [ ] 正常应用按计划写回所有器件,并逐步回读确认。 +- [ ] 应用后重新枚举全设计,最终位号正确且正式位号大小写不敏感地唯一。 +- [ ] 应用状态为 `applied`,变更数、备份路径和 run ID 正确。 +- [ ] 打开预览后人工改变一个目标器件,应用因陈旧状态在首个写入前被拒绝。 +- [ ] 注入中途赋值失败后,所有已触碰器件恢复原值并验证,状态为 `rolled-back`。 +- [ ] 注入回滚赋值失败后,状态为 `rollback-failed`,报告剩余差异、失败序号和备份路径。 +- [ ] 编号交换或循环使用临时位号完成,最终无临时位号残留。 + +## 6. 操作历史与恢复 + +- [ ] “操作历史”显示时间、结果、变更数、设计 ID 和备份路径。 +- [ ] “恢复上次位号”先备份当前状态,再发布恢复事务。 +- [ ] 恢复前显示变更数与备份时间,取消确认时设计不变。 +- [ ] 正常恢复写回历史原值并完成全设计重复验证。 +- [ ] 当前值与历史预期不一致时,恢复因陈旧状态被拒绝。 +- [ ] 恢复目标与范围外正式位号冲突时阻断。 +- [ ] 恢复中注入失败时执行并验证回滚。 + +## 7. 结果与签字 + +| 结论 | 记录 | +|---|---| +| 关键项目是否全部通过 | | +| 未通过项目编号 | | +| 相关 run ID / 日志 / 截图路径 | | +| 允许使用的工程范围 | | +| 验收人 | | +| 复核人 | | +| 日期 | | + +### 未通过项说明 + +记录实际 API 属性、错误号/描述、使用的工程夹具、复现步骤、预期结果和实际结果。不得只写“失败”或用模拟测试替代现场证据。 diff --git a/docs/testing/native-acceptance.md b/docs/testing/native-acceptance.md new file mode 100644 index 0000000..22ea6ab --- /dev/null +++ b/docs/testing/native-acceptance.md @@ -0,0 +1,44 @@ +# 一叶知秋 重构版 原生功能实机验收 + +本清单用于在真实 DxDesigner 7.9.5 / Expedition PCB 环境中验收原生迁移后的功能。各功能的计算逻辑已由自动化测试覆盖;本清单关注 COM 宿主行为(属性写回、读回验证、定位、Excel 输出)与端到端体验。没有真实宿主运行记录时,不得写成“已验证”。 + +## 通用前置条件 + +- 使用便携包根目录的 `MenuAdd.vbs`,通过 DxDesigner 7.9.5 的启动脚本设置导入;Expedition 侧导入 `expedition\ExpeditionBridge.vbs`。 +- 准备可恢复的样例工程,先复制工程目录和原理图文件。 +- 运行“兼容性检测”,保存诊断输出和宿主版本信息。 + +## 自动位号 + +- [ ] 菜单启动,快照导出成功(含属性与网络字段)。 +- [ ] 编号预览、应用、历史记录、恢复(含多单元器件)全链路。 +- [ ] 应用失败(人为制造状态漂移)自动回滚,界面显示拒绝/回滚状态。 +- [ ] 二次应用:不重启宿主的情况下修改规则后再次应用成功(多次消费)。 + +## 属性批改 / 属性显示 + +- [ ] 选中器件 → 填写新值 → 应用 → 读回验证成功。 +- [ ] 缺失属性与锁定器件显示“已跳过”,原理图其余部分不变。 +- [ ] 可见性隐藏/显示双向切换,恢复功能正确还原。 + +## 设计检查 + +- [ ] 孤立网络/网络列表结果与手工核对一致;双击定位跳转到正确页并高亮。 +- [ ] Value/Value1 遗漏查找命中空值器件;“属性缺失也算遗漏”开关生效。 + +## BOM 导出 + +- [ ] 分组合并、NC 过滤、MARK/TEST_POINT/MOUNTHOL 行剔除与旧版一致。 +- [ ] 创维料号校验标色(橙色)与旧版一致;位号重复标红。 +- [ ] Excel 打开模板输出,用户另存路径生效;未安装 Excel 时给出明确错误。 + +## Expedition PCB 装配位号整理 + +- [ ] 菜单出现在 Document Menu Bar,许可流程正常。 +- [ ] 顶层/底层、0/90/180/270/斜向器件的位号旋转、字高与归心符合旧版行为。 +- [ ] 非位号丝印文字被删除;整个操作可在 Expedition 中一次撤销。 + +## 结论规则 + +- 所有记录完成且可重复后,才可将单个模块标记为“已验证”。 +- 失败或行为不一致的模块在 `apply-status.json` / `install.log` / 诊断输出中记录原因。 diff --git a/docs/testing/yiyezhqiu-update-acceptance.md b/docs/testing/yiyezhqiu-update-acceptance.md new file mode 100644 index 0000000..8e065b4 --- /dev/null +++ b/docs/testing/yiyezhqiu-update-acceptance.md @@ -0,0 +1,21 @@ +# 一叶知秋 重构版在线更新验收 + +在线更新默认自动检查、人工安装。检查不会修改原理图,也不会在主程序仍运行时覆盖 EXE;安装前先下载、校验、备份,再退出主程序完成旁路切换。 + +## 本地 file 方案 + +1. 在可写临时目录准备旧版便携目录和新版 ZIP。 +2. 生成 `update-manifest.template.json`,填写新版 `version`、`package_url` 和 ZIP 的 SHA-256。 +3. 在设置页选择 `file://` manifest,频道选择“开发版”,点击“检查更新”。 +4. 第一次确认下载和校验,第二次确认退出并安装。 +5. 检查 `version.json`、`backups` 和 `install.log`;故意让 smoke probe 返回非零,确认旧目录恢复。 + +## stable 频道 + +stable manifest 必须提供 Ed25519 签名和固定公钥。摘要或签名失败时安装按钮必须保持禁用,不能通过 UI 绕过。真实 HTTPS 或只读共享地址接入前,不保存账号、密码或访问令牌。 + +## 离线与失败 + +- 网络不可用、JSON 损坏或渠道不匹配时显示检查失败/不兼容,当前版本继续可用。 +- ZIP 缺失、摘要不一致、签名无效或包含路径穿越时不进入安装事务。 +- 安装后的 smoke probe 非零时恢复旧目录;更新失败不改变 DxDesigner 工程。 diff --git a/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.2.docx b/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.2.docx new file mode 100644 index 0000000..c4f4e4f Binary files /dev/null and b/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.2.docx differ diff --git a/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx b/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx new file mode 100644 index 0000000..e22f4aa Binary files /dev/null and b/docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx differ diff --git a/docs/user/一叶知秋_重构版_更新说明.md b/docs/user/一叶知秋_重构版_更新说明.md new file mode 100644 index 0000000..0cbf111 --- /dev/null +++ b/docs/user/一叶知秋_重构版_更新说明.md @@ -0,0 +1,17 @@ +# 一叶知秋_重构版 更新说明 + +## 本版变更(原生迁移版) + +- 原“一叶知秋”七大功能全部**原生迁移**进新工具,不再桥接旧 EFM/VBS:Value/Value1/Part Number 批量修改、PartName/PartLabel 批量隐藏(新增“显示”方向)、孤立网络/网络列表/跨页互动、Value/Value1 遗漏查找、BOM 导出(含创维料号校验)与 Expedition PCB 装配位号整理。 +- 全部功能共用统一事务通道:预检(摘要与状态一致性校验)→ 逐项写回并读回验证 → 失败自动回滚 → 全设计终检。 +- 桥接协议升级到 v2:快照包含属性全集、可见性、网络分布与真实锁定状态;调度表按“操作类型 + 属性名”泛化,同一事务核心承载所有功能。 +- 宿主侧信箱支持多次应用、真实休眠(不再空转占用 CPU)、心跳检测与旧运行目录自动清理;界面增加“刷新设计快照”的真实重新导出。 +- 更新通道安全强化:stable 频道强制 Ed25519 签名验证(公钥内置于程序),下载地址仅允许 https 与 file 协议,阻止跨协议重定向;更新器加单实例互斥并等待主程序退出后再切换版本。 + +## 设置页 + +设置页支持配置 manifest 地址、stable/development 频道和每日自动检查。自动检查只读取版本信息并显示版本说明;安装始终需要两次人工确认。当前包根目录包含 `version.json` 和 `update-manifest.template.json`。将 ZIP 和 manifest 放在 HTTPS 或只读共享地址后,把 manifest 地址填入设置即可;stable 发布必须带 SHA-256 和 Ed25519 签名(签名工具见 `packaging/sign_manifest.py`),开发阶段可以使用 `file://` 地址验证流程。更新器会下载到用户目录的更新缓存,校验通过后复制当前目录备份,再旁路切换版本;启动探针失败会自动回滚到旧版本。 + +## 实机验收 + +DxDesigner 7.9.5 与 Expedition PCB 的宿主行为(COM 属性写回、网络定位、Excel 输出)仍需按 `docs/testing/native-acceptance.md` 在真实环境验收;逻辑正确性已由自动化测试覆盖。 diff --git a/docs/user/一叶知秋_重构版_模块支持矩阵.md b/docs/user/一叶知秋_重构版_模块支持矩阵.md new file mode 100644 index 0000000..1066d0f --- /dev/null +++ b/docs/user/一叶知秋_重构版_模块支持矩阵.md @@ -0,0 +1,26 @@ +# 一叶知秋 重构版 模块支持矩阵 + +当前版本已将原始“一叶知秋”的全部功能**原生迁移**到新工具:业务逻辑(编号、调度、校验、BOM 组表、料号校验、几何规则)全部在 Python 领域层实现并有单元测试覆盖;DxDesigner / Expedition 宿主只承担设计读写与 Excel 输出。旧的 EFM 表单与桥接式旧脚本已不再随包发布。 + +| 分组 | 模块 | 宿主 | 实现方式 | 实机验收 | +| --- | --- | --- | --- | --- | +| 自动位号 | 位号重编 / 恢复 | DxDesigner 7.9.5 | 原生(重构核心) | 待完成 | +| 属性批改 | Value / Value1 / Part Number 批量修改 | DxDesigner 7.9.5 | 原生迁移(旧 PART_Value_CHA / Value1_CHA / PartNumber_CHA) | 待完成 | +| 属性显示 | PartName / PartLabel 批量隐藏与显示 | DxDesigner 7.9.5 | 原生迁移(旧 PartName_Hide / PartLabel_Hide,并新增“显示”方向) | 待完成 | +| 设计检查 | 孤立网络 / 全部网络列表 / 跨页互动 | DxDesigner 7.9.5 | 原生迁移(旧 NET-solitary / NET-List / NET-interactive,经快照网络导出) | 待完成 | +| 设计检查 | Value / Value1 遗漏查找 | DxDesigner 7.9.5 | 原生迁移(旧 Value_Check_Miss / Value1_Check_Miss;“属性缺失也算遗漏”为可选项) | 待完成 | +| BOM 工具 | BOM 导出(分组合并、NC 过滤、料号校验) | DxDesigner 7.9.5 | 原生迁移(旧 Bom.efm;PVCheck 规则逐分支移植并有表驱动测试) | 待完成 | +| BOM 工具 | PCB 装配位号整理 | Expedition PCB | 原生迁移(旧 MoveAssemblyRef.vbs;几何规则在 Python,宿主只执行移动/删除) | 待完成 | + +## 行为约定 + +- 属性批改与显示按 DxDesigner 中的**选中器件**生效;缺失属性的器件会显示为“已跳过”(旧版为静默跳过),锁定器件一律跳过。 +- 网络检查为只读功能;双击结果行通过宿主定位到对应页并高亮网络。 +- BOM 导出沿用“模板 + Excel 输出”的旧版体验,保存路径由用户选择,不再依赖任何固定安装路径。 +- 所有改图操作走统一事务(preflight → apply → verify → rollback):失败自动回滚并在 `apply-status.json` 记录原因;历史与恢复记录保存在 `%LOCALAPPDATA%\DxProductivity`。 + +## 未迁移项(有意排除) + +- 旧“位号批量命名”(PART_Ref_CHA.efm):已被重构版的自动位号工具完全取代。 +- `BOM_Syn-to_SCH.efm` 属性比对原型:开发中间产物,未形成闭环功能,废弃。 +- 旧 EFM/VBS 资产保留在仓库 `integration/dxdesigner795/legacy/yiyezhqiu/` 下仅作行为参考,不再随包发布。 diff --git a/integration/dxdesigner795/BridgeCommon.vbs b/integration/dxdesigner795/BridgeCommon.vbs new file mode 100644 index 0000000..c91383a --- /dev/null +++ b/integration/dxdesigner795/BridgeCommon.vbs @@ -0,0 +1,228 @@ +' Shared DxDesigner 7.9.5 bridge helpers. Keep this file ASCII-only. + +Function DxToolsQuote(value) + Dim text + Dim expression + text = CStr(value) + ' Double any trailing backslashes so they cannot escape the closing quote. + Set expression = CreateObject("VBScript.RegExp") + expression.Pattern = "\\+$" + expression.Global = False + text = expression.Replace(text, "$&$&") + DxToolsQuote = Chr(34) & Replace(text, Chr(34), _ + Chr(92) & Chr(34)) & Chr(34) +End Function + +Function DxToolsJson(value) + Dim text + text = CStr(value) + text = Replace(text, Chr(92), Chr(92) & Chr(92)) + text = Replace(text, Chr(34), Chr(92) & Chr(34)) + text = Replace(text, vbCr, Chr(92) & "r") + text = Replace(text, vbLf, Chr(92) & "n") + text = Replace(text, vbTab, Chr(92) & "t") + DxToolsJson = text +End Function + +Function DxToolsReadUtf8(path) + Dim stream + Set stream = CreateObject("ADODB.Stream") + stream.Type = 2 + stream.Charset = "utf-8" + stream.Open + stream.LoadFromFile CStr(path) + DxToolsReadUtf8 = stream.ReadText + stream.Close +End Function + +Sub DxToolsWriteUtf8Atomic(path, text) + Dim stream + Dim temporaryPath + Dim shell + Dim commandLine + Dim exitCode + + temporaryPath = CStr(path) & ".tmp" + Set stream = CreateObject("ADODB.Stream") + stream.Type = 2 + stream.Charset = "utf-8" + stream.Open + stream.WriteText CStr(text) + stream.SaveToFile temporaryPath, 2 + stream.Close + + Set shell = CreateObject("WScript.Shell") + commandLine = DxToolsQuote(shell.ExpandEnvironmentStrings("%ComSpec%")) & _ + " /d /s /c " & Chr(34) & "move /y " & _ + DxToolsQuote(temporaryPath) & " " & DxToolsQuote(path) & _ + " >nul" & Chr(34) + exitCode = shell.Run(commandLine, 0, True) + If exitCode <> 0 Then + Err.Raise vbObjectError + 795, "DxToolsWriteUtf8Atomic", _ + "Cannot replace bridge file: " & CStr(path) + End If +End Sub + +Function DxToolsParseScheduleRow(line, ByRef sequence, ByRef op, _ + ByRef bridgeId, ByRef propertyName, ByRef expectedValue, _ + ByRef newValue, ByRef finalValue) + Dim fields + Dim field + + DxToolsParseScheduleRow = False + fields = Split(CStr(line), vbTab) + If UBound(fields) <> 6 Then Exit Function + If Not IsNumeric(fields(0)) Then Exit Function + If CLng(fields(0)) < 1 Then Exit Function + If Len(fields(2)) = 0 Then Exit Function + For Each field In fields + If InStr(field, vbCr) > 0 Or InStr(field, vbLf) > 0 Then Exit Function + Next + + sequence = CLng(fields(0)) + op = CStr(fields(1)) + bridgeId = CStr(fields(2)) + propertyName = CStr(fields(3)) + expectedValue = CStr(fields(4)) + newValue = CStr(fields(5)) + finalValue = CStr(fields(6)) + DxToolsParseScheduleRow = True +End Function + +Function DxToolsSha256File(path) + Dim shell + Dim fso + Dim certutilPath + Dim outputPath + Dim commandLine + Dim exitCode + Dim output + Dim expression + Dim matches + + Set shell = CreateObject("WScript.Shell") + Set fso = CreateObject("Scripting.FileSystemObject") + certutilPath = shell.ExpandEnvironmentStrings( _ + "%SystemRoot%\System32\certutil.exe") + outputPath = CStr(path) & ".sha256.txt" + commandLine = DxToolsQuote(certutilPath) & " -hashfile " & _ + DxToolsQuote(path) & " SHA256 > " & DxToolsQuote(outputPath) + exitCode = shell.Run(DxToolsQuote( _ + shell.ExpandEnvironmentStrings("%ComSpec%")) & _ + " /d /s /c " & Chr(34) & commandLine & Chr(34), 0, True) + If exitCode <> 0 Then + Err.Raise vbObjectError + 796, "DxToolsSha256File", _ + "Cannot calculate result digest" + End If + + output = fso.OpenTextFile(outputPath, 1, False, 0).ReadAll + fso.DeleteFile outputPath, True + Set expression = CreateObject("VBScript.RegExp") + expression.Pattern = "[0-9A-Fa-f]{64}" + expression.Global = False + Set matches = expression.Execute(output) + If matches.Count <> 1 Then + Err.Raise vbObjectError + 797, "DxToolsSha256File", _ + "SHA-256 output is invalid" + End If + DxToolsSha256File = LCase(matches.Item(0).Value) +End Function + +Function DxToolsJsonString(jsonText, key, ByRef value) + Dim marker + Dim markerAt + Dim colonAt + Dim quoteAt + Dim index + Dim character + Dim escaped + + DxToolsJsonString = False + marker = Chr(34) & CStr(key) & Chr(34) + markerAt = InStr(1, CStr(jsonText), marker, vbBinaryCompare) + If markerAt = 0 Then Exit Function + colonAt = InStr(markerAt + Len(marker), CStr(jsonText), ":") + If colonAt = 0 Then Exit Function + quoteAt = InStr(colonAt + 1, CStr(jsonText), Chr(34)) + If quoteAt = 0 Then Exit Function + + escaped = False + value = "" + For index = quoteAt + 1 To Len(CStr(jsonText)) + character = Mid(CStr(jsonText), index, 1) + If escaped Then + Select Case character + Case Chr(34), Chr(92), "/" + value = value & character + Case "r" + value = value & vbCr + Case "n" + value = value & vbLf + Case "t" + value = value & vbTab + Case Else + Exit Function + End Select + escaped = False + ElseIf character = Chr(92) Then + escaped = True + ElseIf character = Chr(34) Then + DxToolsJsonString = True + Exit Function + Else + value = value & character + End If + Next +End Function + +Sub DxBridgeEnsureFolder(path) + Dim fso + Dim parent + Set fso = CreateObject("Scripting.FileSystemObject") + If fso.FolderExists(CStr(path)) Then Exit Sub + parent = fso.GetParentFolderName(CStr(path)) + If parent <> "" And Not fso.FolderExists(parent) Then + Call DxBridgeEnsureFolder(parent) + End If + On Error Resume Next + fso.CreateFolder CStr(path) + If Err.Number <> 0 And Err.Number <> 58 Then + On Error GoTo 0 + Err.Raise vbObjectError + 798, "DxBridgeEnsureFolder", _ + "Cannot create folder: " & CStr(path) + End If + Err.Clear + On Error GoTo 0 +End Sub + +Function DxBridgeNormalizeVisible(value) + Dim text + If IsEmpty(value) Or IsNull(value) Then + DxBridgeNormalizeVisible = "0" + Exit Function + End If + If VarType(value) = vbBoolean Then + If CBool(value) Then + DxBridgeNormalizeVisible = "1" + Else + DxBridgeNormalizeVisible = "0" + End If + Exit Function + End If + text = LCase(Trim(CStr(value))) + If text = "0" Or text = "" Or text = "false" Then + DxBridgeNormalizeVisible = "0" + Else + DxBridgeNormalizeVisible = "1" + End If +End Function + +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 + Err.Clear + On Error GoTo 0 + Call DxBridgeYield() +End Sub diff --git a/integration/dxdesigner795/CompatibilityProbe.vbs b/integration/dxdesigner795/CompatibilityProbe.vbs new file mode 100644 index 0000000..d56b8d6 --- /dev/null +++ b/integration/dxdesigner795/CompatibilityProbe.vbs @@ -0,0 +1,295 @@ +' DxDesigner 7.9.5 read-only compatibility probe. Keep this file ASCII-only. + +Sub DxToolsRunCompatibilityProbe() + Call DxToolsProbeExecute("named") +End Sub + +Sub DxToolsProbeExecute(routeName) + Dim payload + Dim outputPath + Dim shell + Dim process + Dim commandLine + Dim yieldMethod + Dim retainedComponent + Dim retainedOk + Dim executablePath + + payload = DxToolsProbeCapabilities(retainedComponent) + outputPath = CreateObject("WScript.Shell").ExpandEnvironmentStrings( _ + "%LOCALAPPDATA%\DxProductivity\compatibility.json") + + Set shell = CreateObject("WScript.Shell") + executablePath = DxToolsHome & "\DxDesignerTools.exe" + commandLine = DxToolsProbeQuote(executablePath) & " probe" & _ + " --output " & DxToolsProbeQuote(outputPath) & _ + " --route " & routeName & _ + " --payload-json " & DxToolsProbeQuote(payload) & _ + " --hold-seconds 1.5" + + On Error Resume Next + Set process = shell.Exec(commandLine) + If Err.Number <> 0 Then + Dim launchError + launchError = Err.Description + Err.Clear + On Error GoTo 0 + MsgBox DxToolsProbePythonError() & vbCrLf & launchError, vbExclamation + Exit Sub + End If + On Error GoTo 0 + + yieldMethod = DxToolsProbePumpWhileRunning(process) + retainedOk = DxToolsProbeRetainedReferenceReadable(retainedComponent) + payload = DxToolsProbeAppendResult(payload, yieldMethod, retainedOk) + + commandLine = DxToolsProbeQuote(executablePath) & " probe" & _ + " --output " & DxToolsProbeQuote(outputPath) & _ + " --route " & routeName & _ + " --payload-json " & DxToolsProbeQuote(payload) + Set process = shell.Exec(commandLine) + Call DxToolsProbeWait(process, yieldMethod) + + If process.ExitCode = 0 Then + MsgBox DxToolsProbeCompleteMessage() & vbCrLf & outputPath, vbInformation + Else + MsgBox DxToolsProbePythonError(), vbExclamation + End If +End Sub + +Function DxToolsProbeCapabilities(ByRef retainedComponent) + Dim selectedOk + Dim selectedCount + Dim fullOk + Dim fullCount + Dim refdesOk + Dim uidOk + Dim attributesOk + Dim sheetOk + Dim pathMethod + Dim positionMethod + Dim sample + + selectedOk = DxToolsProbeSelected(sample, selectedCount) + fullOk = DxToolsProbeFullDesign(retainedComponent, fullCount) + If sample Is Nothing Then Set sample = retainedComponent + + refdesOk = DxToolsProbeProperty(sample, "refdes") + uidOk = DxToolsProbeProperty(sample, "uid") + attributesOk = DxToolsProbeProperty(sample, "attributes") + sheetOk = DxToolsProbeSheetNumber() + pathMethod = DxToolsProbePathMethod(sample) + positionMethod = DxToolsProbePositionMethod(sample) + + DxToolsProbeCapabilities = "{" & _ + """script_path_source"":""" & _ + DxToolsProbeJson(DxToolsScriptPathSource) & """," & _ + """script_path"":""" & DxToolsProbeJson(DxToolsScriptFullName) & _ + """," & _ + """portable_root_valid"":" & _ + DxToolsProbeBoolean(DxToolsHome <> "") & "," & _ + """selected_query"":" & DxToolsProbeBoolean(selectedOk) & "," & _ + """selected_count"":" & CStr(selectedCount) & "," & _ + """full_design_enumeration"":" & DxToolsProbeBoolean(fullOk) & "," & _ + """full_design_count"":" & CStr(fullCount) & "," & _ + """refdes_readable"":" & DxToolsProbeBoolean(refdesOk) & "," & _ + """uid_readable"":" & DxToolsProbeBoolean(uidOk) & "," & _ + """attributes_readable"":" & DxToolsProbeBoolean(attributesOk) & "," & _ + """sheet_number_readable"":" & DxToolsProbeBoolean(sheetOk) & "," & _ + """path_method"":""" & DxToolsProbeJson(pathMethod) & """," & _ + """position_method"":""" & DxToolsProbeJson(positionMethod) & """}" +End Function + +Function DxToolsProbeSelected(ByRef sample, ByRef count) + Dim comp + count = 0 + Set sample = Nothing + On Error Resume Next + For Each comp In ActiveView.Query(VDM_COMP, VD_SELECTED) + count = count + 1 + If sample Is Nothing Then Set sample = comp + Next + DxToolsProbeSelected = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbeFullDesign(ByRef sample, ByRef count) + Dim projectData + Dim designs + Dim designName + Dim topBlock + Dim comp + count = 0 + Set sample = Nothing + On Error Resume Next + Set projectData = Application.GetProjectData() + Set designs = projectData.GetiCDBDesigns() + designName = designs.GetItem(1) + topBlock = projectData.GetiCDBDesignRootBlock(designName) + For Each comp In Application.DesignComponents("", topBlock, "-1", "STD", True) + count = count + 1 + If sample Is Nothing Then Set sample = comp + Next + DxToolsProbeFullDesign = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbeProperty(comp, propertyName) + Dim ignored + DxToolsProbeProperty = False + If comp Is Nothing Then Exit Function + On Error Resume Next + Select Case propertyName + Case "refdes" + ignored = CStr(comp.Refdes) + Case "uid" + ignored = CStr(comp.UID) + Case "attributes" + ignored = comp.Attributes.Count + End Select + DxToolsProbeProperty = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbeSheetNumber() + Dim ignored + On Error Resume Next + ignored = CStr(ActiveView.Block.SheetNum) + DxToolsProbeSheetNumber = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbePathMethod(comp) + Dim ignored + DxToolsProbePathMethod = "" + If comp Is Nothing Then Exit Function + + On Error Resume Next + ignored = CStr(comp.Parent) & "\" & CStr(comp.GetName(SHORT_NAME)) + If Err.Number = 0 Then DxToolsProbePathMethod = "Parent+GetName(SHORT_NAME)" + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbePositionMethod(comp) + Dim x + Dim y + DxToolsProbePositionMethod = "" + If comp Is Nothing Then Exit Function + + On Error Resume Next + x = comp.X + y = comp.Y + If Err.Number = 0 Then DxToolsProbePositionMethod = "X/Y" + Err.Clear + On Error GoTo 0 + If DxToolsProbePositionMethod <> "" Then Exit Function + + On Error Resume Next + x = comp.PositionX + y = comp.PositionY + If Err.Number = 0 Then DxToolsProbePositionMethod = "PositionX/PositionY" + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbePumpWhileRunning(process) + Dim methodName + methodName = DxToolsProbeFindYieldMethod() + Do While process.Status = 0 + Call DxToolsProbeYield(methodName) + Loop + DxToolsProbePumpWhileRunning = methodName +End Function + +Function DxToolsProbeFindYieldMethod() + If DxToolsProbeTryYield("Scripting.DoEvents") Then + DxToolsProbeFindYieldMethod = "Scripting.DoEvents" + ElseIf DxToolsProbeTryYield("Application.DoEvents") Then + DxToolsProbeFindYieldMethod = "Application.DoEvents" + ElseIf DxToolsProbeTryYield("ActiveView.Refresh") Then + DxToolsProbeFindYieldMethod = "ActiveView.Refresh" + Else + DxToolsProbeFindYieldMethod = "" + End If +End Function + +Function DxToolsProbeTryYield(methodName) + On Error Resume Next + Call DxToolsProbeYield(methodName) + DxToolsProbeTryYield = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Sub DxToolsProbeYield(methodName) + Select Case methodName + Case "Scripting.DoEvents" + Scripting.DoEvents + Case "Application.DoEvents" + Application.DoEvents + Case "ActiveView.Refresh" + ActiveView.Refresh + End Select +End Sub + +Sub DxToolsProbeWait(process, methodName) + Do While process.Status = 0 + Call DxToolsProbeYield(methodName) + Loop +End Sub + +Function DxToolsProbeRetainedReferenceReadable(comp) + Dim ignored + DxToolsProbeRetainedReferenceReadable = False + If comp Is Nothing Then Exit Function + On Error Resume Next + ignored = CStr(comp.Refdes) + DxToolsProbeRetainedReferenceReadable = (Err.Number = 0) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsProbeAppendResult(payload, yieldMethod, retainedOk) + DxToolsProbeAppendResult = Left(payload, Len(payload) - 1) & "," & _ + """yield_method"":""" & DxToolsProbeJson(yieldMethod) & """," & _ + """retained_reference"":" & DxToolsProbeBoolean(retainedOk) & "}" +End Function + +Function DxToolsProbeBoolean(value) + If CBool(value) Then + DxToolsProbeBoolean = "true" + Else + DxToolsProbeBoolean = "false" + End If +End Function + +Function DxToolsProbeJson(value) + Dim text + text = CStr(value) + text = Replace(text, Chr(92), Chr(92) & Chr(92)) + text = Replace(text, Chr(34), Chr(92) & Chr(34)) + text = Replace(text, vbCr, Chr(92) & "r") + text = Replace(text, vbLf, Chr(92) & "n") + DxToolsProbeJson = text +End Function + +Function DxToolsProbeQuote(value) + DxToolsProbeQuote = Chr(34) & Replace(CStr(value), Chr(34), _ + Chr(92) & Chr(34)) & Chr(34) +End Function + +Function DxToolsProbeCompleteMessage() + DxToolsProbeCompleteMessage = ChrW(&H517C) & ChrW(&H5BB9) & _ + ChrW(&H6027) & ChrW(&H68C0) & ChrW(&H6D4B) & ChrW(&H5B8C) & _ + ChrW(&H6210) +End Function + +Function DxToolsProbePythonError() + DxToolsProbePythonError = ChrW(&H5DE5) & ChrW(&H5177) & _ + ChrW(&H542F) & ChrW(&H52A8) & ChrW(&H5931) & ChrW(&H8D25) +End Function diff --git a/integration/dxdesigner795/DesignBridge.vbs b/integration/dxdesigner795/DesignBridge.vbs new file mode 100644 index 0000000..60a5f5e --- /dev/null +++ b/integration/dxdesigner795/DesignBridge.vbs @@ -0,0 +1,46 @@ +' Unified design-bridge entry for DxDesigner 7.9.5. Keep this file ASCII-only. +' Loaded by MenuAdd.vbs through ExecuteGlobal; relies on the DxToolsHome +' global that MenuAdd resolves before any menu action runs. + +Sub DxToolsDesignBridgeEnsureCore() + If Not IsEmpty(DxToolsDesignBridgeCoreLoaded) Then Exit Sub + If DxToolsHome = "" Then + MsgBox DxToolsPathErrorMessage(), vbExclamation + Err.Raise vbObjectError + 799, "DxToolsDesignBridgeEnsureCore", _ + "DxToolsHome is not resolved" + End If + Dim fso + Dim coreRoot + Set fso = CreateObject("Scripting.FileSystemObject") + coreRoot = fso.BuildPath(DxToolsHome, "_runtime\vbs") + If Not fso.FolderExists(coreRoot) Then + coreRoot = fso.BuildPath(DxToolsHome, "core") + End If + Call DxToolsLoadScript(fso.BuildPath(coreRoot, "Snapshot.vbs")) + Call DxToolsLoadScript(fso.BuildPath(coreRoot, "Transaction.vbs")) + Call DxToolsLoadScript(fso.BuildPath(coreRoot, "Mailbox.vbs")) + Call DxToolsLoadScript(fso.BuildPath(coreRoot, "BomExport.vbs")) + DxToolsDesignBridgeCoreLoaded = True +End Sub + +Sub DxToolsRunDesignBridge(featureKey) + If DxToolsHome = "" Then + MsgBox DxToolsPathErrorMessage(), vbExclamation + Exit Sub + End If + On Error Resume Next + Call DxToolsDesignBridgeEnsureCore() + If Err.Number <> 0 Then + Err.Clear + On Error GoTo 0 + Exit Sub + End If + On Error GoTo 0 + Call DxToolsDesignBridgeStart(CStr(featureKey)) +End Sub + +Function DxToolsPathErrorMessage() + DxToolsPathErrorMessage = ChrW(&H65E0) & ChrW(&H6CD5) & _ + ChrW(&H786E) & ChrW(&H5B9A) & ChrW(&H5DE5) & ChrW(&H5177) & _ + ChrW(&H76EE) & ChrW(&H5F55) +End Function diff --git a/integration/dxdesigner795/MenuAdd.vbs b/integration/dxdesigner795/MenuAdd.vbs new file mode 100644 index 0000000..c44977d --- /dev/null +++ b/integration/dxdesigner795/MenuAdd.vbs @@ -0,0 +1,279 @@ +' DxDesigner 7.9.5 portable startup menu. Keep this file ASCII-only. + +Dim DxToolsHome +Dim DxToolsScriptFullName +Dim DxToolsScriptPathSource +Dim DxToolsMenu +Dim DxToolsCommonLoaded +Dim DxToolsDesignBridgeLoaded +Dim DxToolsProbeLoaded + +DxToolsCommonLoaded = False +DxToolsDesignBridgeLoaded = False +DxToolsProbeLoaded = False + +DxToolsHome = DxToolsResolveRoot() +If DxToolsHome = "" Then + MsgBox DxToolsPathErrorMessage(), vbExclamation +Else + Call DxToolsInstallMenu() +End If + +Sub DxToolsInstallMenu() + Dim menuBar + Dim existing + Dim button + Dim i + Dim caption + + caption = DxToolsSuiteCaption() + Set menuBar = CommandBars("Sheet Menu Bar") + For i = menuBar.Controls.Count To 1 Step -1 + Set existing = menuBar.Controls.Item(i) + If existing.Caption = caption Then + On Error Resume Next + existing.Delete + Err.Clear + On Error GoTo 0 + End If + Next + + Set DxToolsMenu = menuBar.Controls.Add(cmdControlPopup) + DxToolsMenu.Caption = caption + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsRefDesCaption() + button.OnAction = "DxToolsOpenRefDes" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsPropertyChangeCaption() + button.OnAction = "DxToolsOpenPropertyChange" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsPropertyVisibilityCaption() + button.OnAction = "DxToolsOpenPropertyVisibility" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsInspectionCaption() + button.OnAction = "DxToolsOpenInspection" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsBomCaption() + button.OnAction = "DxToolsOpenBom" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsCompatibilityCaption() + button.OnAction = "DxToolsOpenCompatibility" + + Set button = DxToolsMenu.Controls.Add + button.Caption = DxToolsGuideCaption() + button.OnAction = "DxToolsOpenGuide" +End Sub + +Sub DxToolsOpenRefDes() + Call DxToolsStartFeature("refdes") +End Sub + +Sub DxToolsOpenPropertyChange() + Call DxToolsStartFeature("property-change") +End Sub + +Sub DxToolsOpenPropertyVisibility() + Call DxToolsStartFeature("property-visibility") +End Sub + +Sub DxToolsOpenInspection() + Call DxToolsStartFeature("inspection") +End Sub + +Sub DxToolsOpenBom() + Call DxToolsStartFeature("bom") +End Sub + +Sub DxToolsStartFeature(featureKey) + If Not DxToolsEnsureRoot() Then Exit Sub + Call DxToolsEnsureCommonLoaded() + If Not DxToolsDesignBridgeLoaded Then + Call DxToolsLoadScript(DxToolsHome & "\DesignBridge.vbs") + DxToolsDesignBridgeLoaded = True + End If + Call DxToolsRunDesignBridge(CStr(featureKey)) +End Sub + +Sub DxToolsOpenCompatibility() + If Not DxToolsEnsureRoot() Then Exit Sub + Call DxToolsEnsureCommonLoaded() + If Not DxToolsProbeLoaded Then + Call DxToolsLoadScript(DxToolsHome & "\CompatibilityProbe.vbs") + DxToolsProbeLoaded = True + End If + Call DxToolsRunCompatibilityProbe() +End Sub + +Sub DxToolsEnsureCommonLoaded() + If DxToolsCommonLoaded Then Exit Sub + Call DxToolsLoadScript(DxToolsHome & "\_runtime\vbs\BridgeCommon.vbs") + DxToolsCommonLoaded = True +End Sub + +Sub DxToolsOpenGuide() + Dim guidePath + Dim shell + If Not DxToolsEnsureRoot() Then Exit Sub + guidePath = DxToolsHome & "\docs\DxDesigner_7.9.5_" & _ + ChrW(&H81EA) & ChrW(&H52A8) & ChrW(&H4F4D) & ChrW(&H53F7) & _ + ChrW(&H5DE5) & ChrW(&H5177) & ChrW(&H4F7F) & ChrW(&H7528) & _ + ChrW(&H8BF4) & ChrW(&H660E) & ".docx" + If Not CreateObject("Scripting.FileSystemObject").FileExists(guidePath) Then + MsgBox DxToolsGuideMissingMessage(), vbExclamation + Exit Sub + End If + Set shell = CreateObject("WScript.Shell") + shell.Run Chr(34) & guidePath & Chr(34), 1, False +End Sub + +Function DxToolsEnsureRoot() + If DxToolsHome = "" Then DxToolsHome = DxToolsResolveRoot() + DxToolsEnsureRoot = (DxToolsHome <> "") + If Not DxToolsEnsureRoot Then + MsgBox DxToolsPathErrorMessage(), vbExclamation + End If +End Function + +Function DxToolsResolveRoot() + Dim candidate + + DxToolsResolveRoot = "" + DxToolsScriptFullName = "" + DxToolsScriptPathSource = "" + + candidate = DxToolsWScriptFullName() + If DxToolsAcceptScriptPath(candidate, "WScript.ScriptFullName") Then + DxToolsResolveRoot = DxToolsParentFolder(candidate) + Exit Function + End If + + candidate = DxToolsCurrentScriptFullName() + If DxToolsAcceptScriptPath(candidate, _ + "Scripting.CurrentScriptFullName") Then + DxToolsResolveRoot = DxToolsParentFolder(candidate) + Exit Function + End If + + candidate = DxToolsScriptingScriptFullName() + If DxToolsAcceptScriptPath(candidate, "Scripting.ScriptFullName") Then + DxToolsResolveRoot = DxToolsParentFolder(candidate) + End If +End Function + +Function DxToolsWScriptFullName() + DxToolsWScriptFullName = "" + On Error Resume Next + DxToolsWScriptFullName = CStr(WScript.ScriptFullName) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsCurrentScriptFullName() + DxToolsCurrentScriptFullName = "" + On Error Resume Next + DxToolsCurrentScriptFullName = CStr(Scripting.CurrentScriptFullName) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsScriptingScriptFullName() + DxToolsScriptingScriptFullName = "" + On Error Resume Next + DxToolsScriptingScriptFullName = CStr(Scripting.ScriptFullName) + Err.Clear + On Error GoTo 0 +End Function + +Function DxToolsAcceptScriptPath(path, sourceName) + Dim root + Dim fso + DxToolsAcceptScriptPath = False + If Len(CStr(path)) = 0 Then Exit Function + Set fso = CreateObject("Scripting.FileSystemObject") + If Not fso.FileExists(CStr(path)) Then Exit Function + root = fso.GetParentFolderName(CStr(path)) + If Not fso.FileExists(fso.BuildPath(root, "DxDesignerTools.exe")) Then _ + Exit Function + If Not fso.FileExists(fso.BuildPath(root, "DesignBridge.vbs")) Then _ + Exit Function + DxToolsScriptFullName = CStr(path) + DxToolsScriptPathSource = CStr(sourceName) + DxToolsAcceptScriptPath = True +End Function + +Function DxToolsParentFolder(path) + DxToolsParentFolder = CreateObject( _ + "Scripting.FileSystemObject").GetParentFolderName(CStr(path)) +End Function + +Sub DxToolsLoadScript(path) + Dim fso + Dim stream + Dim text + Set fso = CreateObject("Scripting.FileSystemObject") + If Not fso.FileExists(CStr(path)) Then + Err.Raise vbObjectError + 795, "DxToolsLoadScript", _ + "Missing script: " & CStr(path) + End If + Set stream = fso.OpenTextFile(CStr(path), 1, False, 0) + text = stream.ReadAll + stream.Close + ExecuteGlobal text +End Sub + +Function DxToolsSuiteCaption() + DxToolsSuiteCaption = "Dx " & ChrW(&H6548) & ChrW(&H7387) & _ + ChrW(&H5DE5) & ChrW(&H5177) +End Function + +Function DxToolsRefDesCaption() + DxToolsRefDesCaption = ChrW(&H81EA) & ChrW(&H52A8) & ChrW(&H4F4D) & _ + ChrW(&H53F7) +End Function + +Function DxToolsPropertyChangeCaption() + DxToolsPropertyChangeCaption = ChrW(&H5C5E) & ChrW(&H6027) & _ + ChrW(&H6279) & ChrW(&H6539) +End Function + +Function DxToolsPropertyVisibilityCaption() + DxToolsPropertyVisibilityCaption = ChrW(&H5C5E) & ChrW(&H6027) & _ + ChrW(&H663E) & ChrW(&H793A) +End Function + +Function DxToolsInspectionCaption() + DxToolsInspectionCaption = ChrW(&H8BBE) & ChrW(&H8BA1) & _ + ChrW(&H68C0) & ChrW(&H67E5) +End Function + +Function DxToolsBomCaption() + DxToolsBomCaption = "BOM " & ChrW(&H5BFC) & ChrW(&H51FA) +End Function + +Function DxToolsCompatibilityCaption() + DxToolsCompatibilityCaption = ChrW(&H517C) & ChrW(&H5BB9) & _ + ChrW(&H6027) & ChrW(&H68C0) & ChrW(&H6D4B) +End Function + +Function DxToolsGuideCaption() + DxToolsGuideCaption = ChrW(&H4F7F) & ChrW(&H7528) & ChrW(&H8BF4) & _ + ChrW(&H660E) +End Function + +Function DxToolsPathErrorMessage() + DxToolsPathErrorMessage = ChrW(&H65E0) & ChrW(&H6CD5) & _ + ChrW(&H786E) & ChrW(&H5B9A) & ChrW(&H5DE5) & ChrW(&H5177) & _ + ChrW(&H76EE) & ChrW(&H5F55) +End Function + +Function DxToolsGuideMissingMessage() + DxToolsGuideMissingMessage = ChrW(&H4F7F) & ChrW(&H7528) & _ + ChrW(&H8BF4) & ChrW(&H660E) & ChrW(&H6587) & ChrW(&H4EF6) & _ + ChrW(&H4E0D) & ChrW(&H5B58) & ChrW(&H5728) +End Function diff --git a/integration/dxdesigner795/ProbeAction.vbs b/integration/dxdesigner795/ProbeAction.vbs new file mode 100644 index 0000000..17d98a1 --- /dev/null +++ b/integration/dxdesigner795/ProbeAction.vbs @@ -0,0 +1,2 @@ +' DxDesigner 7.9.5 Run-route trampoline. Keep this file ASCII-only. +Call DxToolsProbeExecute("run") diff --git a/integration/dxdesigner795/core/BomExport.vbs b/integration/dxdesigner795/core/BomExport.vbs new file mode 100644 index 0000000..aede5e9 --- /dev/null +++ b/integration/dxdesigner795/core/BomExport.vbs @@ -0,0 +1,125 @@ +' BOM Excel renderer for the DxDesigner 7.9.5 bridge. Keep this file ASCII-only. +' Reads a claimed bom-export.json payload, drives Excel COM exactly like the +' legacy PLBOM form did (template + colors + save-as), and writes +' bom-export-status.json for the GUI. + +Sub DxBridgeRenderBom(runRoot, claimedPath) + Dim text + Dim payload + Dim statusState + Dim statusError + + statusState = "ok" + statusError = "" + On Error Resume Next + text = DxToolsReadUtf8(claimedPath) + If Err.Number <> 0 Then + statusState = "failed" + statusError = "cannot read export payload" + Err.Clear + Else + Call DxBomRenderPayload(text, statusState, statusError) + End If + If Err.Number <> 0 Then + statusState = "failed" + statusError = Err.Description + Err.Clear + End If + On Error GoTo 0 + Call DxBomWriteStatus(runRoot, statusState, statusError) +End Sub + +Sub DxBomRenderPayload(text, ByRef statusState, ByRef statusError) + Dim templatePath + Dim outputPath + Dim designName + Dim descriptionHeader + Dim excel + Dim workbooks + Dim workbook + Dim sheet + Dim saveFormat + + Call DxBomField(text, "template_path", templatePath) + Call DxBomField(text, "output_path", outputPath) + Call DxBomField(text, "design_name", designName) + Call DxBomField(text, "description_header", descriptionHeader) + + Set excel = CreateObject("Excel.Application") + excel.Visible = False + excel.DisplayAlerts = False + Set workbooks = excel.Workbooks + Set workbook = workbooks.Open(CStr(templatePath), 3, True) + Set sheet = workbook.Sheets("Sheet1") + + sheet.Cells(1, 1).Value = designName + sheet.Cells(1, 2).Value = "QTY" + sheet.Cells(1, 3).Value = "REFDES" + sheet.Cells(1, 4).Value = "PART NUMBER" + sheet.Cells(1, 5).Value = UCase(descriptionHeader) + + Call DxBomWriteSections(excel, sheet, text) + + If LCase(Right(CStr(outputPath), 5)) = ".xlsx" Then + saveFormat = 51 + Else + saveFormat = 56 + End If + Call workbook.SaveAs(CStr(outputPath), saveFormat) + excel.Visible = True + excel.DisplayAlerts = True + statusState = "ok" + statusError = "" +End Sub + +Sub DxBomWriteSections(excel, sheet, text) + ' Sections and rows are embedded as line-oriented records to keep the VBS + ' JSON reading trivial: S| / R||||| + Dim lines + Dim line + Dim parts + Dim rowIndex + Dim flagParts + rowIndex = 2 + lines = Split(Replace(CStr(text), vbCr, ""), vbLf) + For Each line In lines + If Left(line, 2) = "S|" Then + sheet.Cells(rowIndex, 1).Value = Mid(line, 3) + sheet.Cells(rowIndex, 1).Font.Bold = True + rowIndex = rowIndex + 1 + ElseIf Left(line, 2) = "R|" Then + parts = Split(line, "|") + sheet.Cells(rowIndex, 2).Value = CLng(parts(1)) + sheet.Cells(rowIndex, 3).Value = parts(2) + sheet.Cells(rowIndex, 4).Value = "'" & parts(3) + sheet.Cells(rowIndex, 5).Value = "'" & parts(4) + If InStr(parts(5), "D") > 0 Then + sheet.Cells(rowIndex, 3).Interior.ColorIndex = 3 + End If + If InStr(parts(5), "M") > 0 Then + sheet.Cells(rowIndex, 4).Interior.ColorIndex = 44 + End If + rowIndex = rowIndex + 1 + End If + Next +End Sub + +Sub DxBomField(text, key, ByRef value) + If DxToolsJsonString(text, key, value) Then Exit Sub + value = "" +End Sub + +Sub DxBomWriteStatus(runRoot, state, errorText) + Dim errorValue + If errorText = "" Then + errorValue = "null" + Else + errorValue = """" & DxToolsJson(errorText) & """" + End If + Call DxToolsWriteUtf8Atomic(runRoot & "\bom-export-status.json", _ + "{" & vbCrLf & _ + " ""format_version"": 2," & vbCrLf & _ + " ""state"": """ & DxToolsJson(state) & """," & vbCrLf & _ + " ""error"": " & errorValue & vbCrLf & _ + "}" & vbCrLf) +End Sub diff --git a/integration/dxdesigner795/core/Mailbox.vbs b/integration/dxdesigner795/core/Mailbox.vbs new file mode 100644 index 0000000..297667a --- /dev/null +++ b/integration/dxdesigner795/core/Mailbox.vbs @@ -0,0 +1,373 @@ +' Mailbox pump for the DxDesigner 7.9.5 bridge: multi-consume apply loop, +' locate navigation, snapshot refresh requests, heartbeat, and run cleanup. +' Keep this file ASCII-only. + +Sub DxToolsDesignBridgeStart(featureKey) + Dim objectMap + Dim originalMap + Dim runRoot + Dim runId + Dim snapshotId + Dim process + Dim state + + Set objectMap = CreateObject("Scripting.Dictionary") + Set originalMap = CreateObject("Scripting.Dictionary") + If Not DxExportSnapshot(objectMap, originalMap, runRoot, runId, _ + snapshotId) Then Exit Sub + Call DxBridgeCleanupRuns(DxBridgeRunsRoot(), CStr(runId)) + Set process = DxLaunchUi(runRoot, featureKey) + If process Is Nothing Then Exit Sub + Call DxWriteProgress(runRoot, "waiting") + state = DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _ + objectMap, originalMap) + If state <> "" Then + MsgBox DxBridgeStateMessage(state), _ + IIf(state = "applied", vbInformation, vbExclamation) + End If +End Sub + +Function DxBridgeRunsRoot() + Dim shell + Set shell = CreateObject("WScript.Shell") + DxBridgeRunsRoot = shell.ExpandEnvironmentStrings( _ + "%LOCALAPPDATA%\DxProductivity\runs") +End Function + +Function DxLaunchUi(runRoot, featureKey) + Dim fso + Dim shell + Dim process + Dim executablePath + Dim launchError + + Set DxLaunchUi = Nothing + Set fso = CreateObject("Scripting.FileSystemObject") + executablePath = DxToolsHome & "\DxDesignerTools.exe" + If Not fso.FileExists(executablePath) Then + MsgBox DxBridgeMissingExecutableMessage() & vbCrLf & _ + executablePath, vbExclamation + Exit Function + End If + + Set shell = CreateObject("WScript.Shell") + launchError = "" + On Error Resume Next + Set process = shell.Exec(DxBridgeUiCommand(runRoot, featureKey)) + If Err.Number <> 0 Then launchError = Err.Description + Err.Clear + On Error GoTo 0 + If launchError <> "" Then + MsgBox DxBridgeLaunchErrorMessage() & vbCrLf & launchError, _ + vbExclamation + Exit Function + End If + Set DxLaunchUi = process +End Function + +Function DxBridgeUiCommand(runRoot, featureKey) + Dim featureSuffix + featureSuffix = "" + If CStr(featureKey) <> "" Then + featureSuffix = " --feature " & DxToolsQuote(CStr(featureKey)) + End If + DxBridgeUiCommand = DxToolsQuote( _ + DxToolsHome & "\DxDesignerTools.exe") & _ + " ui --request " & DxToolsQuote(runRoot & "\request.json") & _ + featureSuffix +End Function + +Function DxBridgeMailboxLoop(process, runRoot, runId, snapshotId, _ + objectMap, originalMap) + Dim fso + Dim resultPath + Dim claimPath + Dim state + Set fso = CreateObject("Scripting.FileSystemObject") + resultPath = fso.BuildPath(runRoot, "result.tsv") + claimPath = fso.BuildPath(runRoot, "result.processing") + state = "" + + Do While process.Status = 0 + Call DxBridgeConsumeLocate(runRoot, objectMap) + Call DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _ + snapshotId) + Call DxBridgePumpBomExport(runRoot) + Call DxBridgeWriteProgress(runRoot, "waiting") + If fso.FileExists(resultPath) Then + If DxBridgeClaimFile(fso, resultPath, claimPath) Then + Call DxWriteProgress(runRoot, "processing") + state = DxProcessApply(runRoot, runId, snapshotId, _ + objectMap, originalMap) + Call DxWriteProgress(runRoot, "waiting") + End If + End If + Call DxBridgeIdleWait() + Loop + If fso.FileExists(resultPath) Then + If DxBridgeClaimFile(fso, resultPath, claimPath) Then + state = DxProcessApply(runRoot, runId, snapshotId, _ + objectMap, originalMap) + End If + End If + DxBridgeMailboxLoop = state +End Function + +Function DxBridgeClaimFile(fso, sourcePath, claimPath) + DxBridgeClaimFile = False + If fso.FileExists(claimPath) Then + On Error Resume Next + fso.DeleteFile claimPath, True + Err.Clear + On Error GoTo 0 + End If + On Error Resume Next + fso.MoveFile sourcePath, claimPath + If Err.Number = 0 Then DxBridgeClaimFile = True + Err.Clear + On Error GoTo 0 +End Function + +Sub DxBridgePumpRefresh(runRoot, runId, objectMap, originalMap, _ + ByRef snapshotId) + Dim fso + Dim refreshPath + Dim claimPath + Set fso = CreateObject("Scripting.FileSystemObject") + refreshPath = fso.BuildPath(runRoot, "refresh.request") + If Not fso.FileExists(refreshPath) Then Exit Sub + claimPath = fso.BuildPath(runRoot, "refresh.processing") + If Not DxBridgeClaimFile(fso, refreshPath, claimPath) Then Exit Sub + Call DxWriteProgress(runRoot, "processing") + If DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _ + snapshotId) Then + Call DxWriteProgress(runRoot, "waiting") + End If + On Error Resume Next + fso.DeleteFile claimPath, True + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxBridgePumpBomExport(runRoot) + Dim fso + Dim bomPath + Dim claimPath + Set fso = CreateObject("Scripting.FileSystemObject") + bomPath = fso.BuildPath(runRoot, "bom-export.json") + If Not fso.FileExists(bomPath) Then Exit Sub + claimPath = fso.BuildPath(runRoot, "bom-export.processing") + If Not DxBridgeClaimFile(fso, bomPath, claimPath) Then Exit Sub + Call DxBridgeRenderBom(runRoot, claimPath) + On Error Resume Next + fso.DeleteFile claimPath, True + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxBridgeConsumeLocate(runRoot, objectMap) + Dim fso + Dim locatePath + Dim processingPath + Dim bridgeId + Dim parts + Set fso = CreateObject("Scripting.FileSystemObject") + locatePath = fso.BuildPath(runRoot, "locate.tsv") + processingPath = fso.BuildPath(runRoot, "locate.processing") + If Not fso.FileExists(locatePath) Then Exit Sub + If Not DxBridgeClaimFile(fso, locatePath, processingPath) Then Exit Sub + On Error Resume Next + bridgeId = Trim(DxToolsReadUtf8(processingPath)) + If Err.Number <> 0 Then + Err.Clear + On Error GoTo 0 + fso.DeleteFile processingPath, True + Exit Sub + End If + Err.Clear + On Error GoTo 0 + fso.DeleteFile processingPath, True + If InStr(bridgeId, "net|") = 1 Then + parts = Split(bridgeId, "|") + If UBound(parts) >= 2 Then + Call DxBridgeLocateNet(parts(1), parts(2)) + End If + ElseIf objectMap.Exists(bridgeId) Then + Call DxBridgeLocateComponent(objectMap(bridgeId)) + End If +End Sub + +Sub DxBridgeLocateNet(netName, pageNumber) + Dim projectData + Dim designs + Dim designId + Dim topBlock + Dim net + Dim found + On Error Resume Next + Set projectData = Application.GetProjectData() + If Err.Number <> 0 Then + Err.Clear + On Error GoTo 0 + Exit Sub + End If + Set designs = projectData.GetiCDBDesigns() + designId = CStr(designs.GetItem(1)) + topBlock = projectData.GetiCDBDesignRootBlock(designId) + Err.Clear + ActiveView.UnselectAll + Err.Clear + Application.PushPath topBlock, "", CLng(pageNumber) + Err.Clear + found = False + For Each net In ActiveView.Query(VDM_NET, VD_ALL) + If CStr(net.Name) = CStr(netName) Then + net.Selected = True + If Err.Number <> 0 Then Err.Clear + ActiveView.ZoomSelect + Err.Clear + found = True + Exit For + End If + Next + Err.Clear + ActiveView.Refresh + Err.Clear + On Error GoTo 0 + If Not found Then + MsgBox DxBridgeNetNotFoundMessage() & vbCrLf & CStr(netName), _ + vbInformation + End If +End Sub + +Function DxBridgeNetNotFoundMessage() + DxBridgeNetNotFoundMessage = ChrW(&H672A) & ChrW(&H627E) & _ + ChrW(&H5230) & ChrW(&H7F51) & ChrW(&H7EDC) +End Function + +Sub DxBridgeLocateComponent(component) + On Error Resume Next + ActiveView.UnselectAll + Err.Clear + ActiveView.Select component + If Err.Number <> 0 Then + Err.Clear + ActiveView.SelectObject component + End If + Err.Clear + ActiveView.ZoomTo component + Err.Clear + ActiveView.Refresh + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxBridgeCleanupRuns(runsRoot, currentRunId) + Dim fso + Dim folder + Dim item + Dim names + Dim index + Dim inner + Dim temp + Const KEEP_RUNS = 20 + + On Error Resume Next + Set fso = CreateObject("Scripting.FileSystemObject") + If Not fso.FolderExists(CStr(runsRoot)) Then Exit Sub + Set folder = fso.GetFolder(CStr(runsRoot)) + If folder.SubFolders.Count <= KEEP_RUNS Then + Err.Clear + On Error GoTo 0 + Exit Sub + End If + names = Array() + ReDim names(folder.SubFolders.Count - 1) + index = 0 + For Each item In folder.SubFolders + names(index) = CStr(item.Name) + index = index + 1 + Next + For index = 0 To UBound(names) + For inner = index + 1 To UBound(names) + If StrComp(names(inner), names(index), vbTextCompare) > 0 Then + temp = names(index) + names(index) = names(inner) + names(inner) = temp + End If + Next + Next + For index = KEEP_RUNS To UBound(names) + If names(index) <> CStr(currentRunId) Then + fso.DeleteFolder fso.BuildPath(CStr(runsRoot), names(index)), True + Err.Clear + End If + Next + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxBridgeYield() + On Error Resume Next + Scripting.DoEvents + If Err.Number = 0 Then + On Error GoTo 0 + Exit Sub + End If + Err.Clear + Application.DoEvents + If Err.Number = 0 Then + On Error GoTo 0 + Exit Sub + End If + Err.Clear + ActiveView.Refresh + Err.Clear + On Error GoTo 0 +End Sub + +Function DxBridgeStateMessage(state) + Select Case CStr(state) + Case "applied" + DxBridgeStateMessage = DxBridgeTextApplied() + Case "rolled-back" + DxBridgeStateMessage = DxBridgeTextRolledBack() + Case "rejected" + DxBridgeStateMessage = DxBridgeTextRejected() + Case Else + DxBridgeStateMessage = DxBridgeTextRollbackFailed() + End Select +End Function + +Function DxBridgeTextApplied() + DxBridgeTextApplied = ChrW(&H5E94) & ChrW(&H7528) & ChrW(&H5B8C) & _ + ChrW(&H6210) +End Function + +Function DxBridgeTextRolledBack() + DxBridgeTextRolledBack = ChrW(&H5DF2) & ChrW(&H56DE) & ChrW(&H6EDA) +End Function + +Function DxBridgeTextRejected() + DxBridgeTextRejected = ChrW(&H5DF2) & ChrW(&H62D2) & ChrW(&H7EDD) & _ + ChrW(&HFF1A) & ChrW(&H8BBE) & ChrW(&H8BA1) & ChrW(&H72B6) & _ + ChrW(&H6001) & ChrW(&H4E0E) & ChrW(&H9884) & ChrW(&H89C8) & _ + ChrW(&H4E0D) & ChrW(&H4E00) & ChrW(&H81F4) +End Function + +Function DxBridgeTextRollbackFailed() + DxBridgeTextRollbackFailed = ChrW(&H56DE) & ChrW(&H6EDA) & _ + ChrW(&H5931) & ChrW(&H8D25) & ChrW(&HFF0C) & ChrW(&H8BF7) & _ + ChrW(&H68C0) & ChrW(&H67E5) & ChrW(&H8BBE) & ChrW(&H8BA1) +End Function + +Function DxBridgeMissingExecutableMessage() + DxBridgeMissingExecutableMessage = ChrW(&H627E) & ChrW(&H4E0D) & _ + ChrW(&H5230) & ChrW(&H5DE5) & ChrW(&H5177) & _ + ChrW(&H4E3B) & ChrW(&H7A0B) & ChrW(&H5E8F) +End Function + +Function DxBridgeLaunchErrorMessage() + DxBridgeLaunchErrorMessage = ChrW(&H5DE5) & ChrW(&H5177) & _ + ChrW(&H542F) & ChrW(&H52A8) & ChrW(&H5931) & ChrW(&H8D25) +End Function diff --git a/integration/dxdesigner795/core/Snapshot.vbs b/integration/dxdesigner795/core/Snapshot.vbs new file mode 100644 index 0000000..2bda7c2 --- /dev/null +++ b/integration/dxdesigner795/core/Snapshot.vbs @@ -0,0 +1,495 @@ +' Design snapshot export for the DxDesigner 7.9.5 bridge (protocol v2). +' Keep this file ASCII-only. + +Function DxExportSnapshot(objectMap, originalMap, ByRef runRoot, _ + ByRef runId, ByRef snapshotId) + Dim shell + Dim runsRoot + + DxExportSnapshot = False + Set shell = CreateObject("WScript.Shell") + runId = DxBridgeCreateRunId() + runsRoot = shell.ExpandEnvironmentStrings( _ + "%LOCALAPPDATA%\DxProductivity\runs") + runRoot = fsoBuildPath(runsRoot, CStr(runId)) + Call DxBridgeEnsureFolder(runRoot) + DxExportSnapshot = DxRefreshSnapshot(runRoot, runId, objectMap, _ + originalMap, snapshotId) +End Function + +Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _ + ByRef snapshotId) + Dim projectData + Dim designs + Dim designId + Dim topBlock + Dim component + Dim selected + Dim selectedKeys + Dim componentCount + Dim bridgeId + Dim stableUid + Dim fullPath + Dim logicalKey + Dim sheetNumber + Dim sheetName + Dim refdes + Dim symbolDefault + Dim requestText + Dim componentText + Dim designPath + Dim selectedValue + Dim currentSheetValue + Dim identityKey + Dim attributesText + Dim netsText + Dim selectedNetsText + Dim snapshotSequence + + DxRefreshSnapshot = False + Set selectedKeys = CreateObject("Scripting.Dictionary") + On Error Resume Next + For Each selected In ActiveView.Query(VDM_COMP, VD_SELECTED) + identityKey = DxBridgeComponentIdentity(selected) + If identityKey <> "" And Not selectedKeys.Exists(identityKey) Then + selectedKeys.Add identityKey, True + End If + Next + Err.Clear + On Error GoTo 0 + + On Error Resume Next + Set projectData = Application.GetProjectData() + If Err.Number <> 0 Then + Err.Clear + On Error GoTo 0 + Call DxBridgeExportFailed(DxBridgeProjectUnavailableMessage()) + Exit Function + End If + On Error GoTo 0 + Set designs = projectData.GetiCDBDesigns() + designId = CStr(designs.GetItem(1)) + topBlock = projectData.GetiCDBDesignRootBlock(designId) + designPath = DxBridgeDesignPath() + componentCount = 0 + componentText = "" + + For Each component In Application.DesignComponents( _ + "", topBlock, "-1", "STD", True) + componentCount = componentCount + 1 + bridgeId = "c" & DxBridgePad(componentCount, 6) + stableUid = DxBridgeStableUid(component) + fullPath = DxBridgeFullPath(component) + If stableUid = "" And fullPath = "" Then + Call DxBridgeExportFailed(DxBridgeIdentityUnavailableMessage()) + Exit Function + End If + If stableUid <> "" Then + logicalKey = stableUid + Else + logicalKey = fullPath + End If + refdes = DxBridgeRefdes(component) + symbolDefault = DxBridgeSymbolDefault(component, refdes) + sheetNumber = DxBridgeSheetNumber(component) + sheetName = CStr(sheetNumber) + identityKey = DxBridgeIdentityKey(stableUid, fullPath) + selectedValue = selectedKeys.Exists(identityKey) + currentSheetValue = (sheetNumber = DxBridgeCurrentSheetNumber()) + attributesText = DxBridgeExportAttributes(component) + + objectMap.Add bridgeId, component + If componentText <> "" Then componentText = componentText & "," & vbCrLf + componentText = componentText & _ + " {" & vbCrLf & _ + " ""bridge_id"": """ & DxToolsJson(bridgeId) & """," & vbCrLf & _ + " ""stable_uid"": " & DxBridgeNullable(stableUid) & "," & vbCrLf & _ + " ""full_path"": """ & DxToolsJson(fullPath) & """," & vbCrLf & _ + " ""logical_group_key"": """ & DxToolsJson(logicalKey) & """," & vbCrLf & _ + " ""sheet_name"": """ & DxToolsJson(sheetName) & """," & vbCrLf & _ + " ""sheet_number"": " & CStr(sheetNumber) & "," & vbCrLf & _ + " ""x"": """ & DxBridgeCoordinate(component, True) & """," & vbCrLf & _ + " ""y"": """ & DxBridgeCoordinate(component, False) & """," & vbCrLf & _ + " ""y_axis_up"": true," & vbCrLf & _ + " ""refdes"": """ & DxToolsJson(refdes) & """," & vbCrLf & _ + " ""symbol_refdes_default"": " & _ + DxBridgeNullable(symbolDefault) & "," & vbCrLf & _ + " ""selected"": " & DxBridgeBoolean(selectedValue) & "," & vbCrLf & _ + " ""current_sheet"": " & _ + DxBridgeBoolean(currentSheetValue) & "," & vbCrLf & _ + " ""part_number"": """ & _ + DxToolsJson(DxBridgePartNumber(component)) & """," & vbCrLf & _ + " ""value"": """ & _ + DxToolsJson(DxBridgeValue(component)) & """," & vbCrLf & _ + " ""locked"": " & DxBridgeBoolean(DxBridgeLocked(component)) & "," & vbCrLf & _ + " ""attributes"": " & attributesText & vbCrLf & _ + " }" + Next + If componentCount = 0 Then + Call DxBridgeExportFailed(DxBridgeEmptyDesignMessage()) + Exit Function + End If + + netsText = DxBridgeExportNets(topBlock) + selectedNetsText = DxBridgeExportSelectedNets() + snapshotSequence = DxBridgeNextSnapshotSequence(runRoot) + snapshotId = "snapshot-" & CStr(runId) & "-" & CStr(snapshotSequence) + + requestText = "{" & vbCrLf & _ + " ""format_version"": 2," & vbCrLf & _ + " ""run_id"": """ & DxToolsJson(runId) & """," & vbCrLf & _ + " ""snapshot_id"": """ & DxToolsJson(snapshotId) & """," & vbCrLf & _ + " ""design_id"": """ & DxToolsJson(designId) & """," & vbCrLf & _ + " ""design_path"": """ & DxToolsJson(designPath) & """," & vbCrLf & _ + " ""nets"": " & netsText & "," & vbCrLf & _ + " ""selected_nets"": " & selectedNetsText & "," & vbCrLf & _ + " ""components"": [" & vbCrLf & componentText & vbCrLf & _ + " ]" & vbCrLf & "}" & vbCrLf + Call DxToolsWriteUtf8Atomic(fsoBuildPath(runRoot, "request.json"), _ + requestText) + DxRefreshSnapshot = True +End Function + +Function DxBridgeExportAttributes(component) + Dim attribute + Dim text + Dim count + Dim name + Dim value + Dim visible + + text = "" + count = 0 + On Error Resume Next + For Each attribute In component.Attributes + name = CStr(attribute.Name) + value = CStr(attribute.Value) + visible = DxBridgeNormalizeVisible(attribute.Visible) + If Err.Number <> 0 Then + Err.Clear + ElseIf name <> "" Then + If text <> "" Then text = text & ", " + text = text & _ + "{""name"": """ & DxToolsJson(name) & """" & _ + ", ""value"": """ & DxToolsJson(value) & """" & _ + ", ""visible"": " & DxBridgeBoolean(visible) & "}" + count = count + 1 + End If + Next + Err.Clear + On Error GoTo 0 + DxBridgeExportAttributes = "[" & text & "]" +End Function + +Function DxBridgeExportNets(topBlock) + Dim nets + Dim net + Dim name + Dim page + Dim pages + Dim names + Dim text + Dim nameText + + DxBridgeExportNets = "[]" + On Error Resume Next + Set nets = Application.DesignNets("", topBlock, "-1", "STD", True) + If Err.Number <> 0 Or nets Is Nothing Then + Err.Clear + On Error GoTo 0 + Exit Function + End If + Set pages = CreateObject("Scripting.Dictionary") + Set names = CreateObject("Scripting.Dictionary") + For Each net In nets + name = "" + page = -1 + name = CStr(net.Name) + If Err.Number <> 0 Then + Err.Clear + name = "" + End If + page = CLng(net.SheetNum) + If Err.Number <> 0 Then + Err.Clear + page = DxBridgeCurrentSheetNumber() + End If + If name <> "" And page >= 0 Then + nameText = LCase(name) + If Not names.Exists(nameText) Then + names.Add nameText, name + pages.Add nameText, CStr(page) + ElseIf InStr(pages(nameText), CStr(page)) = 0 Then + pages(nameText) = pages(nameText) & ", " & CStr(page) + End If + End If + Next + Err.Clear + On Error GoTo 0 + + For Each nameText In names.Keys + If text <> "" Then text = text & ", " + text = text & _ + "{""name"": """ & DxToolsJson(names(nameText)) & """" & _ + ", ""pages"": [" & pages(nameText) & "]}" + Next + DxBridgeExportNets = "[" & text & "]" +End Function + +Function DxBridgeExportSelectedNets() + Dim net + Dim name + Dim text + + DxBridgeExportSelectedNets = "[]" + text = "" + On Error Resume Next + For Each net In ActiveView.Query(VDM_NET, VD_SELECTED) + name = CStr(net.Name) + If Err.Number <> 0 Then + Err.Clear + ElseIf name <> "" Then + If text <> "" Then text = text & ", " + text = text & """" & DxToolsJson(name) & """" + End If + Next + Err.Clear + On Error GoTo 0 + DxBridgeExportSelectedNets = "[" & text & "]" +End Function + +Function DxBridgeNextSnapshotSequence(runRoot) + Dim fso + Dim sequencePath + Dim text + Set fso = CreateObject("Scripting.FileSystemObject") + sequencePath = fsoBuildPath(runRoot, "snapshot.seq") + DxBridgeNextSnapshotSequence = 1 + On Error Resume Next + If fso.FileExists(sequencePath) Then + text = Trim(DxToolsReadUtf8(sequencePath)) + If IsNumeric(text) Then + DxBridgeNextSnapshotSequence = CLng(text) + 1 + End If + End If + If Err.Number <> 0 Then + Err.Clear + DxBridgeNextSnapshotSequence = 1 + End If + On Error GoTo 0 + Call DxToolsWriteUtf8Atomic(sequencePath, _ + CStr(DxBridgeNextSnapshotSequence) & vbCrLf) +End Function + +Sub DxBridgeExportFailed(message) + MsgBox DxBridgeExportFailedPrefix() & vbCrLf & message, vbExclamation +End Sub + +Function fsoBuildPath(parent, child) + fsoBuildPath = CreateObject("Scripting.FileSystemObject").BuildPath( _ + CStr(parent), CStr(child)) +End Function + +Function DxBridgeCreateRunId() + Randomize + DxBridgeCreateRunId = CStr(Year(Now)) & DxBridgePad(Month(Now), 2) & _ + DxBridgePad(Day(Now), 2) & "T" & DxBridgePad(Hour(Now), 2) & _ + DxBridgePad(Minute(Now), 2) & DxBridgePad(Second(Now), 2) & "-" & _ + DxBridgePad(Hex(CLng(Rnd * 2147483647)), 8) +End Function + +Function DxBridgePad(value, width) + DxBridgePad = Right(String(CLng(width), "0") & CStr(value), CLng(width)) +End Function + +Function DxBridgeStableUid(component) + DxBridgeStableUid = "" + On Error Resume Next + DxBridgeStableUid = CStr(component.UID) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeFullPath(component) + Dim parentName + Dim componentName + parentName = "" + componentName = "" + On Error Resume Next + parentName = CStr(component.Parent.Name) + componentName = CStr(component.GetName(SHORT_NAME)) + Err.Clear + On Error GoTo 0 + If componentName = "" Then + On Error Resume Next + componentName = CStr(component.Name) + Err.Clear + On Error GoTo 0 + End If + If parentName <> "" And componentName <> "" Then + DxBridgeFullPath = parentName & "\" & componentName + Else + DxBridgeFullPath = componentName + End If +End Function + +Function DxBridgeIdentityKey(stableUid, fullPath) + If CStr(stableUid) <> "" Then + DxBridgeIdentityKey = "uid:" & LCase(CStr(stableUid)) + ElseIf CStr(fullPath) <> "" Then + DxBridgeIdentityKey = "path:" & LCase(CStr(fullPath)) + Else + DxBridgeIdentityKey = "" + End If +End Function + +Function DxBridgeComponentIdentity(component) + DxBridgeComponentIdentity = DxBridgeIdentityKey( _ + DxBridgeStableUid(component), DxBridgeFullPath(component)) +End Function + +Function DxBridgeRefdes(component) + DxBridgeRefdes = "" + On Error Resume Next + DxBridgeRefdes = CStr(component.Refdes) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeSymbolDefault(component, refdes) + DxBridgeSymbolDefault = "" + On Error Resume Next + DxBridgeSymbolDefault = CStr(component.SymbolRefdesDefault) + Err.Clear + On Error GoTo 0 + If DxBridgeSymbolDefault = "" And InStr(CStr(refdes), "?") > 0 Then + DxBridgeSymbolDefault = CStr(refdes) + End If +End Function + +Function DxBridgeSheetNumber(component) + DxBridgeSheetNumber = DxBridgeCurrentSheetNumber() + On Error Resume Next + DxBridgeSheetNumber = CLng(component.Parent.SheetNum) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeCurrentSheetNumber() + DxBridgeCurrentSheetNumber = 0 + On Error Resume Next + DxBridgeCurrentSheetNumber = CLng(ActiveView.Block.SheetNum) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeCoordinate(component, readX) + Dim value + value = 0 + On Error Resume Next + If CBool(readX) Then + value = component.X + Else + value = component.Y + End If + If Err.Number <> 0 Then + Err.Clear + If CBool(readX) Then + value = component.PositionX + Else + value = component.PositionY + End If + End If + Err.Clear + On Error GoTo 0 + DxBridgeCoordinate = Replace(CStr(value), ",", ".") +End Function + +Function DxBridgePartNumber(component) + DxBridgePartNumber = "" + On Error Resume Next + DxBridgePartNumber = CStr(component.PartNumber) + Err.Clear + On Error GoTo 0 + If DxBridgePartNumber = "" Then + DxBridgePartNumber = DxBridgeAttribute(component, "Part Number") + End If +End Function + +Function DxBridgeValue(component) + DxBridgeValue = "" + On Error Resume Next + DxBridgeValue = CStr(component.Value) + Err.Clear + On Error GoTo 0 + If DxBridgeValue = "" Then + DxBridgeValue = DxBridgeAttribute(component, "Value") + End If +End Function + +Function DxBridgeAttribute(component, name) + DxBridgeAttribute = "" + On Error Resume Next + DxBridgeAttribute = CStr(component.Attributes.Item(CStr(name)).Value) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeLocked(component) + DxBridgeLocked = False + On Error Resume Next + DxBridgeLocked = CBool(component.Locked) + If Err.Number <> 0 Then + Err.Clear + DxBridgeLocked = False + End If + On Error GoTo 0 +End Function + +Function DxBridgeDesignPath() + DxBridgeDesignPath = "" + On Error Resume Next + DxBridgeDesignPath = CStr(Application.ProjectPath) + Err.Clear + On Error GoTo 0 +End Function + +Function DxBridgeNullable(value) + If CStr(value) = "" Then + DxBridgeNullable = "null" + Else + DxBridgeNullable = """" & DxToolsJson(value) & """" + End If +End Function + +Function DxBridgeBoolean(value) + If CBool(value) Then + DxBridgeBoolean = "true" + Else + DxBridgeBoolean = "false" + End If +End Function + +Function DxBridgeExportFailedPrefix() + DxBridgeExportFailedPrefix = ChrW(&H65E0) & ChrW(&H6CD5) & _ + ChrW(&H5BFC) & ChrW(&H51FA) & ChrW(&H8BBE) & ChrW(&H8BA1) & _ + ChrW(&H5FEB) & ChrW(&H7167) +End Function + +Function DxBridgeProjectUnavailableMessage() + DxBridgeProjectUnavailableMessage = ChrW(&H65E0) & ChrW(&H6CD5) & _ + ChrW(&H8BBF) & ChrW(&H95EE) & ChrW(&H5F53) & ChrW(&H524D) & _ + ChrW(&H5DE5) & ChrW(&H7A0B) +End Function + +Function DxBridgeIdentityUnavailableMessage() + DxBridgeIdentityUnavailableMessage = ChrW(&H67D0) & ChrW(&H5668) & _ + ChrW(&H4EF6) & ChrW(&H8EAB) & ChrW(&H4EFD) & ChrW(&H4E0D) & _ + ChrW(&H53EF) & ChrW(&H8BFB) +End Function + +Function DxBridgeEmptyDesignMessage() + DxBridgeEmptyDesignMessage = ChrW(&H5F53) & ChrW(&H524D) & _ + ChrW(&H8BBE) & ChrW(&H8BA1) & ChrW(&H6CA1) & ChrW(&H6709) & _ + ChrW(&H5668) & ChrW(&H4EF6) +End Function diff --git a/integration/dxdesigner795/core/Transaction.vbs b/integration/dxdesigner795/core/Transaction.vbs new file mode 100644 index 0000000..5931b5d --- /dev/null +++ b/integration/dxdesigner795/core/Transaction.vbs @@ -0,0 +1,441 @@ +' Generalized apply transaction for the DxDesigner 7.9.5 bridge (protocol v2). +' Keep this file ASCII-only. + +Function DxProcessApply(runRoot, runId, snapshotId, objectMap, originalMap) + Dim resultText + Dim backupPath + Dim errorText + Dim failingSequence + Dim changedCount + Dim rollbackState + Dim state + + state = "rejected" + failingSequence = 0 + changedCount = 0 + rollbackState = "" + If DxPreflightApply(runRoot, runId, snapshotId, objectMap, _ + resultText, backupPath, errorText) Then + state = DxApplySchedule(resultText, objectMap, _ + failingSequence, changedCount, rollbackState, errorText) + End If + Call DxWriteApplyStatus(runRoot, runId, state, changedCount, _ + backupPath, failingSequence, errorText, rollbackState) + DxProcessApply = state +End Function + +Function DxPreflightApply(runRoot, runId, snapshotId, objectMap, _ + ByRef resultText, ByRef backupPath, ByRef errorText) + Dim fso + Dim requestPath + Dim resultPath + Dim requestText + Dim requestRunId + Dim requestSnapshotId + Dim digest + Dim actualDigest + Dim lines + Dim line + Dim sequence + Dim op + Dim bridgeId + Dim propertyName + Dim expectedValue + Dim newValue + Dim finalValue + Dim expectedSequence + Dim rowCount + Dim counts + Dim projected + Dim key + Dim component + + DxPreflightApply = False + errorText = "" + backupPath = "" + Set fso = CreateObject("Scripting.FileSystemObject") + requestPath = fso.BuildPath(runRoot, "apply-request.json") + resultPath = fso.BuildPath(runRoot, "result.tsv") + If Not fso.FileExists(requestPath) Or Not fso.FileExists(resultPath) Then + errorText = "Apply request is incomplete" + Exit Function + End If + + requestText = DxToolsReadUtf8(requestPath) + If InStr(requestText, """format_version"": 2,") = 0 Then + errorText = "Unsupported apply request version" + Exit Function + End If + If Not DxToolsJsonString(requestText, "run_id", requestRunId) Or _ + Not DxToolsJsonString(requestText, "snapshot_id", _ + requestSnapshotId) Or _ + Not DxToolsJsonString(requestText, "backup_path", backupPath) Or _ + Not DxToolsJsonString(requestText, "schedule_sha256", digest) Then + errorText = "Apply request fields are invalid" + Exit Function + End If + If requestRunId <> CStr(runId) Or _ + requestSnapshotId <> CStr(snapshotId) Then + errorText = "Apply request identity is stale" + Exit Function + End If + If Not fso.FileExists(backupPath) Then + errorText = "Apply backup is missing" + Exit Function + End If + actualDigest = DxToolsSha256File(resultPath) + If LCase(digest) <> LCase(actualDigest) Then + errorText = "Apply schedule digest mismatch" + Exit Function + End If + + resultText = DxToolsReadUtf8(resultPath) + lines = Split(Replace(resultText, vbCr, ""), vbLf) + expectedSequence = 1 + rowCount = 0 + Set counts = CreateObject("Scripting.Dictionary") + Set projected = CreateObject("Scripting.Dictionary") + For Each line In lines + If Len(line) > 0 Then + rowCount = rowCount + 1 + If Not DxToolsParseScheduleRow(line, sequence, op, bridgeId, _ + propertyName, expectedValue, newValue, finalValue) Then + errorText = "Apply schedule row is invalid" + Exit Function + End If + If sequence <> expectedSequence Then + errorText = "Apply schedule sequence is not contiguous" + Exit Function + End If + If Not objectMap.Exists(bridgeId) Then + errorText = "Apply schedule has an unknown bridge ID" + Exit Function + End If + If Not DxBridgeOpSupported(op) Then + errorText = "Apply schedule has an unsupported operation" + Exit Function + End If + key = DxBridgeOpKey(op, propertyName, bridgeId) + If counts.Exists(key) Then + counts(key) = counts(key) + 1 + Else + counts.Add key, 1 + End If + If counts(key) > 2 Then + errorText = "Apply schedule repeats an operation target" + Exit Function + End If + If Not projected.Exists(key) Then + Set component = objectMap(bridgeId) + projected.Add key, DxBridgeReadOpValue(component, op, _ + propertyName) + End If + If Not DxBridgeOpValueMatches(op, projected(key), _ + expectedValue) Then + errorText = "Apply schedule expected value is stale" + Exit Function + End If + projected(key) = CStr(newValue) + expectedSequence = expectedSequence + 1 + End If + Next + If rowCount = 0 Then + errorText = "Apply schedule is empty" + Exit Function + End If + DxPreflightApply = True +End Function + +Function DxApplySchedule(resultText, objectMap, _ + ByRef failingSequence, ByRef changedCount, ByRef rollbackState, _ + ByRef errorText) + Dim lines + Dim line + Dim sequence + Dim op + Dim bridgeId + Dim propertyName + Dim expectedValue + Dim newValue + Dim finalValue + Dim component + Dim touched + Dim originals + Dim finals + Dim key + Dim actual + Dim writeError + + Set touched = CreateObject("Scripting.Dictionary") + Set originals = CreateObject("Scripting.Dictionary") + Set finals = CreateObject("Scripting.Dictionary") + lines = Split(Replace(CStr(resultText), vbCr, ""), vbLf) + For Each line In lines + If Len(line) > 0 Then + Call DxToolsParseScheduleRow(line, sequence, op, bridgeId, _ + propertyName, expectedValue, newValue, finalValue) + Set component = objectMap(bridgeId) + actual = DxBridgeReadOpValue(component, op, propertyName) + If Not DxBridgeOpValueMatches(op, actual, expectedValue) Then + failingSequence = sequence + errorText = "Component changed after preflight" + If touched.Count = 0 Then + DxApplySchedule = "rejected" + Exit Function + End If + DxApplySchedule = DxRollbackState(objectMap, originals, _ + touched, rollbackState, errorText) + Exit Function + End If + key = DxBridgeOpKey(op, propertyName, bridgeId) + If Not touched.Exists(key) Then + touched.Add key, Array(CStr(op), CStr(propertyName), _ + CStr(bridgeId)) + originals.Add key, actual + End If + writeError = "" + If Not DxBridgeWriteOpValue(component, op, propertyName, _ + newValue, writeError) Then + failingSequence = sequence + If writeError = "" Then + errorText = "Operation did not persist" + Else + errorText = writeError + End If + DxApplySchedule = DxRollbackState(objectMap, originals, _ + touched, rollbackState, errorText) + Exit Function + End If + If Not DxBridgeOpValueMatches(op, _ + DxBridgeReadOpValue(component, op, propertyName), _ + newValue) Then + failingSequence = sequence + errorText = "Operation did not persist" + DxApplySchedule = DxRollbackState(objectMap, originals, _ + touched, rollbackState, errorText) + Exit Function + End If + finals.Add key, Array(CStr(op), CStr(propertyName), _ + CStr(bridgeId), CStr(finalValue)) + End If + Next + + If Not DxVerifyOperations(objectMap, finals, errorText) Then + DxApplySchedule = DxRollbackState(objectMap, originals, touched, _ + rollbackState, errorText) + Exit Function + End If + changedCount = touched.Count + DxApplySchedule = "applied" +End Function + +Function DxRollbackState(objectMap, originals, touched, _ + ByRef rollbackState, ByRef errorText) + Dim rollbackError + rollbackError = "" + If DxRollback(objectMap, originals, touched, rollbackError) Then + rollbackState = "verified" + DxRollbackState = "rolled-back" + Else + rollbackState = "failed" + If rollbackError <> "" Then errorText = errorText & "; " & rollbackError + DxRollbackState = "rollback-failed" + End If +End Function + +Function DxRollback(objectMap, originals, touched, ByRef errorText) + Dim key + Dim entry + Dim component + Dim writeError + DxRollback = True + errorText = "" + For Each key In touched.Keys + entry = touched(key) + Set component = objectMap(entry(2)) + writeError = "" + If Not DxBridgeWriteOpValue(component, entry(0), entry(1), _ + originals(key), writeError) Then + DxRollback = False + errorText = "Rollback write failed for " & CStr(entry(2)) + ElseIf Not DxBridgeOpValueMatches(entry(0), _ + DxBridgeReadOpValue(component, entry(0), entry(1)), _ + originals(key)) Then + DxRollback = False + errorText = "Rollback verification failed for " & CStr(entry(2)) + End If + Next +End Function + +Function DxVerifyOperations(objectMap, finals, ByRef errorText) + Dim key + Dim entry + Dim bridgeId + Dim refdes + Dim formalValues + Dim hasRefdesOps + + DxVerifyOperations = False + hasRefdesOps = False + For Each key In finals.Keys + entry = finals(key) + If Not DxBridgeOpValueMatches(entry(0), _ + DxBridgeReadOpValue(objectMap(entry(2)), entry(0), _ + entry(1)), entry(3)) Then + errorText = "Final verification failed for " & CStr(entry(2)) + Exit Function + End If + If entry(0) = "refdes" Then hasRefdesOps = True + Next + If hasRefdesOps Then + Set formalValues = CreateObject("Scripting.Dictionary") + For Each bridgeId In objectMap.Keys + refdes = CStr(objectMap(bridgeId).Refdes) + If DxBridgeIsFormalRefdes(refdes) Then + If formalValues.Exists(LCase(refdes)) Then + errorText = "Duplicate reference designator: " & refdes + Exit Function + End If + formalValues.Add LCase(refdes), bridgeId + End If + Next + End If + DxVerifyOperations = True +End Function + +Function DxBridgeIsFormalRefdes(value) + Dim expression + Set expression = CreateObject("VBScript.RegExp") + expression.Pattern = "^[A-Za-z]+[0-9]+$" + expression.IgnoreCase = True + DxBridgeIsFormalRefdes = expression.Test(CStr(value)) +End Function + +Function DxBridgeOpSupported(op) + DxBridgeOpSupported = False + If CStr(op) = "refdes" Then DxBridgeOpSupported = True + If CStr(op) = "property" Then DxBridgeOpSupported = True + If CStr(op) = "visibility" Then DxBridgeOpSupported = True +End Function + +Function DxBridgeOpKey(op, propertyName, bridgeId) + DxBridgeOpKey = CStr(op) & "|" & LCase(CStr(propertyName)) & "|" & _ + LCase(CStr(bridgeId)) +End Function + +Function DxBridgeReadOpValue(component, op, propertyName) + Select Case CStr(op) + Case "refdes" + DxBridgeReadOpValue = CStr(component.Refdes) + Case "property" + DxBridgeReadOpValue = "" + On Error Resume Next + DxBridgeReadOpValue = CStr( _ + component.Attributes.Item(CStr(propertyName)).Value) + If Err.Number <> 0 Then + Err.Clear + DxBridgeReadOpValue = "" + End If + On Error GoTo 0 + Case "visibility" + DxBridgeReadOpValue = "" + On Error Resume Next + DxBridgeReadOpValue = DxBridgeNormalizeVisible( _ + component.Attributes.Item(CStr(propertyName)).Visible) + If Err.Number <> 0 Then + Err.Clear + DxBridgeReadOpValue = "" + End If + On Error GoTo 0 + Case Else + DxBridgeReadOpValue = "" + End Select +End Function + +Function DxBridgeWriteOpValue(component, op, propertyName, value, _ + ByRef errorText) + DxBridgeWriteOpValue = False + errorText = "" + On Error Resume Next + Select Case CStr(op) + Case "refdes" + component.Refdes = CStr(value) + Case "property" + component.Attributes.Item(CStr(propertyName)).Value = CStr(value) + Case "visibility" + component.Attributes.Item(CStr(propertyName)).Visible = _ + CBool(CStr(value)) + Case Else + Err.Raise vbObjectError + 801, "DxBridgeWriteOpValue", _ + "Unsupported operation: " & CStr(op) + End Select + If Err.Number <> 0 Then + errorText = Err.Description + Err.Clear + On Error GoTo 0 + Exit Function + End If + Err.Clear + On Error GoTo 0 + DxBridgeWriteOpValue = True +End Function + +Function DxBridgeOpValueMatches(op, actual, expected) + If CStr(op) = "refdes" Then + DxBridgeOpValueMatches = (LCase(CStr(actual)) = LCase(CStr(expected))) + Else + DxBridgeOpValueMatches = (CStr(actual) = CStr(expected)) + End If +End Function + +Sub DxWriteApplyStatus(runRoot, runId, state, changedCount, backupPath, _ + failingSequence, errorText, rollbackState) + Dim text + Dim failingValue + Dim backupValue + Dim errorValue + Dim rollbackValue + If failingSequence > 0 Then + failingValue = CStr(failingSequence) + Else + failingValue = "null" + End If + If backupPath = "" Then + backupValue = "null" + Else + backupValue = """" & DxToolsJson(backupPath) & """" + End If + If errorText = "" Then + errorValue = "null" + Else + errorValue = """" & DxToolsJson(errorText) & """" + End If + If rollbackState = "" Then + rollbackValue = "null" + Else + rollbackValue = """" & DxToolsJson(rollbackState) & """" + End If + text = "{" & vbCrLf & _ + " ""format_version"": 2," & vbCrLf & _ + " ""run_id"": """ & DxToolsJson(runId) & """," & vbCrLf & _ + " ""state"": """ & DxToolsJson(state) & """," & vbCrLf & _ + " ""changed_count"": " & CStr(changedCount) & "," & vbCrLf & _ + " ""backup_path"": " & backupValue & "," & vbCrLf & _ + " ""failing_sequence"": " & failingValue & "," & vbCrLf & _ + " ""error"": " & errorValue & "," & vbCrLf & _ + " ""rollback_state"": " & rollbackValue & vbCrLf & _ + "}" & vbCrLf + Call DxToolsWriteUtf8Atomic(runRoot & "\apply-status.json", text) +End Sub + +Sub DxWriteProgress(runRoot, state) + On Error Resume Next + Call DxToolsWriteUtf8Atomic(runRoot & "\apply-progress.json", _ + "{" & vbCrLf & _ + " ""format_version"": 2," & vbCrLf & _ + " ""state"": """ & DxToolsJson(state) & """," & vbCrLf & _ + " ""updated"": """ & DxToolsJson(Now) & """" & vbCrLf & _ + "}" & vbCrLf) + Err.Clear + On Error GoTo 0 +End Sub diff --git a/integration/dxdesigner795/expedition/ExpeditionBridge.vbs b/integration/dxdesigner795/expedition/ExpeditionBridge.vbs new file mode 100644 index 0000000..bbad9c0 --- /dev/null +++ b/integration/dxdesigner795/expedition/ExpeditionBridge.vbs @@ -0,0 +1,338 @@ +' Expedition PCB bridge for the assembly refdes tidy-up. Keep this file ASCII-only. +' Native migration of the legacy MoveAssemblyRef.vbs: the host exports fab +' texts and component footprints, the portable exe computes the plan, and the +' host applies it inside one undoable transaction. + +Dim DxToolsHome + +Sub DxToolsInstallExpeditionMenu() + Dim menuBar + Dim existing + Dim button + Dim i + Dim caption + + DxToolsHome = DxEpResolveRoot() + If DxToolsHome = "" Then + MsgBox "DxDesignerTools.exe not found next to this script.", _ + vbExclamation + Exit Sub + End If + + caption = "Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) + Set menuBar = CommandBars("Document Menu Bar") + For i = menuBar.Controls.Count To 1 Step -1 + Set existing = menuBar.Controls.Item(i) + If existing.Caption = caption Then + On Error Resume Next + existing.Delete + Err.Clear + On Error GoTo 0 + End If + Next + + Set DxExpeditionMenu = menuBar.Controls.Add(10) ' cmdControlPopup + DxExpeditionMenu.Caption = caption + + Set button = DxExpeditionMenu.Controls.Add + button.Caption = ChrW(&H81EA) & ChrW(&H52A8) & ChrW(&H8C03) & _ + ChrW(&H6574) & ChrW(&H88C5) & ChrW(&H914D) & ChrW(&H5C42) & _ + ChrW(&H4F4D) & ChrW(&H53F7) + button.OnAction = "DxExpeditionRunAssemblyRefdes" +End Sub + +Sub DxExpeditionRunAssemblyRefdes() + Dim app + Dim docObj + Dim requestText + Dim planText + Dim planPath + Dim requestPath + Dim fso + Dim shell + + Set app = Application + Set docObj = DxEpGetLicensedDoc(app) + If docObj Is Nothing Then Exit Sub + + Set fso = CreateObject("Scripting.FileSystemObject") + Set shell = CreateObject("WScript.Shell") + requestPath = shell.ExpandEnvironmentStrings( _ + "%TEMP%\dx-assembly-request.txt") + planPath = shell.ExpandEnvironmentStrings("%TEMP%\dx-assembly-plan.txt") + + requestText = DxEpExportRequest(docObj) + Call DxEpWriteAscii(requestPath, requestText) + + Dim exec + Dim commandLine + commandLine = DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _ + " compute assembly-refdes --request " & DxToolsQuote(requestPath) & _ + " --output " & DxToolsQuote(planPath) + On Error Resume Next + Set exec = shell.Exec(commandLine) + If Err.Number <> 0 Then + Err.Clear + On Error GoTo 0 + MsgBox "Cannot run DxDesignerTools.exe", vbExclamation + Exit Sub + End If + Do While exec.Status = 0 + Call DxEpSleep(50) + Loop + On Error GoTo 0 + If fso.FileExists(planPath) Then + planText = DxEpReadAscii(planPath) + Else + planText = "" + End If + + Call DxEpApplyPlan(docObj, app, planText) +End Sub + +Function DxEpExportRequest(docObj) + Dim fabtxts + Dim fabtxt + Dim lines + Dim textIndex + Dim componentLines + Dim places + Dim place + Dim pa + Dim dx + Dim dy + Dim sorted + Dim x + Dim y + Dim temp + Dim spans + Dim componentKey + Dim orientation + Dim hasComponent + + Set spans = CreateObject("Scripting.Dictionary") + lines = "" + componentLines = "" + textIndex = 0 + Set fabtxts = docObj.FabricationLayerTexts( _ + epcbFabAll, epcbSelectAll, epcbSideTopOrBottom, True) + + For Each fabtxt In fabtxts + componentKey = "" + orientation = "" + hasComponent = False + On Error Resume Next + If Not fabtxt.Component Is Nothing Then + hasComponent = True + componentKey = CStr(fabtxt.Component.Name) + If Err.Number <> 0 Then + Err.Clear + componentKey = "" + End If + orientation = CStr(fabtxt.Component.Orientation) + If Err.Number <> 0 Then + Err.Clear + orientation = "" + End If + If componentKey <> "" And Not spans.Exists(componentKey) Then + fabtxt.Component.Selected = True + Err.Clear + Set places = docObj.PlacementOutlines(epcbSelectSelected) + If Err.Number <> 0 Then + Err.Clear + Set places = Nothing + End If + dx = 0 + dy = 0 + If Not places Is Nothing Then + For Each place In places + pa = place.Geometry.Outline + sorted = False + Do While Not sorted + sorted = True + For x = 0 To UBound(pa, 2) - 1 + If pa(0, x) > pa(0, x + 1) Then + temp = pa(0, x + 1) + pa(0, x + 1) = pa(0, x) + pa(0, x) = temp + sorted = False + End If + Next + Loop + dx = (pa(0, UBound(pa, 2)) - pa(0, 0)) / 2 + sorted = False + Do While Not sorted + sorted = True + For y = 0 To UBound(pa, 2) - 1 + If pa(1, y) > pa(1, y + 1) Then + temp = pa(1, y + 1) + pa(1, y + 1) = pa(1, y) + pa(1, y) = temp + sorted = False + End If + Next + Loop + dy = (pa(1, UBound(pa, 2)) - pa(1, 0)) / 2 + Next + End If + fabtxt.Component.Selected = False + Err.Clear + If componentLines <> "" Then componentLines = _ + componentLines & vbCrLf + componentLines = componentLines & "C|" & componentKey & _ + "|" & CStr(fabtxt.Component.PositionX) & "|" & _ + CStr(fabtxt.Component.PositionY) & "|" & _ + CStr(dx) & "|" & CStr(dy) + If Err.Number <> 0 Then Err.Clear + spans.Add componentKey, True + End If + End If + Err.Clear + On Error GoTo 0 + + If lines <> "" Then lines = lines & vbCrLf + lines = lines & "T|" & textIndex & _ + "|" & CStr(fabtxt.TextType) & _ + "|" & CStr(fabtxt.Side) & _ + "|" & IIf(fabtxt.Type = epcbFabAssembly, "1", "0") & _ + "|" & fabtxt.TextString & _ + "|" & orientation & _ + "|" & componentKey + textIndex = textIndex + 1 + Next + DxEpExportRequest = lines & vbCrLf & componentLines & vbCrLf +End Function + +Sub DxEpApplyPlan(docObj, app, planText) + Dim fabtxts + Dim fabtxt + Dim index + Dim lines + Dim line + Dim parts + Dim planLines + + Set planLines = CreateObject("Scripting.Dictionary") + lines = Split(Replace(CStr(planText), vbCr, ""), vbLf) + For Each line In lines + If Len(line) > 0 Then + parts = Split(line, "|") + If UBound(parts) >= 1 Then + If Not planLines.Exists(CStr(parts(1))) Then + planLines.Add CStr(parts(1)), line + End If + End If + End If + Next + + docObj.TransactionStart (epcbDRCModeDRC) + app.LockServer + index = 0 + Set fabtxts = docObj.FabricationLayerTexts( _ + epcbFabAll, epcbSelectAll, epcbSideTopOrBottom, True) + For Each fabtxt In fabtxts + If planLines.Exists(CStr(index)) Then + Call DxEpApplyLine(planLines(CStr(index)), fabtxt) + End If + index = index + 1 + Next + app.UnlockServer + docObj.TransactionEnd (True) +End Sub + +Sub DxEpApplyLine(line, fabtxt) + Dim parts + parts = Split(line, "|") + On Error Resume Next + If parts(0) = "DELETE" Then + fabtxt.Delete() + ElseIf parts(0) = "MOVE" Then + fabtxt.Format.VerticalJust = epcbJustifyVCenter + fabtxt.Format.HorizontalJust = epcbJustifyHCenter + fabtxt.Format.Font = parts(6) + If parts(5) <> "" Then + fabtxt.Format.Height(epcbUnitMM) = CDbl(parts(5)) + End If + fabtxt.Format.Orientation(epcbAngleUnitDegrees) = CDbl(parts(4)) + Call fabtxt.Move(CDbl(parts(2)), CDbl(parts(3))) + End If + Err.Clear + On Error GoTo 0 +End Sub + +Sub DxEpWriteAscii(path, text) + Dim stream + Set stream = CreateObject("Scripting.FileSystemObject"). _ + OpenTextFile(CStr(path), 2, True, 0) + stream.Write CStr(text) + stream.Close +End Sub + +Function DxEpReadAscii(path) + Dim stream + Set stream = CreateObject("Scripting.FileSystemObject"). _ + OpenTextFile(CStr(path), 1, False, 0) + DxEpReadAscii = stream.ReadAll + stream.Close +End Function + +Sub DxEpSleep(milliseconds) + On Error Resume Next + CreateObject("WScript.Shell").Run _ + "%ComSpec% /d /s /c ping -n 1 -w 100 127.0.0.1 > nul", 0, True + Err.Clear + On Error GoTo 0 +End Sub + +Function DxEpResolveRoot() + Dim fso + Dim candidate + Set fso = CreateObject("Scripting.FileSystemObject") + DxEpResolveRoot = "" + On Error Resume Next + candidate = CStr(WScript.ScriptFullName) + If Err.Number <> 0 Then + Err.Clear + candidate = CStr(Scripting.ScriptFullName) + End If + On Error GoTo 0 + If candidate <> "" Then + ' expedition\