feat: add complete yiyezhqiu productivity suite

This commit is contained in:
阿白叔 committed 2026-10-10 17:10:32 +08:00
commit e422ca8b2a
155 files changed
+18959

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
__pycache__/
*.py[cod]
.pytest_cache/
.coverage
htmlcov/
.venv/
venv/
*.egg-info/
build/
dist/
release/
.zcode/
+37
View File
@@ -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 默认排除规则(自定义规则请写在本行下方,不会被同步/恢复改动)-----
# 自定义规则写在下方(本行提示可删除)
@@ -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 <absolute request.json>` 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 <positive integer>` 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
<root>\RefDesBridge.vbs
<root>\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\<UTC timestamp>-<random token>` 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
"<portable root>\DxDesignerTools.exe" ui --request "<run root>\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.
File diff suppressed because it is too large. Load diff
@@ -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 `兼容接入`.
@@ -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.
@@ -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\<run_id>\
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.
@@ -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\\<version>` 临时目录;
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 版本。
+97
View File
@@ -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 属性、错误号/描述、使用的工程夹具、复现步骤、预期结果和实际结果。不得只写“失败”或用模拟测试替代现场证据。
+44
View File
@@ -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` / 诊断输出中记录原因。
@@ -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 工程。
@@ -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` 在真实环境验收;逻辑正确性已由自动化测试覆盖。
@@ -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/` 下仅作行为参考,不再随包发布。
+228
View File
@@ -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
@@ -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
@@ -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
+279
View File
@@ -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
@@ -0,0 +1,2 @@
' DxDesigner 7.9.5 Run-route trampoline. Keep this file ASCII-only.
Call DxToolsProbeExecute("run")
@@ -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|<page> / R|<qty>|<refdes>|<pn>|<desc>|<flags>
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
+373
View File
@@ -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
+495
View File
@@ -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
@@ -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
@@ -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\<script> -> tool root is two levels up
DxEpResolveRoot = fso.GetParentFolderName( _
fso.GetParentFolderName(candidate))
If Not fso.FileExists(fso.BuildPath( _
DxEpResolveRoot, "DxDesignerTools.exe")) Then
DxEpResolveRoot = ""
End If
End If
End Function
Function DxEpGetLicensedDoc(app)
On Error Resume Next
Dim key, licenseServer, licenseToken, docObj
Set DxEpGetLicensedDoc = Nothing
Set docObj = app.ActiveDocument
If Err.Number <> 0 Then
Call app.Gui.StatusBarText( _
"No active document: " & Err.Description, epcbStatusFieldError)
Err.Clear
On Error GoTo 0
Exit Function
End If
key = docObj.Validate(0)
Set licenseServer = CreateObject("MGCPCBAutomationLicensing.Application")
licenseToken = licenseServer.GetToken(key)
Set licenseServer = Nothing
Err.Clear
docObj.Validate (licenseToken)
If Err.Number <> 0 Then
Call app.Gui.StatusBarText( _
"No active document license: " & Err.Description, _
epcbStatusFieldError)
Err.Clear
On Error GoTo 0
Exit Function
End If
Set DxEpGetLicensedDoc = docObj
On Error GoTo 0
End Function
@@ -0,0 +1,28 @@
'This part of the script sets up some menus for Demo Purposes
' It adds a menu as the 8th item to the Sheet Menu Bar
Dim SKY_env
SKY_env= Scripting.GetEnvVariable("SKY_MT")
dim fred
Set sMenu = CommandBars("Sheet Menu Bar").Controls.Add(cmdControlPopup)
sMenu.Caption = "&SKY Tool"
'Add buttons to this menu
Set sButton = sMenu.Controls.Add
sButton.Caption = "Help"
fred = "wte " & SKY_env& "\readme.txt"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "Excel BOM"
fred = "Form " & SKY_env& "\Bom.efm"
sButton.OnAction = fred
@@ -0,0 +1,32 @@
Option Explicit
' Get the application object. It is understodd for internal scripts
Dim pcbApp
Set pcbApp = Application
Dim SKY_env
SKY_env= Scripting.GetEnvVariable("SKY_MT")
' add icon to route menu bar
'Dim cmdBars
'Set cmdBars = Gui.CommandBars
'Dim RteToolBar, RteTBCntls, Btn1
'Set RteToolBar = gui.commandbars("Route")
'Set RteTBCntls = RteToolBar.controls
'Set Btn1 = RteTBCntls.Add(cmdControlButton)
'Btn1.OnAction = "Run " + SKY_env + "\MoveAssemblyRef.vbs"
'Btn1.TooltipText = "Auto Move Assembly RefDesigner"
'Btn1.DescriptionText = "Run script: MoveAssemblyRef.vbs"
'Btn1.BitmapFile = SKY_env + "\Icons\MoveAssemblyRef.bmp"
'add menu
Dim sMenu
Set sMenu = pcbApp.Gui.CommandBars("Document Menu Bar").Controls.Add(cmdControlPopup)
sMenu.Caption = "&SKY Tool"
'Add buttons to this menu
Dim sButton
Set sButton = sMenu.Controls.Add
sButton.Caption = "×Ô¶¯µ÷Õû×°Åä²ãλºÅ"
sButton.OnAction = "Run " + SKY_env + "\MoveAssemblyRef.vbs"
Binary file not shown.

After

Width:  |  Height:  |  Size: 822 B

@@ -0,0 +1,31 @@
@ECHO OFF
IF "%WDIR%" == "" GOTO NOPATH
:YESPATH
@ECHO MENTOR已安装
pushd "%~dp0"
:win
::如果SKY_MT为空,则未安装过,需要增加
IF "%SKY_MT%" == "" GOTO win_add
::不为空,则需要判断是否为当前路径
wmic ENVIRONMENT where "name='SKY_MT'" get VariableValue|findstr /c:"%CD% ">nul&&(GOTO win_pathexist)
::不是当前路径,则需要更新为当前路径
wmic ENVIRONMENT where "name='SKY_MT' and username='<system>'" set VariableValue="%CD%"
ECHO 变量已存在,但路径错误,已更改
GOTO END
:win_pathexist:
ECHO 路径已存在
GOTO END
:win_add
wmic ENVIRONMENT create name="SKY_MT",username="<system>",VariableValue="%CD%"
wmic ENVIRONMENT where "name='WDIR' and username='<system>'" set VariableValue="%WDIR%;%%SKY_MT%%"
GOTO END
:NOPATH
@ECHO MENTOR未安装
GOTO END
:END
wmic ENVIRONMENT where "name='WDIR'" get VariableValue
wmic ENVIRONMENT where "name='SKY_MT'" get VariableValue
PAUSE
@@ -0,0 +1,249 @@
' ====================================================================
' This program looks at all of the silkcreen and assembly reference designators and
' changes any that are at 180 to 0 and at 270 to 90 and put them to the origin.
'
' This code is based on MoveAssemblyRef.vbs that is part of AATK 4.0
' from Mentor Graphics
'
' Author: wuyongqing
' Date : 2013.10.29
' ====================================================================
'
'Option Explicit
'
' The example below demonstrates the element manipulations
' on a fabrication layer text.
' It moves all the assembly text to the origin and changes the height and orientation
' ====================================================================
main
Sub main()
' On Error Resume Next
Dim app 'As FablinkXEApplication ' MGCPCB.Application
Set app = Application
'Set app = GetObject(, "MGCPCB.FablinkXEApplication") '(, "MGCPCB.Application")
Dim docObj 'As MGCPCB.Document
Dim fabtxts 'As FabricationLayerTexts
Dim fabtxt 'As FabricationLayerText
Dim cnt, ori, dx, dy, pa, x, y, z, sorted, TheArray, Temp, n
Dim place 'As PlacementOutline
Dim places 'As PlacementOutlines
Dim MAXHEIGHT
MAXHEIGHT = 0.8
' collect document object
Set docObj = GetLicensedDoc(app)
If (docObj Is Nothing) Then Exit Sub
Dim size
Set fabtxts = docObj.FabricationLayerTexts(epcbFabAll, epcbSelectAll, epcbSideTopOrBottom, True) 'get a selection of all the fab layer texts
cnt = fabtxts.Count
Call app.Gui.ProgressBarInitialize(True, "Progess", cnt, 0) 'initialize the progress bar from o to cnt
cnt = 0
docObj.TransactionStart (epcbDRCModeDRC) ' make all the moves one single undable action
app.LockServer 'speed up the process by locking the server
For Each fabtxt In fabtxts 'walk through all the fabrication layer texts
If Not fabtxt.Component Is Nothing Then 'if it is not text belonging to a component throw it out. Like board level texts.
If fabtxt.TextType = 1 Then 'only 'epcbTextRefDes(1)' Type, Others will delete
fabtxt.Component.Selected = True 'select the component
'Call docObj.ActiveView.SetExtentsToSelection(False, True) 'zoom into the component
Set places = docObj.PlacementOutlines(epcbSelectSelected)
'docObj.ActiveView.SetExtentsToSelection
For Each place In places ' find the outside of the component to move the silkscreen text to
'pa = place.Geometry.PointsArray
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
ori = fabtxt.Component.Orientation
fabtxt.Format.VerticalJust = epcbJustifyVCenter
fabtxt.Format.HorizontalJust = epcbJustifyHCenter
n = Len(fabtxt.TextString)
If n < 5 Then
'MsgBox fabtxt.TextString & vbCrLf & fabtxt.TextType & vbCrLf & fabtxt.Format.VerticalJust
'fabtxt.Format.AspectRatio = 1
fabtxt.Format.Font = "Arial"
'fabtxt.Format.Height = 0.42
ElseIf n < 6 Then
fabtxt.Format.Font = "Arial Narrow"
'fabtxt.Format.Height = 0.42
Else
fabtxt.Format.Font = "Arial Narrow"
fabtxt.Format.Height = 0.35
End If
'if n > 3 then'fabtxt.TextString = "CT26" Then
' MsgBox "dx="&dx & "dy="&dy&vbCrLf & "x,y=" &fabtxt.Component.PositionX &","& fabtxt.Component.PositionY&vbCrLf &pa(0, UBound(pa, 2))&","&pa(0,0)&"y="&pa(1, UBound(pa, 2))&","&pa(1,0) &", UBound="& UBound(pa, 2)&",side="&fabtxt.Side
'end if
If ori = 0 Or ori = 180 Then
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = 0 'if the text is rotated at 0 or 180 make it 0
If fabtxt.Type = epcbFabAssembly Then
if dy < 0.1 Or dy > MAXHEIGHT Then
dy = MAXHEIGHT
end if
fabtxt.Format.Height(epcbUnitMM) = dy
'fabtxt.Format.Penwidth(epcbUnitMM) = qing
sss = fabtxt.Component.PositionX 'PositionX(epcbUnitMM)
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY)' + dy)', epcbUnitMils)
End If
ElseIf ori = 90 Or ori = 270 Then
If fabtxt.Side = 1 Then 'On Top layer
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = 90
Else
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = 270
End If
If fabtxt.Type = epcbFabAssembly Then
if dx < 0.1 Or dx > MAXHEIGHT Then
dx = MAXHEIGHT
end if
fabtxt.Format.Height(epcbUnitMM) = dx
'fabtxt.Format.Penwidth(epcbUnitMM) = qing
'Call fabtxt.Move(fabtxt.Component.PositionX + dx, fabtxt.Component.PositionY)', epcbUnitMils)
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY) ', epcbUnitMils)
End If
ElseIf ori = 45 Or ori = 225 Then
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = 45
If fabtxt.Type = epcbFabAssembly Then
dx = (pa(0, UBound(pa, 2)) - pa(0, 0)) * 0.54 / 2
if dx < 0.1 Or dx > MAXHEIGHT Then
dx = MAXHEIGHT
end if
fabtxt.Format.Height(epcbUnitMM) = dx
'fabtxt.Format.Penwidth(epcbUnitMM) = qing
'Call fabtxt.Move(fabtxt.Component.PositionX + dx, fabtxt.Component.PositionY)', epcbUnitMils)
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY) ', epcbUnitMils)
End If
ElseIf ori = 135 Or ori = 315 Then
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = 315
If fabtxt.Type = epcbFabAssembly Then
dx = (pa(0, UBound(pa, 2)) - pa(0, 0)) * 0.54 / 2
if dx < 0.1 Or dx > MAXHEIGHT Then
dx = MAXHEIGHT
end if
fabtxt.Format.Height(epcbUnitMM) = dx
'fabtxt.Format.Penwidth(epcbUnitMM) = qing
'Call fabtxt.Move(fabtxt.Component.PositionX + dx, fabtxt.Component.PositionY)', epcbUnitMils)
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY) ', epcbUnitMils)
End If
ElseIf ori > 90 And ori < 270 Then
fabtxt.Format.Height(epcbUnitMM) = 0.4
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = ori + 180
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY)
Else
fabtxt.Format.Height(epcbUnitMM) = 0.4
fabtxt.Format.Orientation(epcbAngleUnitDegrees) = ori
Call fabtxt.Move(fabtxt.Component.PositionX, fabtxt.Component.PositionY)
End If
app.Gui.ProgressBar (cnt)
cnt = cnt + 1
fabtxt.Component.Selected = False
Else
fabtxt.Delete()
End If
End If
Next
app.UnlockServer 'unlock the server
docObj.TransactionEnd (True) 'end the make it all one undo
app.Gui.ProgressBarInitialize (False)
End Sub
'
' This function retrieves an automation license for a document
'
' Returns:
' - 'Nothing' if licensing failed .
' - A reference to the active document of the application if
' licensing succeeded.
'
Public Function GetLicensedDoc(app)
On Error Resume Next
Dim key, licenseServer, licenseToken, docObj
Set GetLicensedDoc = Nothing
' collect the active document
Set docObj = app.ActiveDocument
If (Err) Then
Call app.Gui.StatusBarText("No active document: " + Err.Description, epcbStatusFieldError)
Exit Function
End If
' Ask Expedition’s document for the key
key = docObj.Validate(0)
' Get token from license server
Set licenseServer = CreateObject("MGCPCBAutomationLicensing.Application")
licenseToken = licenseServer.GetToken(key)
Set licenseServer = Nothing
' Ask the document to validate the license token
Err.Clear
docObj.Validate (licenseToken)
If (Err) Then
Call app.Gui.StatusBarText("No active document license: " + Err.Description, epcbStatusFieldError)
Exit Function
End If
' everything is OK, return document
Set GetLicensedDoc = docObj
End Function
@@ -0,0 +1,42 @@
EE7.9.5 BOM导出工具 20160830
功能描述:
1、支持EE7.9.5 版本 BOM 按页导出到一个xls文件,导出格式可直接粘贴到BOM制作工具中。
2、支持同一页中相同料号和描述的位号自动合并,同一料号不同描述的位号高亮显示。
3、支持料号与描述一致性检查,不一致时料号红色高亮显示。
4、支持描述中带“NC”关键字的物料自动删除,或者高亮显示。
5、支持位号唯一性检查,位号不唯一时位号红色高亮显示。
6、临时料号红色高亮显示。
7、带有“USE”关键字的描述红色高亮显示。
8、MARK、MOUNTHOLE等物料高亮显示。
安装方法:
双击Intall.bat完成安装,Win7及以上版本请右键以管理权限安装。
或者手动添加环境变量完成安装:
1、新建环境变量SKY_MT,值为BOM导出工具的路径。
2、修改WDIR环境变量,在后面增加%SKY_MT%。
使用方法:
打开需要导出BOM的EE7.9工程文件,使用“文件” ---- “打开” ---- “文件” 打开“Open File”
对话框,修改文件类型为“Script Forms(*.efm)”,打开BOM导出工具目录下的BOM.efm文件。
在打开的对话框中点击“ComponentList”按钮,稍等即可自动生成BOM。如果需要删除NC物料,
请勾选“Delete NC component”选项。生成的BOM如需保存,请使用另存为。
注意事项:
1、BOM导出工具及项目工程文件的路径不能包含中文和空格。
2、位号为“Ref Designator”项,料号为“Part Number”项,描述为“VALUE”项。
3、有任何问题请联系 XiongYongZhao@skyworth.com
20160830更新内容:
1、修复BOM导出时错乱的问题。
2、增加料号与描述一致性检查功能,目前支持电阻、电容、电感三类。临时物料、空描述、带有
USE关键字的物料不检查。不匹配时料号单元格底色为黄色高亮。
3、增加位号唯一性检查功能,在导出后的BOM中,同一位号单元格底色为红色高亮。
已知问题:
1、0~10R的电阻,系统中有两种物料编码规则,暂时只支持一种。
2、电阻单位只支持R、K、M,电容只支持P、N、U,电感只支持U、M、H,无单位或者其它单位可能
误报,请反馈。
@@ -0,0 +1,7 @@
;DxDesigner stuff
[Viewdraw]
Script#0=%SKY_MT%/DxMenuAdd.vbs
脚本#0=%SKY_MT%/DxMenuAdd.vbs
[Expedition PCB]
Script#0=%SKY_MT%/ExMenuAdd.vbs
@@ -0,0 +1,76 @@
'This part of the script sets up some menus for Demo Purposes
' It adds a menu as the 9th item to the Sheet Menu Bar
'Dim SKY_env
'SKY_env= Scripting.GetEnvVariable("SKY_MT")
Dim fred
Set sMenu = CommandBars("Sheet Menu Bar").Controls.Add(cmdControlPopup,,,9)
sMenu.Caption = "一叶知秋(&Y)"
'Add buttons to this menu
Set sButton = sMenu.Controls.Add
sButton.Caption = "孤立网络检查(&G)"
fred = "Form " & "D:\NET_CHECK\NET-solitary.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "网络跨页互动(&K)"
fred = "Form " & "D:\NET_CHECK\NET-interactive.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "全部网络列表(&N)"
fred = "Form " & "D:\NET_CHECK\NET-List.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "位号批量命名(&W)"
fred = "Form " & "D:\NET_CHECK\PART_Ref_CHA.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "Value批量修改(&V)"
fred = "Form " & "D:\NET_CHECK\PART_Value_CHA.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "Value1批量修改(&V1)"
fred = "Form " & "D:\NET_CHECK\PART_Value1_CHA.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "BOM导出(&B)"
fred = "Form " & "D:\NET_CHECK\BOM_output\Bom.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "物料编号修改(&W)"
fred = "Form " & "D:\NET_CHECK\PART_PartNumber_CHA.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "PartName批量隐藏(&P)"
fred = "Form " & "D:\NET_CHECK\PartName_Hide.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "PartLabel批量隐藏(&L)"
fred = "Form " & "D:\NET_CHECK\PartLabel_Hide.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "Value值遗漏查找(&VY)"
fred = "Form " & "D:\NET_CHECK\Value_Check_Miss.efm"
sButton.OnAction = fred
Set sButton = sMenu.Controls.Add
sButton.Caption = "Value1值遗漏查找(&V1Y)"
fred = "Form " & "D:\NET_CHECK\Value1_Check_Miss.efm"
sButton.OnAction = fred
Binary file not shown.
+57
View File
@@ -0,0 +1,57 @@
# -*- mode: python ; coding: utf-8 -*-
from pathlib import Path
from PyInstaller.utils.hooks import collect_data_files, collect_submodules
ROOT = Path(SPEC).resolve().parent.parent
hiddenimports = (
collect_submodules("dx_productivity")
+ collect_submodules("qtawesome")
+ collect_submodules("cryptography")
)
datas = collect_data_files("qtawesome")
a = Analysis(
[str(ROOT / "src" / "dx_productivity" / "bridge" / "launcher.py")],
pathex=[str(ROOT / "src")],
binaries=[],
datas=datas,
hiddenimports=hiddenimports,
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="DxDesignerTools",
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
contents_directory="_runtime",
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name="DxDesignerTools",
)
+162
View File
@@ -0,0 +1,162 @@
[CmdletBinding()]
param()
$ErrorActionPreference = "Stop"
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$buildRoot = Join-Path $repoRoot "build\pyinstaller"
$distRoot = Join-Path $repoRoot "dist\DxDesignerTools"
$releaseBase = Join-Path $repoRoot "release"
$releaseRoot = Join-Path $releaseBase "DxDesigner效率工具"
$archivePath = Join-Path $releaseBase "DxDesigner效率工具_Win11_x64.zip"
$manifestPath = Join-Path $releaseBase "SHA256SUMS.txt"
$versionFile = Join-Path $releaseRoot "version.json"
$updateManifestFile = Join-Path $releaseRoot "update-manifest.template.json"
function Assert-RepositoryChild {
param([Parameter(Mandatory = $true)][string]$Path)
$fullPath = [IO.Path]::GetFullPath($Path)
$fullRoot = [IO.Path]::GetFullPath($repoRoot).TrimEnd('\') + '\'
if (-not $fullPath.StartsWith($fullRoot, [StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to modify path outside repository: $fullPath"
}
}
foreach ($path in @($buildRoot, $distRoot, $releaseRoot, $archivePath, $manifestPath)) {
Assert-RepositoryChild -Path $path
}
$pythonInfo = & py -3.12 -c "import struct,sys; print(str(sys.version_info.major)+'.'+str(sys.version_info.minor)+'|'+str(struct.calcsize('P')*8))"
if ($LASTEXITCODE -ne 0 -or $pythonInfo.Trim() -ne "3.12|64") {
throw "Build requires 64-bit Python 3.12."
}
$pythonExe = (& py -3.12 -c "import sys; print(sys.executable)").Trim()
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $pythonExe -PathType Leaf)) {
throw "Could not resolve the Python 3.12 executable."
}
& $pythonExe -c "import PyInstaller, PySide6, qtawesome"
if ($LASTEXITCODE -ne 0) {
throw "Build dependencies are missing. Install the project build extras before running this script."
}
foreach ($path in @($buildRoot, $distRoot, $releaseRoot)) {
if (Test-Path -LiteralPath $path) {
Remove-Item -LiteralPath $path -Recurse -Force
}
}
foreach ($path in @($archivePath, $manifestPath)) {
if (Test-Path -LiteralPath $path) {
Remove-Item -LiteralPath $path -Force
}
}
New-Item -ItemType Directory -Path $releaseBase -Force | Out-Null
$pyInstallerArgs = @(
"-m", "PyInstaller", "--noconfirm", "--clean",
"--workpath", $buildRoot,
"--distpath", (Split-Path -Parent $distRoot),
(Join-Path $PSScriptRoot "DxDesignerTools.spec")
)
$pythonRoot = Split-Path -Parent $pythonExe
$windowsRoot = if ([string]::IsNullOrWhiteSpace($env:WINDIR)) { "C:\Windows" } else { $env:WINDIR }
$buildPath = @(
$pythonRoot,
(Join-Path $pythonRoot "Scripts"),
(Join-Path $windowsRoot "System32"),
$windowsRoot,
(Join-Path $windowsRoot "System32\Wbem")
) -join ";"
$originalPath = $env:PATH
try {
$env:PATH = $buildPath
& $pythonExe @pyInstallerArgs
if ($LASTEXITCODE -ne 0) {
throw "PyInstaller build failed."
}
}
finally {
$env:PATH = $originalPath
}
Copy-Item -LiteralPath $distRoot -Destination $releaseRoot -Recurse
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\MenuAdd.vbs") -Destination (Join-Path $releaseRoot "MenuAdd.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\DesignBridge.vbs") -Destination (Join-Path $releaseRoot "DesignBridge.vbs")
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\CompatibilityProbe.vbs") -Destination (Join-Path $releaseRoot "CompatibilityProbe.vbs")
$runtimeVbs = Join-Path $releaseRoot "_runtime\vbs"
New-Item -ItemType Directory -Path $runtimeVbs -Force | Out-Null
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\BridgeCommon.vbs") -Destination (Join-Path $runtimeVbs "BridgeCommon.vbs")
$coreSource = Join-Path $repoRoot "integration\dxdesigner795\core"
New-Item -ItemType Directory -Path $runtimeVbs -Force | Out-Null
Copy-Item -Path (Join-Path $coreSource "*.vbs") -Destination $runtimeVbs
$expeditionRoot = Join-Path $releaseRoot "expedition"
New-Item -ItemType Directory -Path $expeditionRoot -Force | Out-Null
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\expedition\ExpeditionBridge.vbs") -Destination (Join-Path $expeditionRoot "ExpeditionBridge.vbs")
$templatesRoot = Join-Path $releaseRoot "templates"
New-Item -ItemType Directory -Path $templatesRoot -Force | Out-Null
Copy-Item -LiteralPath (Join-Path $repoRoot "integration\dxdesigner795\templates\BOM模板.xls") -Destination (Join-Path $templatesRoot "BOM模板.xls")
$docsRoot = Join-Path $releaseRoot "docs"
New-Item -ItemType Directory -Path $docsRoot -Force | Out-Null
$guideSource = Join-Path $repoRoot "docs\user\DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx"
$guideDestination = Join-Path $docsRoot "DxDesigner_7.9.5_自动位号工具使用说明.docx"
Copy-Item -LiteralPath $guideSource -Destination $guideDestination
$env:PYTHONPATH = Join-Path $repoRoot "src"
$productVersion = (& $pythonExe -c "import dx_productivity; print(dx_productivity.__version__)").Trim()
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($productVersion)) {
throw "Could not read dx_productivity.__version__ from the source tree."
}
Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue
$versionPayload = [ordered]@{
product = "yiyezhqiu-refactored"
display_name = "一叶知秋_重构版"
version = $productVersion
}
[IO.File]::WriteAllText($versionFile, ($versionPayload | ConvertTo-Json), [Text.UTF8Encoding]::new($false))
$updatePayload = [ordered]@{
product = "yiyezhqiu-refactored"
version = $productVersion
channel = "stable"
min_supported_version = "0.1.0"
package_url = ""
sha256 = ""
release_notes = ""
published_at = (Get-Date).ToUniversalTime().ToString("yyyy-MM-dd")
signature = ""
}
[IO.File]::WriteAllText($updateManifestFile, ($updatePayload | ConvertTo-Json), [Text.UTF8Encoding]::new($false))
$expected = @(
(Join-Path $releaseRoot "DxDesignerTools.exe"),
(Join-Path $releaseRoot "_runtime\python312.dll"),
(Join-Path $releaseRoot "MenuAdd.vbs"),
(Join-Path $releaseRoot "DesignBridge.vbs"),
(Join-Path $releaseRoot "CompatibilityProbe.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\BridgeCommon.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\Snapshot.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\Transaction.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\Mailbox.vbs"),
(Join-Path $releaseRoot "_runtime\vbs\BomExport.vbs"),
(Join-Path $releaseRoot "templates\BOM模板.xls"),
(Join-Path $releaseRoot "expedition\ExpeditionBridge.vbs"),
(Join-Path $docsRoot "DxDesigner_7.9.5_自动位号工具使用说明.docx"),
$versionFile,
$updateManifestFile
)
foreach ($path in $expected) {
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
throw "Release file is missing: $path"
}
}
Compress-Archive -LiteralPath $releaseRoot -DestinationPath $archivePath -CompressionLevel Optimal
$archiveHash = (Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash.ToLowerInvariant()
$manifest = "$archiveHash *DxDesigner效率工具_Win11_x64.zip" + [Environment]::NewLine
[IO.File]::WriteAllText($manifestPath, $manifest, [Text.UTF8Encoding]::new($false))
Write-Output "RELEASE_ROOT=$releaseRoot"
Write-Output "ARCHIVE=$archivePath"
Write-Output "SHA256=$archiveHash"
+52
View File
@@ -0,0 +1,52 @@
"""Sign a release archive and produce the manifest signature field.
Workflow (offline, on the machine holding the private key):
python packaging/sign_manifest.py --package dist/Bx.zip \
--key ..\\signing\\yiyezhqiu-release-private-key.pem
Prints the base64 Ed25519 signature over the archive bytes. Paste it into
``update-manifest.template.json``'s ``signature`` field (stable channel
manifests must carry it; the client refuses unsigned stable updates).
NEVER copy the private key into the repository or the release package.
"""
from __future__ import annotations
import argparse
import base64
import sys
from pathlib import Path
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Sign an update archive")
parser.add_argument("--package", type=Path, required=True)
parser.add_argument("--key", type=Path, required=True)
return parser
def main(argv: list[str] | None = None) -> int:
options = build_parser().parse_args(argv)
try:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
Ed25519PrivateKey,
)
except ImportError:
print("cryptography is required: pip install cryptography", file=sys.stderr)
return 2
key_pem = options.key.read_bytes()
private_key = serialization.load_pem_private_key(key_pem, password=None)
if not isinstance(private_key, Ed25519PrivateKey):
print("the key file is not an Ed25519 private key", file=sys.stderr)
return 2
signature = private_key.sign(options.package.read_bytes())
print(base64.b64encode(signature).decode("ascii"))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+35
View File
@@ -0,0 +1,35 @@
[build-system]
requires = ["setuptools>=75"]
build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "0.1.0"
description = "Productivity tools for DxDesigner 7.9.5"
requires-python = ">=3.12,<3.13"
dependencies = [
"PySide6-Essentials>=6.7,<7",
"qtawesome>=1.3,<2",
"cryptography>=42,<46",
]
[project.optional-dependencies]
dev = [
"build>=1.2,<2",
"coverage>=7,<8",
"pytest>=8,<9",
"pytest-qt>=4.4,<5",
]
build-release = [
"pyinstaller>=6.11,<7",
]
[project.scripts]
dx-productivity = "dx_productivity.ui.app:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra"
+6
View File
@@ -0,0 +1,6 @@
"""DxDesigner 7.9.5 productivity suite."""
__version__ = "0.1.0"
PRODUCT_ID = "yiyezhqiu-refactored"
DISPLAY_NAME = "一叶知秋_重构版"
+5
View File
@@ -0,0 +1,5 @@
from dx_productivity.bridge.launcher import main
if __name__ == "__main__":
raise SystemExit(main())
+1
View File
@@ -0,0 +1 @@
"""File-based bridge helpers for the DxDesigner scripting host."""
@@ -0,0 +1,73 @@
"""Headless compute host: pure calculation commands with no Qt dependency."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Sequence
from dx_productivity.features.assembly_refdes.planner import (
ComponentFootprint,
FabricationText,
plan_assembly_refdes,
render_plan,
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Headless compute commands")
sub = parser.add_subparsers(dest="command", required=True)
assembly = sub.add_parser(
"assembly-refdes",
help="Compute the assembly refdes move plan for Expedition PCB",
)
assembly.add_argument("--request", type=Path, required=True)
assembly.add_argument("--output", type=Path, required=True)
return parser
def run_assembly_refdes(request_path: Path, output_path: Path) -> int:
texts: list[FabricationText] = []
footprints: dict[str, ComponentFootprint] = {}
for line in request_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
fields = line.split("|")
if fields[0] == "T" and len(fields) >= 8:
texts.append(
FabricationText(
index=int(fields[1]),
text_type=int(fields[2]),
side=int(fields[3]),
is_assembly=fields[4] == "1",
text_string=fields[5],
orientation=float(fields[6]) if fields[6] else 0.0,
component_name=fields[7] if len(fields) > 7 else "",
)
)
elif fields[0] == "C" and len(fields) >= 6:
footprint = ComponentFootprint(
name=fields[1],
pos_x=float(fields[2]),
pos_y=float(fields[3]),
x_half_span=float(fields[4]),
y_half_span=float(fields[5]),
)
footprints[footprint.name] = footprint
plans, _processed = plan_assembly_refdes(texts, footprints)
output_path.write_text(render_plan(plans), encoding="ascii")
return 0
def main(argv: Sequence[str] | None = None) -> int:
options = build_parser().parse_args(argv)
if options.command == "assembly-refdes":
return run_assembly_refdes(options.request, options.output)
return 2
if __name__ == "__main__":
raise SystemExit(main())
+46
View File
@@ -0,0 +1,46 @@
"""Dispatch the packaged executable without loading Qt for probe runs."""
from __future__ import annotations
import sys
from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
arguments = list(sys.argv[1:] if argv is None else argv)
if arguments and arguments[0] == "probe":
from dx_productivity.bridge.probe_host import main as probe_main
return probe_main(arguments[1:])
if arguments and arguments[0] == "compute":
from dx_productivity.bridge.compute_host import main as compute_main
return compute_main(arguments[1:])
if arguments and arguments[0] == "update":
import argparse
import json
from pathlib import Path
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
parser = argparse.ArgumentParser(prog="DxDesignerTools update")
parser.add_argument("--plan", required=True, type=Path)
options = parser.parse_args(arguments[1:])
plan = InstallPlan.from_mapping(
json.loads(options.plan.read_text(encoding="utf-8"))
)
result = UpdateInstaller().install(plan)
return 0 if result.state == "installed" else 1
if arguments and arguments[0] == "ui":
arguments = arguments[1:]
from dx_productivity.ui.app import main as ui_main
return ui_main(arguments)
if __name__ == "__main__":
raise SystemExit(main())
+52
View File
@@ -0,0 +1,52 @@
"""Write deterministic compatibility results from the DxDesigner probe."""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
from typing import Sequence
from dx_productivity.bridge.protocol import atomic_write_text
PROBE_ROUTES = ("named", "run", "form")
def write_probe_marker(
output_path: Path, route: str, payload: dict[str, object]
) -> None:
"""Write one versioned result consumed by the installer and live checklist."""
data = {"format_version": 1, "route": route, **payload}
output_path.parent.mkdir(parents=True, exist_ok=True)
atomic_write_text(
output_path,
json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\n",
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Record DxDesigner probe results")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--route", choices=PROBE_ROUTES, required=True)
parser.add_argument("--payload-json", required=True)
parser.add_argument("--hold-seconds", type=float, default=0.0)
return parser
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")
if args.hold_seconds < 0:
raise ValueError("hold seconds must not be negative")
if args.hold_seconds:
time.sleep(args.hold_seconds)
write_probe_marker(args.output, args.route, payload)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+395
View File
@@ -0,0 +1,395 @@
"""Strict versioned JSON and TSV bridge protocol (format version 2)."""
from __future__ import annotations
import json
import hashlib
import re
import tempfile
from collections import Counter
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
from dx_productivity.domain.models import (
ApplyStatus,
ApplyStep,
ApplyRequest,
AttributeRecord,
ComponentRecord,
DesignSnapshot,
NetRecord,
OpType,
)
FORMAT_VERSION = 2
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
SCHEDULE_COLUMNS = 7
OP_VALUES = frozenset(item.value for item in OpType)
class ProtocolError(ValueError):
"""Raised when bridge input violates the versioned contract."""
def load_request(path: Path) -> DesignSnapshot:
data = _load_json_object(path)
_require_version(data)
raw_components = data.get("components")
if not isinstance(raw_components, list):
raise ProtocolError("components must be an array")
components = tuple(
_parse_component(item, index) for index, item in enumerate(raw_components)
)
bridge_ids = [component.bridge_id for component in components]
if len(bridge_ids) != len(set(bridge_ids)):
raise ProtocolError("duplicate bridge_id in request")
nets = _parse_nets(data)
selected_nets = _parse_selected_nets(data)
return DesignSnapshot(
format_version=FORMAT_VERSION,
run_id=_require_nonempty_str(data, "run_id"),
snapshot_id=_require_nonempty_str(data, "snapshot_id"),
design_id=_require_nonempty_str(data, "design_id"),
design_path=_require_str(data, "design_path"),
components=components,
nets=nets,
selected_nets=selected_nets,
)
def _parse_nets(data: dict[str, Any]) -> tuple[NetRecord, ...]:
raw_nets = data.get("nets")
if raw_nets is None:
return ()
if not isinstance(raw_nets, list):
raise ProtocolError("nets must be an array")
nets: list[NetRecord] = []
seen: set[str] = set()
for index, item in enumerate(raw_nets):
if not isinstance(item, dict):
raise ProtocolError(f"nets[{index}] must be an object")
name = _require_str(item, "name")
if not name.strip():
raise ProtocolError(f"nets[{index}].name must not be empty")
if name.casefold() in seen:
raise ProtocolError(f"duplicate net name: {name}")
seen.add(name.casefold())
raw_pages = item.get("pages")
if not isinstance(raw_pages, list) or any(
type(page) is not int or page < 0 for page in raw_pages
):
raise ProtocolError(f"nets[{index}].pages must be an integer array")
nets.append(NetRecord(name=name, pages=tuple(raw_pages)))
return tuple(nets)
def _parse_selected_nets(data: dict[str, Any]) -> tuple[str, ...]:
raw_selected = data.get("selected_nets")
if raw_selected is None:
return ()
if not isinstance(raw_selected, list) or any(
not isinstance(item, str) for item in raw_selected
):
raise ProtocolError("selected_nets must be a string array")
return tuple(raw_selected)
def write_schedule(path: Path, schedule: tuple[ApplyStep, ...]) -> None:
atomic_write_text(path, _schedule_text(schedule))
def schedule_sha256(schedule: tuple[ApplyStep, ...]) -> str:
return hashlib.sha256(_schedule_text(schedule).encode("utf-8")).hexdigest()
def write_apply_request(path: Path, request: ApplyRequest) -> None:
_validate_apply_request(request)
payload = {
"format_version": request.format_version,
"run_id": request.run_id,
"snapshot_id": request.snapshot_id,
"backup_path": str(request.backup_path),
"schedule_sha256": request.schedule_sha256,
}
atomic_write_text(
path,
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
)
def load_apply_request(path: Path) -> ApplyRequest:
data = _load_json_object(path)
_require_version(data)
request = ApplyRequest(
format_version=FORMAT_VERSION,
run_id=_require_nonempty_str(data, "run_id"),
snapshot_id=_require_nonempty_str(data, "snapshot_id"),
backup_path=Path(_require_nonempty_str(data, "backup_path")),
schedule_sha256=_require_nonempty_str(data, "schedule_sha256"),
)
_validate_apply_request(request)
return request
def _validate_apply_request(request: ApplyRequest) -> None:
if request.format_version != FORMAT_VERSION:
raise ProtocolError(
f"unsupported format_version: {request.format_version!r}"
)
if not request.run_id.strip() or not request.snapshot_id.strip():
raise ProtocolError("apply request IDs must not be empty")
if not request.backup_path.is_absolute():
raise ProtocolError("backup_path must be absolute")
if SHA256_RE.fullmatch(request.schedule_sha256) is None:
raise ProtocolError("schedule_sha256 must be lowercase SHA-256")
def _schedule_text(schedule: tuple[ApplyStep, ...]) -> str:
expected_sequences = list(range(1, len(schedule) + 1))
actual_sequences = [step.sequence for step in schedule]
if actual_sequences != expected_sequences:
raise ProtocolError("schedule sequence must be contiguous from 1")
counts: Counter[str] = Counter(step.target_key for step in schedule)
if any(count > 2 for count in counts.values()):
raise ProtocolError("one operation target may appear at most twice")
rows: list[str] = []
for step in schedule:
if step.op not in OpType:
raise ProtocolError(f"schedule op is invalid: {step.op!r}")
if step.op is not OpType.REFDES and not step.property_name.strip():
raise ProtocolError("property schedules must carry a property name")
fields = (
str(step.sequence),
step.op.value,
step.bridge_id,
step.property_name,
step.expected_refdes,
step.new_refdes,
step.final_refdes,
)
if any(any(char in field for char in "\t\r\n") for field in fields):
raise ProtocolError("schedule fields must not contain tabs or line breaks")
if not step.bridge_id:
raise ProtocolError("schedule bridge_id must not be empty")
rows.append("\t".join(fields))
return "".join(f"{row}\n" for row in rows)
def parse_schedule_text(text: str) -> tuple[ApplyStep, ...]:
"""Parse the 7-column schedule TSV (used by tests and restore tooling)."""
steps: list[ApplyStep] = []
for line in text.splitlines():
if not line.strip():
continue
fields = line.split("\t")
if len(fields) != SCHEDULE_COLUMNS:
raise ProtocolError("schedule row must have 7 columns")
try:
sequence = int(fields[0])
except ValueError as exc:
raise ProtocolError("schedule sequence must be an integer") from exc
if fields[1] not in OP_VALUES:
raise ProtocolError(f"schedule op is invalid: {fields[1]!r}")
steps.append(
ApplyStep(
sequence=sequence,
op=OpType(fields[1]),
bridge_id=fields[2],
property_name=fields[3],
expected_refdes=fields[4],
new_refdes=fields[5],
final_refdes=fields[6],
)
)
return tuple(steps)
def load_apply_status(path: Path) -> ApplyStatus:
data = _load_json_object(path)
_require_version(data)
changed_count = _require_int(data, "changed_count")
if changed_count < 0:
raise ProtocolError("changed_count must not be negative")
backup_value = data.get("backup_path")
if backup_value is not None and not isinstance(backup_value, str):
raise ProtocolError("backup_path must be a string or null")
failing_sequence = data.get("failing_sequence")
if failing_sequence is not None and type(failing_sequence) is not int:
raise ProtocolError("failing_sequence must be an integer or null")
return ApplyStatus(
format_version=FORMAT_VERSION,
run_id=_require_nonempty_str(data, "run_id"),
state=_require_nonempty_str(data, "state"),
changed_count=changed_count,
backup_path=Path(backup_value) if backup_value else None,
failing_sequence=failing_sequence,
error=_optional_str(data, "error"),
rollback_state=_optional_str(data, "rollback_state"),
)
def _parse_component(value: object, index: int) -> ComponentRecord:
if not isinstance(value, dict):
raise ProtocolError(f"components[{index}] must be an object")
data: dict[str, Any] = value
stable_uid = _optional_str(data, "stable_uid")
full_path = _require_str(data, "full_path")
if not stable_uid and not full_path:
raise ProtocolError(f"components[{index}] has no stable identity")
sheet_number = data.get("sheet_number")
if sheet_number is not None and type(sheet_number) is not int:
raise ProtocolError(f"components[{index}].sheet_number must be integer or null")
return ComponentRecord(
bridge_id=_require_nonempty_str(data, "bridge_id", index),
stable_uid=stable_uid,
full_path=full_path,
logical_group_key=_require_str(data, "logical_group_key", index),
sheet_name=_require_str(data, "sheet_name", index),
sheet_number=sheet_number,
x=_require_decimal(data, "x", index),
y=_require_decimal(data, "y", index),
y_axis_up=_require_bool(data, "y_axis_up", index),
refdes=_require_str(data, "refdes", index),
symbol_refdes_default=_optional_str(data, "symbol_refdes_default", index),
selected=_require_bool(data, "selected", index),
current_sheet=_require_bool(data, "current_sheet", index),
part_number=_require_str(data, "part_number", index),
value=_require_str(data, "value", index),
locked=_require_bool(data, "locked", index),
attributes=_parse_attributes(data, index),
)
def _parse_attributes(
data: dict[str, Any], index: int
) -> tuple[AttributeRecord, ...]:
raw_attributes = data.get("attributes")
if raw_attributes is None:
return ()
if not isinstance(raw_attributes, list):
raise ProtocolError(f"components[{index}].attributes must be an array")
attributes: list[AttributeRecord] = []
for attribute_index, item in enumerate(raw_attributes):
if not isinstance(item, dict):
raise ProtocolError(
f"components[{index}].attributes[{attribute_index}] must be an object"
)
attributes.append(
AttributeRecord(
name=_require_nonempty_str(item, "name"),
value=_require_str(item, "value"),
visible=_require_bool(item, "visible", attribute_index),
)
)
return tuple(attributes)
def _load_json_object(path: Path) -> dict[str, Any]:
try:
data = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ProtocolError(f"cannot read JSON protocol file: {path}") from exc
if not isinstance(data, dict):
raise ProtocolError("protocol root must be a JSON object")
return data
def _require_version(data: dict[str, Any]) -> None:
if data.get("format_version") != FORMAT_VERSION:
raise ProtocolError(
f"unsupported format_version: {data.get('format_version')!r}"
)
def _field_name(key: str, index: int | None) -> str:
return f"components[{index}].{key}" if index is not None else key
def _require_str(
data: dict[str, Any], key: str, index: int | None = None
) -> str:
value = data.get(key)
if not isinstance(value, str):
raise ProtocolError(f"{_field_name(key, index)} must be a string")
return value
def _require_nonempty_str(
data: dict[str, Any], key: str, index: int | None = None
) -> str:
value = _require_str(data, key, index)
if not value.strip():
raise ProtocolError(f"{_field_name(key, index)} must not be empty")
return value
def _optional_str(
data: dict[str, Any], key: str, index: int | None = None
) -> str | None:
value = data.get(key)
if value is not None and not isinstance(value, str):
raise ProtocolError(f"{_field_name(key, index)} must be a string or null")
return value
def _require_bool(data: dict[str, Any], key: str, index: int) -> bool:
value = data.get(key)
if type(value) is not bool:
raise ProtocolError(f"{_field_name(key, index)} must be a boolean")
return value
def _require_int(data: dict[str, Any], key: str) -> int:
value = data.get(key)
if type(value) is not int:
raise ProtocolError(f"{key} must be an integer")
return value
def _require_decimal(data: dict[str, Any], key: str, index: int) -> Decimal:
value = data.get(key)
if not isinstance(value, str):
raise ProtocolError(f"{_field_name(key, index)} must be a decimal string")
try:
number = Decimal(value)
except InvalidOperation as exc:
raise ProtocolError(
f"{_field_name(key, index)} must be a decimal string"
) from exc
if not number.is_finite():
raise ProtocolError(f"{_field_name(key, index)} must be finite")
return number
def atomic_write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="\n",
delete=False,
dir=path.parent,
prefix=f".{path.name}.",
suffix=".tmp",
) as handle:
handle.write(text)
temporary_path = Path(handle.name)
temporary_path.replace(path)
finally:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
+316
View File
@@ -0,0 +1,316 @@
"""Atomic run mailboxes, backups, operation history, and restore inputs."""
from __future__ import annotations
import json
import re
import tempfile
import uuid
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from dx_productivity.domain.models import (
AnnotationPlan,
ApplyStatus,
DesignSnapshot,
HistoryEntry,
OperationChange,
OpType,
RestoreItem,
RestoreRequest,
RunPaths,
)
FORMAT_VERSION = 2
SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
OP_VALUES = frozenset(item.value for item in OpType)
class RunStoreError(ValueError):
"""Raised when persisted transaction data is missing or inconsistent."""
class RunStore:
def __init__(
self,
root: Path,
*,
now: Callable[[], datetime] | None = None,
uuid_factory: Callable[[], uuid.UUID] | None = None,
) -> None:
self.root = Path(root)
self.run_root = self.root / "runs"
self.backup_root = self.root / "backups"
self.history_root = self.root / "history"
self._now = now or (lambda: datetime.now(timezone.utc))
self._uuid_factory = uuid_factory or uuid.uuid4
def create_run(self) -> RunPaths:
run_id = f"{_timestamp_token(self._now())}-{self._uuid_factory().hex[:8]}"
root = self.run_root / run_id
root.mkdir(parents=True, exist_ok=False)
return RunPaths(
run_id=run_id,
root=root,
request=root / "request.json",
result=root / "result.tsv",
locate=root / "locate.tsv",
apply_status=root / "apply-status.json",
)
def write_backup(
self, snapshot: DesignSnapshot, plan: AnnotationPlan
) -> Path:
if plan.snapshot_id != snapshot.snapshot_id:
raise RunStoreError("plan snapshot does not match backup snapshot")
targets = {
bridge_id: (row.new_refdes or "", row.op, row.property_name)
for row in plan.rows
if row.changed and row.new_refdes is not None
for bridge_id in row.bridge_ids
}
if not targets:
raise RunStoreError("backup requires at least one changed component")
by_bridge = {c.bridge_id: c for c in snapshot.components}
changes = [
OperationChange(
bridge_id=bridge_id,
stable_uid=by_bridge[bridge_id].stable_uid,
full_path=by_bridge[bridge_id].full_path,
op=op,
property_name=property_name,
old_value=by_bridge[bridge_id].refdes
if op is OpType.REFDES
else _attribute_value(by_bridge[bridge_id], property_name),
new_value=new_value,
)
for bridge_id, (new_value, op, property_name) in targets.items()
]
return self.write_operation_backup(snapshot, tuple(changes))
def write_operation_backup(
self, snapshot: DesignSnapshot, changes: tuple[OperationChange, ...]
) -> Path:
"""Persist an operation-aware backup used for restore and history."""
if not changes:
raise RunStoreError("backup requires at least one changed component")
by_bridge = {c.bridge_id: c for c in snapshot.components}
missing = sorted(
change.bridge_id
for change in changes
if change.bridge_id not in by_bridge
)
if missing:
raise RunStoreError(
f"backup target is absent from snapshot: {missing}"
)
timestamp = self._now()
safe_design_id = _safe_name(snapshot.design_id)
filename = (
f"{_timestamp_token(timestamp)}-{safe_design_id}-{snapshot.run_id}.json"
)
path = self.backup_root / filename
payload = {
"format_version": FORMAT_VERSION,
"timestamp": _iso_timestamp(timestamp),
"run_id": snapshot.run_id,
"snapshot_id": snapshot.snapshot_id,
"design_id": snapshot.design_id,
"design_path": snapshot.design_path,
"changes": [
{
"bridge_id": change.bridge_id,
"stable_uid": change.stable_uid,
"full_path": change.full_path,
"op": change.op.value,
"property": change.property_name,
"old_value": change.old_value,
"new_value": change.new_value,
}
for change in changes
],
}
_atomic_write_json(path, payload)
return path
def record_status(
self, status: ApplyStatus, design_id: str | None = None
) -> None:
backup = None
if status.backup_path is not None:
data = _load_json_object(status.backup_path)
if data.get("format_version") != FORMAT_VERSION:
raise RunStoreError("unsupported backup format_version")
if data.get("run_id") != status.run_id:
raise RunStoreError("status run_id does not match backup")
backup = data
elif status.state not in {"rejected", "rollback-failed"}:
raise RunStoreError("history status requires a backup path")
if backup is not None:
resolved_design = _required_string(backup, "design_id")
elif design_id:
resolved_design = design_id
else:
resolved_design = "unknown-design"
timestamp = self._now()
payload = {
"format_version": FORMAT_VERSION,
"timestamp": _iso_timestamp(timestamp),
"run_id": status.run_id,
"design_id": resolved_design,
"backup_path": (
str(status.backup_path) if status.backup_path is not None else ""
),
"state": status.state,
"changed_count": status.changed_count,
}
path = self.history_root / (
f"{_timestamp_token(timestamp)}-{_safe_name(resolved_design)}-"
f"{status.run_id}.json"
)
_atomic_write_json(path, payload)
def list_history(self, design_id: str) -> tuple[HistoryEntry, ...]:
if not self.history_root.exists():
return ()
entries: list[HistoryEntry] = []
for path in self.history_root.glob("*.json"):
try:
data = _load_json_object(path)
if (
data.get("format_version") != FORMAT_VERSION
or data.get("design_id") != design_id
):
continue
changed_count = data.get("changed_count")
if type(changed_count) is not int or changed_count < 0:
continue
backup_value = data.get("backup_path")
backup_path = (
Path(str(backup_value))
if isinstance(backup_value, str) and backup_value.strip()
else None
)
entries.append(
HistoryEntry(
timestamp=_parse_timestamp(
_required_string(data, "timestamp")
),
run_id=_required_string(data, "run_id"),
design_id=design_id,
backup_path=backup_path,
state=_required_string(data, "state"),
changed_count=changed_count,
)
)
except (OSError, ValueError, json.JSONDecodeError):
continue
return tuple(sorted(entries, key=lambda entry: entry.timestamp, reverse=True))
def build_restore_settings(self, entry: HistoryEntry) -> RestoreRequest:
if entry.backup_path is None:
raise RunStoreError("history entry has no restorable backup")
backup = _load_json_object(entry.backup_path)
if backup.get("format_version") != FORMAT_VERSION:
raise RunStoreError("unsupported backup format_version")
if backup.get("design_id") != entry.design_id:
raise RunStoreError("history design_id does not match backup")
raw_changes = backup.get("changes")
if not isinstance(raw_changes, list) or not raw_changes:
raise RunStoreError("backup has no restore changes")
changes = tuple(_parse_restore_item(value) for value in raw_changes)
return RestoreRequest(entry.design_id, entry.backup_path, changes)
def _parse_restore_item(value: object) -> RestoreItem:
if not isinstance(value, dict):
raise RunStoreError("backup change must be an object")
stable_uid = value.get("stable_uid")
if stable_uid is not None and not isinstance(stable_uid, str):
raise RunStoreError("backup stable_uid must be a string or null")
op_raw = value.get("op", OpType.REFDES.value)
if op_raw not in OP_VALUES:
raise RunStoreError("backup change op is invalid")
property_name = value.get("property", "")
if not isinstance(property_name, str):
raise RunStoreError("backup change property must be a string")
return RestoreItem(
bridge_id=_required_string(value, "bridge_id"),
stable_uid=stable_uid,
full_path=_required_string(value, "full_path"),
expected_value=_required_string(value, "new_value", allow_empty=True),
restore_value=_required_string(value, "old_value", allow_empty=True),
op=OpType(op_raw),
property_name=property_name,
)
def _attribute_value(component: Any, property_name: str) -> str:
for attribute in component.attributes:
if attribute.name.casefold() == property_name.casefold():
return attribute.value
return ""
def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
temporary_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="\n",
delete=False,
dir=path.parent,
prefix=f".{path.name}.",
suffix=".tmp",
) as handle:
handle.write(text)
temporary_path = Path(handle.name)
temporary_path.replace(path)
finally:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
def _load_json_object(path: Path) -> dict[str, Any]:
data = json.loads(path.read_text(encoding="utf-8-sig"))
if not isinstance(data, dict):
raise RunStoreError("persisted data root must be an object")
return data
def _required_string(
data: dict[str, Any], key: str, *, allow_empty: bool = False
) -> str:
value = data.get(key)
if not isinstance(value, str) or (not allow_empty and not value.strip()):
raise RunStoreError(f"{key} must be a string")
return value
def _safe_name(value: str) -> str:
safe = SAFE_NAME_RE.sub("_", value).strip("._-")
return safe or "design"
def _timestamp_token(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
def _iso_timestamp(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _parse_timestamp(value: str) -> datetime:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise RunStoreError("timestamp must include a timezone")
return parsed
@@ -0,0 +1,31 @@
"""Describe startup menu actions included in a portable release."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True, slots=True)
class StartupAssets:
tool_root: Path
action_scripts: dict[str, str]
def generate_startup_assets(tool_root: Path) -> StartupAssets:
"""Return stable named actions for the startup-imported menu.
The values are action routes, not filesystem paths. This deliberately keeps
the menu relocatable and prevents feature actions from entering RefDes state.
"""
actions = {
"refdes": "DxToolsOpenRefDes",
"property-change": "DxToolsOpenPropertyChange",
"property-visibility": "DxToolsOpenPropertyVisibility",
"inspection": "DxToolsOpenInspection",
"bom": "DxToolsOpenBom",
"compatibility": "DxToolsOpenCompatibility",
"guide": "DxToolsOpenGuide",
}
return StartupAssets(tool_root=Path(tool_root), action_scripts=actions)
+1
View File
@@ -0,0 +1 @@
"""Pure annotation domain types and algorithms."""
+122
View File
@@ -0,0 +1,122 @@
"""Scope, prefix, eligibility, and logical-component identity rules."""
from __future__ import annotations
import re
from collections import defaultdict
from decimal import Decimal
from dx_productivity.domain.models import (
ComponentRecord,
LogicalComponent,
PrefixResolution,
Scope,
)
PLACEHOLDER_RE = re.compile(r"^([A-Za-z]+)\?+$")
def select_scope(
records: tuple[ComponentRecord, ...], scope: Scope
) -> tuple[ComponentRecord, ...]:
if scope is Scope.SELECTED:
return tuple(record for record in records if record.selected)
if scope is Scope.CURRENT_SHEET:
return tuple(record for record in records if record.current_sheet)
if scope is Scope.FULL_DESIGN:
return records
raise ValueError(f"unsupported scope: {scope!r}")
def resolve_prefix(record: ComponentRecord) -> PrefixResolution:
candidates = (record.refdes.strip(), (record.symbol_refdes_default or "").strip())
for candidate in candidates:
match = PLACEHOLDER_RE.fullmatch(candidate)
if match:
return PrefixResolution(match.group(1).upper(), True, None)
return PrefixResolution(None, False, "missing-prefix")
def is_fill_only_eligible(record: ComponentRecord) -> bool:
if record.locked:
return False
refdes = record.refdes.strip()
return not refdes or PLACEHOLDER_RE.fullmatch(refdes) is not None
def is_reannotation_eligible(record: ComponentRecord) -> bool:
return not record.locked and resolve_prefix(record).resolved
def group_logical_components(
records: tuple[ComponentRecord, ...],
) -> tuple[LogicalComponent, ...]:
buckets: dict[tuple[str, str], list[ComponentRecord]] = defaultdict(list)
ambiguous: list[ComponentRecord] = []
for record in sorted(records, key=lambda item: item.bridge_id.casefold()):
stable_uid = (record.stable_uid or "").strip()
fallback_key = record.logical_group_key.strip()
if stable_uid:
buckets[("uid", stable_uid.casefold())].append(record)
elif fallback_key:
buckets[("fallback", fallback_key.casefold())].append(record)
else:
ambiguous.append(record)
groups = [
_build_group(members, identity_ambiguous=False)
for _, members in sorted(buckets.items(), key=lambda item: item[0])
]
groups.extend(
_build_group(
[record],
identity_ambiguous=True,
forced_key=f"ambiguous:{record.bridge_id}",
)
for record in ambiguous
)
return tuple(sorted(groups, key=lambda group: group.key.casefold()))
def _build_group(
members: list[ComponentRecord],
*,
identity_ambiguous: bool,
forced_key: str | None = None,
) -> LogicalComponent:
ordered_members = tuple(sorted(members, key=_member_sort_key))
representative = ordered_members[0]
prefixes = {
resolution.prefix
for resolution in (resolve_prefix(member) for member in ordered_members)
if resolution.resolved and resolution.prefix is not None
}
key = forced_key or (
(representative.stable_uid or "").strip()
or representative.logical_group_key.strip()
)
return LogicalComponent(
key=key,
members=ordered_members,
prefix=next(iter(prefixes)) if len(prefixes) == 1 else None,
sheet_number=representative.sheet_number,
x=representative.x,
normalized_y=_normalized_y(representative),
identity_ambiguous=identity_ambiguous,
)
def _normalized_y(record: ComponentRecord) -> Decimal:
return record.y if record.y_axis_up else -record.y
def _member_sort_key(record: ComponentRecord) -> tuple[object, ...]:
return (
record.sheet_number is None,
record.sheet_number if record.sheet_number is not None else 0,
-_normalized_y(record),
record.x,
record.bridge_id.casefold(),
)
+263
View File
@@ -0,0 +1,263 @@
"""Immutable data shared by the bridge, planner, and UI."""
from __future__ import annotations
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"
class OpType(str, Enum):
"""Operation kinds carried by a bridge schedule row."""
REFDES = "refdes"
PROPERTY_VALUE = "property"
PROPERTY_VISIBILITY = "visibility"
@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
attributes: tuple["AttributeRecord", ...] = ()
@dataclass(frozen=True, slots=True)
class AttributeRecord:
name: str
value: str
visible: bool
@dataclass(frozen=True, slots=True)
class OperationChange:
"""One reversible design change recorded in a transaction backup."""
bridge_id: str
stable_uid: str | None
full_path: str
op: OpType
property_name: str
old_value: str
new_value: str
@dataclass(frozen=True, slots=True)
class NetRecord:
name: str
pages: tuple[int, ...]
@dataclass(frozen=True, slots=True)
class ApplyStep:
sequence: int
bridge_id: str
expected_refdes: str
new_refdes: str
final_refdes: str
op: OpType = OpType.REFDES
property_name: str = ""
@property
def target_key(self) -> str:
return f"{self.op.value}|{self.property_name.casefold()}|{self.bridge_id.casefold()}"
@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
identity_ambiguous: bool = False
@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")
prefix_overrides: tuple[tuple[str, str], ...] = ()
sheet_number_overrides: tuple[tuple[str, int], ...] = ()
@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
sheet_name: str = ""
sheet_number: int | None = None
x: Decimal = Decimal("0")
normalized_y: Decimal = Decimal("0")
part_number: str = ""
value: str = ""
locked: bool = False
identity_ambiguous: bool = False
op: OpType = OpType.REFDES
property_name: str = ""
@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, ...]
nets: tuple[NetRecord, ...] = ()
selected_nets: tuple[str, ...] = ()
@property
def component_count(self) -> int:
return len(self.components)
@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 ApplyRequest:
format_version: int
run_id: str
snapshot_id: str
backup_path: Path
schedule_sha256: str
@dataclass(frozen=True, slots=True)
class RunPaths:
run_id: str
root: Path
request: Path
result: Path
locate: Path
apply_status: Path
@property
def apply_request(self) -> Path:
return self.root / "apply-request.json"
@dataclass(frozen=True, slots=True)
class HistoryEntry:
timestamp: datetime
run_id: str
design_id: str
backup_path: Path | None
state: str
changed_count: int
@dataclass(frozen=True, slots=True)
class RestoreItem:
bridge_id: str
stable_uid: str | None
full_path: str
expected_value: str
restore_value: str
op: OpType = OpType.REFDES
property_name: str = ""
@dataclass(frozen=True, slots=True)
class RestoreRequest:
design_id: str
source_backup: Path
changes: tuple[RestoreItem, ...]
+80
View File
@@ -0,0 +1,80 @@
"""Per-prefix continuous and page-based reference allocation."""
from __future__ import annotations
import re
from collections import defaultdict
from dx_productivity.domain.models import (
AnnotationSettings,
LogicalComponent,
NumberingMode,
)
PREFIX_RE = re.compile(r"^[A-Za-z]+$")
def allocate_numbers(
components: tuple[LogicalComponent, ...],
occupied: set[str],
settings: AnnotationSettings,
) -> dict[str, str]:
occupied_folded = {value.casefold() for value in occupied}
allocated: dict[str, str] = {}
if settings.numbering_mode is NumberingMode.CONTINUOUS:
if settings.start_number < 1:
raise ValueError("start number must be at least 1")
next_number: dict[str, int] = defaultdict(lambda: settings.start_number)
for component in components:
prefix = _validated_prefix(component)
number = _next_available(
prefix, next_number[prefix], occupied_folded
)
value = f"{prefix}{number}"
allocated[component.key] = value
occupied_folded.add(value.casefold())
next_number[prefix] = number + 1
return allocated
if settings.numbering_mode is NumberingMode.PAGE:
if settings.page_step < 1:
raise ValueError("page step number must be at least 1")
if settings.page_start < 0:
raise ValueError("page start number must not be negative")
next_number: dict[tuple[str, int], int] = {}
for component in components:
if component.sheet_number is None or component.sheet_number < 0:
raise ValueError("page numbering requires a numeric sheet")
prefix = _validated_prefix(component)
key = (prefix, component.sheet_number)
start = (
component.sheet_number * settings.page_step + settings.page_start
)
if start < 1:
raise ValueError("page numbering must start at 1")
number = _next_available(
prefix, next_number.get(key, start), occupied_folded
)
value = f"{prefix}{number}"
allocated[component.key] = value
occupied_folded.add(value.casefold())
next_number[key] = number + 1
return allocated
raise ValueError(f"unsupported numbering mode: {settings.numbering_mode!r}")
def _validated_prefix(component: LogicalComponent) -> str:
prefix = (component.prefix or "").upper()
if PREFIX_RE.fullmatch(prefix) is None:
raise ValueError(f"component {component.key!r} has no resolved prefix")
return prefix
def _next_available(prefix: str, start: int, occupied: set[str]) -> int:
number = start
while f"{prefix}{number}".casefold() in occupied:
number += 1
return number
+107
View File
@@ -0,0 +1,107 @@
"""Deterministic schematic coordinate ordering."""
from __future__ import annotations
from collections import defaultdict
from decimal import Decimal
from typing import Callable
from dx_productivity.domain.models import (
AnnotationSettings,
LogicalComponent,
SortOrder,
)
def order_components(
components: tuple[LogicalComponent, ...], settings: AnnotationSettings
) -> tuple[LogicalComponent, ...]:
tolerance = settings.row_tolerance
if tolerance < 0:
raise ValueError("row_tolerance must not be negative")
by_sheet: dict[int | None, list[LogicalComponent]] = defaultdict(list)
for component in components:
by_sheet[component.sheet_number].append(component)
ordered: list[LogicalComponent] = []
for sheet in sorted(by_sheet, key=_sheet_sort_key):
ordered.extend(_order_sheet(by_sheet[sheet], settings.sort_order, tolerance))
return tuple(ordered)
def _order_sheet(
components: list[LogicalComponent],
sort_order: SortOrder,
tolerance: Decimal,
) -> list[LogicalComponent]:
if sort_order in {
SortOrder.TOP_DOWN_LEFT_RIGHT,
SortOrder.TOP_DOWN_RIGHT_LEFT,
}:
primary = sorted(
components,
key=lambda item: (-item.normalized_y, item.x, item.key.casefold()),
)
rows = _cluster(primary, lambda item: item.normalized_y, tolerance)
reverse_x = sort_order is SortOrder.TOP_DOWN_RIGHT_LEFT
return [
item
for row in rows
for item in sorted(
row,
key=lambda component: (
-component.x if reverse_x else component.x,
component.key.casefold(),
),
)
]
if sort_order in {
SortOrder.LEFT_RIGHT_TOP_DOWN,
SortOrder.RIGHT_LEFT_TOP_DOWN,
}:
reverse_x = sort_order is SortOrder.RIGHT_LEFT_TOP_DOWN
primary = sorted(
components,
key=lambda item: (
-item.x if reverse_x else item.x,
-item.normalized_y,
item.key.casefold(),
),
)
columns = _cluster(primary, lambda item: item.x, tolerance)
return [
item
for column in columns
for item in sorted(
column,
key=lambda component: (
-component.normalized_y,
component.key.casefold(),
),
)
]
raise ValueError(f"unsupported sort order: {sort_order!r}")
def _cluster(
components: list[LogicalComponent],
coordinate: Callable[[LogicalComponent], Decimal],
tolerance: Decimal,
) -> list[list[LogicalComponent]]:
clusters: list[list[LogicalComponent]] = []
anchor: Decimal | None = None
for component in components:
value = coordinate(component)
if anchor is None or abs(value - anchor) > tolerance:
clusters.append([component])
anchor = value
else:
clusters[-1].append(component)
return clusters
def _sheet_sort_key(sheet_number: int | None) -> tuple[bool, int]:
return (sheet_number is None, sheet_number if sheet_number is not None else 0)
+289
View File
@@ -0,0 +1,289 @@
"""Compose scope, grouping, allocation, validation, and scheduling."""
from __future__ import annotations
import re
from dataclasses import replace
from dx_productivity.domain.identity import (
group_logical_components,
is_fill_only_eligible,
select_scope,
)
from dx_productivity.domain.models import (
AnnotationPlan,
AnnotationSettings,
DesignSnapshot,
Issue,
LogicalComponent,
NumberingMode,
PlanRow,
ProcessingMode,
Severity,
)
from dx_productivity.domain.numbering import allocate_numbers
from dx_productivity.domain.ordering import order_components
from dx_productivity.domain.refdes_rules import (
is_claimed_refdes,
split_refdes,
)
from dx_productivity.domain.schedule import build_apply_schedule
from dx_productivity.domain.validation import deduplicate_issues, validate_plan
PREFIX_RE = re.compile(r"^[A-Za-z]+$")
def build_annotation_plan(
snapshot: DesignSnapshot, settings: AnnotationSettings
) -> AnnotationPlan:
scoped_records = select_scope(snapshot.components, settings.scope)
if not scoped_records:
issue = Issue(
"empty-scope",
Severity.BLOCKING,
"当前范围内没有器件",
)
return AnnotationPlan(snapshot.snapshot_id, (), (issue,), ())
prefix_overrides = {
key.casefold(): value.strip().upper()
for key, value in settings.prefix_overrides
}
sheet_overrides = {
name.casefold(): number for name, number in settings.sheet_number_overrides
}
preliminary: list[Issue] = []
groups = tuple(
_apply_overrides(
group,
prefix_overrides,
sheet_overrides,
preliminary,
)
for group in group_logical_components(scoped_records)
)
try:
ordered_groups = order_components(groups, settings)
except ValueError as exc:
preliminary.append(
Issue("invalid-settings", Severity.BLOCKING, str(exc))
)
ordered_groups = tuple(groups)
eligible_keys: set[str] = set()
for group in ordered_groups:
if _is_group_eligible(group, settings.processing_mode, preliminary):
eligible_keys.add(group.key.casefold())
eligible_groups = tuple(
group
for group in ordered_groups
if group.key.casefold() in eligible_keys
)
eligible_members = {
member.bridge_id
for group in eligible_groups
for member in group.members
}
# Occupancy only excludes components this plan will rewrite. Members of the
# same logical component left outside the scope keep their claimed value,
# so the allocator can never hand out a duplicate (out-of-scope members are
# reported separately by validation as out-of-scope-member).
occupied = {
record.refdes.strip().casefold()
for record in snapshot.components
if is_claimed_refdes(record.refdes)
and record.bridge_id not in eligible_members
}
try:
allocations = allocate_numbers(eligible_groups, occupied, settings)
except ValueError as exc:
preliminary.append(
Issue("invalid-numbering", Severity.BLOCKING, str(exc))
)
allocations = {}
preliminary.extend(
_page_overflow_issues(eligible_groups, allocations, settings)
)
rows = tuple(
_build_row(group, allocations.get(group.key), settings.processing_mode)
for group in ordered_groups
)
issues = deduplicate_issues([*preliminary, *validate_plan(snapshot, rows)])
if any(issue.severity is Severity.BLOCKING for issue in issues):
schedule = ()
else:
schedule = build_apply_schedule(rows)
return AnnotationPlan(snapshot.snapshot_id, rows, issues, schedule)
def _page_overflow_issues(
groups: tuple[LogicalComponent, ...],
allocations: dict[str, str],
settings: AnnotationSettings,
) -> list[Issue]:
if settings.numbering_mode is not NumberingMode.PAGE:
return []
issues: list[Issue] = []
for group in groups:
value = allocations.get(group.key)
parsed = split_refdes(value) if value else None
if parsed is None or group.sheet_number is None:
continue
block_end = (
(group.sheet_number + 1) * settings.page_step
+ settings.page_start
- 1
)
if parsed[1] > block_end:
issues.append(
Issue(
"page-overflow",
Severity.WARNING,
"页块位号溢出,已侵入后续页号段",
tuple(member.bridge_id for member in group.members),
)
)
return issues
def _apply_overrides(
group: LogicalComponent,
prefix_overrides: dict[str, str],
sheet_overrides: dict[str, int],
issues: list[Issue],
) -> LogicalComponent:
prefix = prefix_overrides.get(group.key.casefold(), group.prefix)
if prefix is not None:
prefix = prefix.upper()
if PREFIX_RE.fullmatch(prefix) is None:
issues.append(
Issue(
"invalid-prefix",
Severity.BLOCKING,
"手工前缀只能包含英文字母",
tuple(member.bridge_id for member in group.members),
)
)
prefix = None
sheet_number = group.sheet_number
if sheet_number is None:
sheet_name = group.members[0].sheet_name.casefold()
sheet_number = sheet_overrides.get(sheet_name)
elif sheet_overrides:
sheet_name = group.members[0].sheet_name.casefold()
if sheet_name in sheet_overrides:
issues.append(
Issue(
"sheet-override-ignored",
Severity.INFORMATIONAL,
"该页已有页号,页号覆盖仅对未编号页生效",
tuple(member.bridge_id for member in group.members),
)
)
return replace(group, prefix=prefix, sheet_number=sheet_number)
def _is_group_eligible(
group: LogicalComponent,
mode: ProcessingMode,
issues: list[Issue],
) -> bool:
bridge_ids = tuple(member.bridge_id for member in group.members)
if group.identity_ambiguous:
issues.append(
Issue(
"ambiguous-logical-identity",
Severity.BLOCKING,
"无法可靠判断多单元器件归属",
bridge_ids,
)
)
return False
if any(member.locked for member in group.members):
issues.append(
Issue(
"locked-preserved",
Severity.INFORMATIONAL,
"锁定器件已保留",
bridge_ids,
)
)
return False
current_values = {member.refdes.strip().casefold() for member in group.members}
if len(current_values) > 1:
issues.append(
Issue(
"multiple-current-refdes",
Severity.BLOCKING,
"同一逻辑器件包含多个现有位号",
bridge_ids,
)
)
return False
if group.prefix is None:
issues.append(
Issue(
"missing-prefix",
Severity.BLOCKING,
"位号前缀未确定",
bridge_ids,
)
)
return False
if mode is ProcessingMode.FILL_ONLY:
return all(is_fill_only_eligible(member) for member in group.members)
if mode is ProcessingMode.REANNOTATE:
return True
raise ValueError(f"unsupported processing mode: {mode!r}")
def _build_row(
group: LogicalComponent,
allocation: str | None,
mode: ProcessingMode,
) -> PlanRow:
representative = group.members[0]
old_values = {member.refdes.strip() for member in group.members}
old_refdes = (
next(iter(old_values))
if len(old_values) == 1
else representative.refdes.strip()
)
locked = any(member.locked for member in group.members)
if allocation is not None:
new_refdes = allocation
changed = old_refdes.casefold() != allocation.casefold()
status = "pending" if changed else "preserved"
else:
new_refdes = old_refdes if is_claimed_refdes(old_refdes) else None
changed = False
if group.identity_ambiguous or group.prefix is None or len(old_values) > 1:
status = "blocked"
elif locked:
status = "locked"
elif mode is ProcessingMode.FILL_ONLY:
status = "preserved"
else:
status = "blocked"
return PlanRow(
logical_key=group.key,
bridge_ids=tuple(member.bridge_id for member in group.members),
full_path=representative.full_path,
prefix=group.prefix,
old_refdes=old_refdes,
new_refdes=new_refdes,
status=status,
changed=changed,
sheet_name=representative.sheet_name,
sheet_number=group.sheet_number,
x=group.x,
normalized_y=group.normalized_y,
part_number=representative.part_number,
value=representative.value,
locked=locked,
identity_ambiguous=group.identity_ambiguous,
)
@@ -0,0 +1,50 @@
"""Single source of truth for reference-designator string rules.
Three different formal-refdes definitions previously lived in validation,
schedule, and restore. All refdes shape decisions must go through here:
- ``is_formal_refdes``: strict allocator shape ``PREFIX + DIGITS`` (e.g. ``R12``).
Used when deciding whether a *target* value can be reasoned about numerically.
- ``is_claimed_refdes``: any non-empty, non-placeholder value occupying a slot in
the design (``R12``, ``U1A``, even malformed ``R``). Used for occupancy and
collision checks so suffixed or irregular current values can never be ignored.
- ``is_placeholder``: the ``PREFIX??`` un-annotated shape.
"""
from __future__ import annotations
import re
PLACEHOLDER_RE = re.compile(r"^([A-Za-z]+)\?+$")
FORMAL_RE = re.compile(r"^([A-Za-z]+)([0-9]+)$")
PREFIX_RE = re.compile(r"^([A-Za-z]+)$")
def normalize_refdes(value: str) -> str:
return value.strip()
def is_placeholder(value: str) -> bool:
return PLACEHOLDER_RE.fullmatch(value.strip()) is not None
def split_refdes(value: str) -> tuple[str, int] | None:
match = FORMAL_RE.fullmatch(value.strip())
if match is None:
return None
return match.group(1), int(match.group(2))
def is_formal_refdes(value: str) -> bool:
return split_refdes(value) is not None
def is_claimed_refdes(value: str) -> bool:
text = value.strip()
return bool(text) and not is_placeholder(text)
def refdes_prefix(value: str) -> str | None:
match = PREFIX_RE.fullmatch(value.strip())
return match.group(1) if match else None
+246
View File
@@ -0,0 +1,246 @@
"""Build a verified annotation plan from a previous operation backup."""
from __future__ import annotations
from collections import defaultdict
from dx_productivity.domain.models import (
AnnotationPlan,
ComponentRecord,
DesignSnapshot,
Issue,
OpType,
PlanRow,
RestoreItem,
RestoreRequest,
Severity,
)
from dx_productivity.domain.refdes_rules import (
is_claimed_refdes,
refdes_prefix,
)
from dx_productivity.domain.schedule import build_apply_schedule
def build_restore_plan(
snapshot: DesignSnapshot,
request: RestoreRequest,
) -> AnnotationPlan:
issues: list[Issue] = []
if request.design_id != snapshot.design_id:
issues.append(
_issue("restore-design", "备份不属于当前设计")
)
return AnnotationPlan(snapshot.snapshot_id, (), tuple(issues), ())
matched: list[tuple[RestoreItem, ComponentRecord, bool]] = []
for item in request.changes:
candidates = _match_components(snapshot, item)
if not candidates:
issues.append(
_issue("restore-missing", "找不到备份中的器件")
)
continue
if len(candidates) != 1:
issues.append(
_issue(
"restore-ambiguous",
"备份器件身份不唯一",
*(component.bridge_id for component in candidates),
)
)
continue
component = candidates[0]
if component.locked:
issues.append(
_issue(
"restore-locked",
"锁定器件不能恢复位号",
component.bridge_id,
)
)
continue
current = component.refdes.strip().casefold()
expected = item.expected_value.strip().casefold()
restore = item.restore_value.strip().casefold()
if current == expected:
satisfied = False
elif current == restore:
satisfied = True
else:
issues.append(
_issue(
"restore-stale",
"器件位号已在备份后发生变化",
component.bridge_id,
)
)
continue
matched.append((item, component, satisfied))
if issues:
return AnnotationPlan(snapshot.snapshot_id, (), tuple(issues), ())
groups: dict[str, list[tuple[RestoreItem, ComponentRecord, bool]]] = defaultdict(
list
)
for entry in matched:
item, component, _ = entry
if item.op is OpType.REFDES:
key = component.logical_group_key or _identity_key(component)
else:
key = (
f"op:{item.op.value}:{item.property_name}:"
f"{component.bridge_id}"
)
groups[key].append(entry)
target_ids = {
component.bridge_id
for values in groups.values()
for _, component, _ in values
}
outside_claimed = {
component.refdes.strip().casefold()
for component in snapshot.components
if component.bridge_id not in target_ids
and is_claimed_refdes(component.refdes)
}
proposed_claimed: dict[str, str] = {}
rows: list[PlanRow] = []
for logical_key in sorted(groups, key=str.casefold):
values = groups[logical_key]
expected_values = {item.expected_value.strip().casefold() for item, _, _ in values}
restore_values = {item.restore_value.strip().casefold() for item, _, _ in values}
if len(expected_values) != 1 or len(restore_values) != 1:
issues.append(
_issue(
"restore-ambiguous",
"同一逻辑器件包含不一致的恢复值",
*(component.bridge_id for _, component, _ in values),
)
)
continue
item, representative, satisfied = values[0]
target = item.restore_value.strip()
target_folded = target.casefold()
is_refdes = item.op is OpType.REFDES
if is_refdes and is_claimed_refdes(target):
if target_folded in outside_claimed:
issues.append(
_issue(
"restore-collision",
"恢复位号与范围外器件冲突",
*(component.bridge_id for _, component, _ in values),
)
)
continue
other_group = proposed_claimed.get(target_folded)
if other_group is not None and other_group != logical_key:
issues.append(
_issue(
"restore-collision",
"恢复计划包含重复正式位号",
*(component.bridge_id for _, component, _ in values),
)
)
continue
proposed_claimed[target_folded] = logical_key
rows.append(
PlanRow(
logical_key=logical_key,
bridge_ids=tuple(
sorted(
(component.bridge_id for _, component, _ in values),
key=str.casefold,
)
),
full_path=representative.full_path,
prefix=(
refdes_prefix(target) or refdes_prefix(item.expected_value)
)
if is_refdes
else None,
old_refdes=item.expected_value.strip(),
new_refdes=target,
status="restore",
changed=item.expected_value.strip().casefold() != target_folded
and not satisfied,
sheet_name=representative.sheet_name,
sheet_number=representative.sheet_number,
x=representative.x,
normalized_y=(
representative.y
if representative.y_axis_up
else -representative.y
),
part_number=representative.part_number,
value=representative.value,
locked=representative.locked,
op=item.op,
property_name=item.property_name,
)
)
if issues:
return AnnotationPlan(snapshot.snapshot_id, tuple(rows), tuple(issues), ())
try:
schedule = build_apply_schedule(tuple(rows))
except ValueError as exc:
issues.append(_issue("restore-schedule", str(exc)))
schedule = ()
return AnnotationPlan(
snapshot.snapshot_id,
tuple(rows),
tuple(issues),
schedule,
)
def _match_components(
snapshot: DesignSnapshot,
item: RestoreItem,
) -> tuple[ComponentRecord, ...]:
bridge_id = item.bridge_id.strip().casefold()
if bridge_id:
exact = tuple(
component
for component in snapshot.components
if component.bridge_id.casefold() == bridge_id
)
if exact:
return exact
path = item.full_path.strip().casefold()
if path:
by_path = tuple(
component
for component in snapshot.components
if component.full_path.strip().casefold() == path
)
if len(by_path) == 1:
return by_path
uid = (item.stable_uid or "").strip().casefold()
if uid:
by_uid = tuple(
component
for component in snapshot.components
if component.stable_uid
and component.stable_uid.strip().casefold() == uid
)
if by_uid:
return by_uid
return ()
def _identity_key(component: ComponentRecord) -> str:
if component.stable_uid:
return f"uid:{component.stable_uid.casefold()}"
return f"path:{component.full_path.casefold()}"
def _issue(code: str, message: str, *bridge_ids: str) -> Issue:
return Issue(code, Severity.BLOCKING, message, tuple(bridge_ids))
+131
View File
@@ -0,0 +1,131 @@
"""Build an expected-current apply schedule, including cycle breaks."""
from __future__ import annotations
from dataclasses import replace as Replace
from dx_productivity.domain.models import ApplyStep, OpType, PlanRow
from dx_productivity.domain.refdes_rules import PREFIX_RE, is_formal_refdes
def build_apply_schedule(rows: tuple[PlanRow, ...]) -> tuple[ApplyStep, ...]:
"""Property and visibility rows apply as direct independent writes; refdes
rows go through the cycle-breaking scheduler because targets can collide."""
direct: list[ApplyStep] = []
refdes_rows: list[PlanRow] = []
for row in rows:
if not row.changed:
continue
if row.op is OpType.REFDES:
refdes_rows.append(row)
else:
direct.extend(_direct_steps(row))
cycles = _refdes_schedule(tuple(refdes_rows))
combined = list(direct) + list(cycles)
return tuple(
Replace(step, sequence=index)
for index, step in enumerate(combined, start=1)
)
def _direct_steps(row: PlanRow) -> list[ApplyStep]:
if row.new_refdes is None:
raise ValueError(f"changed row {row.logical_key!r} has no target")
if not row.bridge_ids:
raise ValueError(f"changed row {row.logical_key!r} has no bridge ID")
bridge_id = min(row.bridge_ids, key=str.casefold)
target = row.new_refdes.strip()
return [
ApplyStep(
sequence=0,
bridge_id=bridge_id,
expected_refdes=row.old_refdes.strip(),
new_refdes=target,
final_refdes=target,
op=row.op,
property_name=row.property_name,
)
]
def _refdes_schedule(rows: tuple[PlanRow, ...]) -> tuple[ApplyStep, ...]:
pending: dict[str, PlanRow] = {}
current: dict[str, str] = {}
target_owner: dict[str, str] = {}
for row in rows:
if row.new_refdes is None:
raise ValueError(f"changed row {row.logical_key!r} has no target")
if not row.bridge_ids:
raise ValueError(f"changed row {row.logical_key!r} has no bridge ID")
bridge_id = min(row.bridge_ids, key=str.casefold)
if bridge_id in pending:
raise ValueError(f"duplicate bridge ID in schedule: {bridge_id}")
target = row.new_refdes.strip()
owner = target_owner.setdefault(target.casefold(), bridge_id)
if owner != bridge_id:
raise ValueError(
f"duplicate target refdes in schedule: {target!r}"
)
pending[bridge_id] = row
current[bridge_id] = row.old_refdes.strip()
steps: list[ApplyStep] = []
temporary_ids: set[str] = set()
while pending:
available = [
bridge_id
for bridge_id, row in pending.items()
if _target_is_free(bridge_id, row.new_refdes or "", pending, current)
]
if available:
bridge_id = min(available, key=str.casefold)
row = pending.pop(bridge_id)
target = row.new_refdes or ""
steps.append(
ApplyStep(
len(steps) + 1,
bridge_id,
current[bridge_id],
target,
target,
)
)
current[bridge_id] = target
continue
bridge_id = min(pending, key=str.casefold)
if bridge_id in temporary_ids:
raise ValueError("schedule dependency graph cannot be resolved")
row = pending[bridge_id]
prefix = (row.prefix or "").upper()
if PREFIX_RE.fullmatch(prefix) is None:
raise ValueError(f"cycle row {row.logical_key!r} has no valid prefix")
temporary = f"{prefix}?"
steps.append(
ApplyStep(
len(steps) + 1,
bridge_id,
current[bridge_id],
temporary,
row.new_refdes or "",
)
)
current[bridge_id] = temporary
temporary_ids.add(bridge_id)
return tuple(steps)
def _target_is_free(
bridge_id: str,
target: str,
pending: dict[str, PlanRow],
current: dict[str, str],
) -> bool:
if not is_formal_refdes(target):
return True
target_folded = target.casefold()
return all(
other_id == bridge_id or current[other_id].casefold() != target_folded
for other_id in pending
)
+225
View File
@@ -0,0 +1,225 @@
"""Source-design and proposed-plan validation."""
from __future__ import annotations
from collections import defaultdict
from dx_productivity.domain.identity import group_logical_components
from dx_productivity.domain.models import (
ComponentRecord,
DesignSnapshot,
Issue,
PlanRow,
Severity,
)
from dx_productivity.domain.refdes_rules import is_claimed_refdes
def validate_plan(
snapshot: DesignSnapshot, rows: tuple[PlanRow, ...]
) -> tuple[Issue, ...]:
issues: list[Issue] = []
issues.extend(_validate_source_duplicates(snapshot))
issues.extend(_validate_proposed_duplicates(rows))
issues.extend(_validate_occupied_outputs(snapshot, rows))
issues.extend(_validate_out_of_scope_members(snapshot, rows))
issues.extend(_validate_rows(snapshot, rows))
return deduplicate_issues(issues)
def _validate_source_duplicates(snapshot: DesignSnapshot) -> list[Issue]:
owners: dict[str, list[str]] = defaultdict(list)
issues: list[Issue] = []
for group in group_logical_components(snapshot.components):
formal_values = {
member.refdes.strip().casefold()
for member in group.members
if is_claimed_refdes(member.refdes)
}
if len(formal_values) > 1:
issues.append(
Issue(
"multiple-current-refdes",
Severity.BLOCKING,
"同一逻辑器件包含多个现有位号",
tuple(member.bridge_id for member in group.members),
)
)
for value in formal_values:
owners[value].append(group.key)
for keys in owners.values():
unique_keys = tuple(sorted(set(keys), key=str.casefold))
if len(unique_keys) > 1:
issues.append(
Issue(
"duplicate-source-refdes",
Severity.BLOCKING,
"源设计中存在重复正式位号",
unique_keys,
)
)
return issues
def _validate_proposed_duplicates(rows: tuple[PlanRow, ...]) -> list[Issue]:
targets: dict[str, list[PlanRow]] = defaultdict(list)
by_logical: dict[str, set[str]] = defaultdict(set)
for row in rows:
if row.changed and row.new_refdes:
targets[row.new_refdes.casefold()].append(row)
by_logical[row.logical_key].add(row.new_refdes.casefold())
issues: list[Issue] = []
for target_rows in targets.values():
logical_keys = {row.logical_key for row in target_rows}
if len(logical_keys) > 1:
issues.append(
Issue(
"duplicate-proposed-refdes",
Severity.BLOCKING,
"预览中多个器件将获得同一位号",
tuple(
bridge_id
for row in target_rows
for bridge_id in row.bridge_ids
),
)
)
for logical_key, outputs in by_logical.items():
if len(outputs) > 1:
issues.append(
Issue(
"multiple-proposed-refdes",
Severity.BLOCKING,
"同一逻辑器件被分配了多个目标位号",
(logical_key,),
)
)
return issues
def _validate_occupied_outputs(
snapshot: DesignSnapshot, rows: tuple[PlanRow, ...]
) -> list[Issue]:
target_bridge_ids = {
bridge_id for row in rows for bridge_id in row.bridge_ids
}
occupied: dict[str, list[str]] = defaultdict(list)
for record in snapshot.components:
if (
record.bridge_id not in target_bridge_ids
and is_claimed_refdes(record.refdes)
):
occupied[record.refdes.strip().casefold()].append(record.bridge_id)
issues: list[Issue] = []
for row in rows:
if row.changed and row.new_refdes:
conflicts = occupied.get(row.new_refdes.casefold(), [])
if conflicts:
issues.append(
Issue(
"occupied-output",
Severity.BLOCKING,
"目标位号已被范围外器件占用",
tuple(row.bridge_ids) + tuple(conflicts),
)
)
return issues
def _validate_out_of_scope_members(
snapshot: DesignSnapshot, rows: tuple[PlanRow, ...]
) -> list[Issue]:
"""Renaming one member of a logical component while a claimed member
stays outside the plan would silently split multi-unit association."""
row_keys = {
row.logical_key.casefold(): row for row in rows if row.changed
}
if not row_keys:
return []
planned_ids = {
bridge_id for row in rows for bridge_id in row.bridge_ids
}
issues: list[Issue] = []
for record in snapshot.components:
row = row_keys.get(_record_logical_key(record))
if row is None or record.bridge_id in planned_ids:
continue
if is_claimed_refdes(record.refdes):
issues.append(
Issue(
"out-of-scope-member",
Severity.BLOCKING,
"同逻辑器件存在范围外成员,需扩大范围后重编",
tuple(row.bridge_ids) + (record.bridge_id,),
)
)
return issues
def _validate_rows(
snapshot: DesignSnapshot, rows: tuple[PlanRow, ...]
) -> list[Issue]:
by_bridge = {record.bridge_id: record for record in snapshot.components}
issues: list[Issue] = []
for row in rows:
if row.identity_ambiguous:
issues.append(
Issue(
"ambiguous-logical-identity",
Severity.BLOCKING,
"无法可靠判断多单元器件归属",
row.bridge_ids,
)
)
if row.changed and (not row.prefix or not row.new_refdes):
issues.append(
Issue(
"missing-prefix",
Severity.BLOCKING,
"位号前缀未确定",
row.bridge_ids,
)
)
if row.changed and any(
by_bridge.get(bridge_id) is not None
and by_bridge[bridge_id].locked
for bridge_id in row.bridge_ids
):
issues.append(
Issue(
"locked-target",
Severity.BLOCKING,
"锁定器件不能修改位号",
row.bridge_ids,
)
)
return issues
def deduplicate_issues(issues: list[Issue]) -> tuple[Issue, ...]:
unique = {
(issue.code, issue.severity, issue.bridge_ids): issue for issue in issues
}
severity_order = {
Severity.BLOCKING: 0,
Severity.WARNING: 1,
Severity.INFORMATIONAL: 2,
}
return tuple(
sorted(
unique.values(),
key=lambda issue: (
severity_order[issue.severity],
issue.code,
issue.bridge_ids,
),
)
)
def _record_logical_key(record: ComponentRecord) -> str:
key = (record.stable_uid or "").strip() or record.logical_group_key.strip()
return key.casefold()
+1
View File
@@ -0,0 +1 @@
"""Native reimplementations of the legacy tool modules."""
@@ -0,0 +1,160 @@
"""Assembly reference designator tidy-up for Expedition PCB.
Faithful port of the legacy MoveAssemblyRef.vbs (AATK 4.0 based, author
wuyongqing 2013): all fabrication-layer refdes texts are re-oriented to the
component orientation, re-sized from the component placement outline, and
moved to the component origin; non-refdes fab texts attached to components
are deleted.
The Expedition host exports a line-oriented request (one ``T|`` record per
fabrication text, one ``C|`` record per component) and consumes the returned
plan lines (``MOVE|`` / ``DELETE|``) inside a single transaction.
"""
from __future__ import annotations
from dataclasses import dataclass
from dx_productivity.domain.models import OpType # noqa: F401 (re-export)
MAXHEIGHT = 0.8
@dataclass(frozen=True, slots=True)
class FabricationText:
index: int
text_type: int
side: int
is_assembly: bool
text_string: str
orientation: float
component_name: str
@dataclass(frozen=True, slots=True)
class ComponentFootprint:
name: str
pos_x: float
pos_y: float
x_half_span: float
y_half_span: float
@dataclass(frozen=True, slots=True)
class MovePlan:
index: int
x: float
y: float
rotation: float
height: float | None
font: str
@dataclass(frozen=True, slots=True)
class DeletePlan:
index: int
def plan_assembly_refdes(
texts: list[FabricationText],
footprints: dict[str, ComponentFootprint],
) -> tuple[tuple[MovePlan | DeletePlan, ...], int]:
"""Return the plan plus the number of processed refdes texts."""
plans: list[MovePlan | DeletePlan] = []
processed = 0
for text in sorted(texts, key=lambda item: item.index):
if text.component_name == "":
continue
if text.text_type != 1:
plans.append(DeletePlan(index=text.index))
continue
footprint = footprints.get(text.component_name)
if footprint is None:
continue
processed += 1
rotation, height = _orientation_and_height(text, footprint)
plans.append(
MovePlan(
index=text.index,
x=footprint.pos_x,
y=footprint.pos_y,
rotation=rotation,
height=height,
font=_font_for(text.text_string),
)
)
return tuple(plans), processed
def _font_for(text_string: str) -> str:
n = len(text_string)
if n < 5:
return "Arial"
if n < 6:
return "Arial Narrow"
return "Arial Narrow"
def _clamp_height(value: float) -> float:
if value < 0.1 or value > MAXHEIGHT:
return MAXHEIGHT
return value
def _orientation_and_height(
text: FabricationText, footprint: ComponentFootprint
) -> tuple[float, float | None]:
ori = text.orientation
if ori in (0, 180):
rotation = 0
height = (
_clamp_height(footprint.y_half_span)
if text.is_assembly
else None
)
elif ori in (90, 270):
rotation = 90 if text.side == 1 else 270
height = (
_clamp_height(footprint.x_half_span)
if text.is_assembly
else None
)
elif ori in (45, 225):
rotation = 45
height = (
_clamp_height(footprint.x_half_span * 0.54)
if text.is_assembly
else None
)
elif ori in (135, 315):
rotation = 315
height = (
_clamp_height(footprint.x_half_span * 0.54)
if text.is_assembly
else None
)
elif 90 < ori < 270:
rotation = ori + 180
height = 0.4
else:
rotation = ori
height = 0.4
return rotation, height
def render_plan(
plans: tuple[MovePlan | DeletePlan, ...],
) -> str:
"""Render the plan as line records consumed by the Expedition host."""
lines: list[str] = []
for plan in plans:
if isinstance(plan, DeletePlan):
lines.append(f"DELETE|{plan.index}")
else:
height = "" if plan.height is None else f"{plan.height:.4f}"
lines.append(
f"MOVE|{plan.index}|{plan.x:.4f}|{plan.y:.4f}|"
f"{plan.rotation:.2f}|{height}|{plan.font}"
)
return "".join(f"{line}\n" for line in lines)
@@ -0,0 +1,17 @@
"""Native BOM export feature (legacy Bom.efm logic, Python checks)."""
from dx_productivity.features.bom.planner import (
BOMResult,
BOMRow,
BOMSettings,
build_bom,
pv_check,
)
__all__ = [
"BOMResult",
"BOMRow",
"BOMSettings",
"build_bom",
"pv_check",
]
+384
View File
@@ -0,0 +1,384 @@
"""BOM assembly and Skyworth part-number verification (legacy Bom.efm, natively).
The merge/filter/check pipeline below is a faithful port of the legacy
PLBOM form script (Bom.efm, version 20161026):
- components grouped per sheet, duplicates merged by (part number, description),
- ``MARK`` / ``TEST_POINT`` / ``MOUNTHOL`` rows deleted,
- optional NC filtering on the description,
- duplicate-refdes highlighting (red) and PVCheck part-number verification
(orange) using the original Skyworth part-number decode rules.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from dx_productivity.domain.models import (
AttributeRecord,
ComponentRecord,
DesignSnapshot,
)
MARK_EXCLUSIONS = ("MARK", "TEST_POINT", "MOUNTHOL")
@dataclass(frozen=True, slots=True)
class BOMSettings:
"""``description_source``: ``value`` or ``part-label`` (legacy cbDesc)."""
scope: str = "full" # full | current-sheet | selected
description_source: str = "value"
exclude_nc: bool = False
@dataclass(frozen=True, slots=True)
class BOMRow:
page: int | None
qty: int
refdes: str
part_number: str
description: str
duplicate_refdes: bool = False
part_number_mismatch: bool = False
mismatch_reason: str = ""
@dataclass(frozen=True, slots=True)
class BOMResult:
sections: tuple[tuple[int | None, tuple[BOMRow, ...]], ...] = ()
rows: tuple[BOMRow, ...] = field(default_factory=tuple)
excluded_count: int = 0
def build_bom(
snapshot: DesignSnapshot, settings: BOMSettings
) -> BOMResult:
components = _scope_components(snapshot, settings.scope)
part_rows: list[_RawRow] = []
excluded = 0
for component in components:
part_number = _part_number(component)
description = _description(component, settings.description_source)
if settings.exclude_nc and "nc" in description.casefold():
excluded += 1
continue
refdes = component.refdes.strip() or component.stable_uid or ""
part_rows.append(
_RawRow(
page=component.sheet_number,
refdes=refdes,
part_number=part_number,
description=description,
)
)
# Group by page in ascending order (None last), mirroring the per-page
# merge of the legacy walk.
pages: list[int | None] = []
for row in part_rows:
if row.page not in pages:
pages.append(row.page)
pages.sort(key=lambda page: (page is None, page if page is not None else 0))
merged_rows: list[BOMRow] = []
sections: list[tuple[int | None, tuple[BOMRow, ...]]] = []
for page in pages:
page_rows = [row for row in part_rows if row.page == page]
merged = _merge(page_rows)
merged = [
row
for row in merged
if not any(token in row.part_number for token in MARK_EXCLUSIONS)
]
sections.append((page, tuple(merged)))
merged_rows.extend(merged)
duplicate_refdes = _duplicate_refdes(merged_rows)
checked: list[BOMRow] = []
for row in merged_rows:
mismatch, reason = pv_check(row.part_number, row.description)
checked.append(
BOMRow(
page=row.page,
qty=row.qty,
refdes=row.refdes,
part_number=row.part_number,
description=row.description,
duplicate_refdes=row.refdes.casefold() in duplicate_refdes,
part_number_mismatch=mismatch,
mismatch_reason=reason,
)
)
# rebuild sections with checked rows
checked_sections: list[tuple[int | None, tuple[BOMRow, ...]]] = []
cursor = 0
for page, section_rows in sections:
count = len(section_rows)
checked_sections.append(
(page, tuple(checked[cursor : cursor + count]))
)
cursor += count
return BOMResult(
sections=tuple(checked_sections),
rows=tuple(checked),
excluded_count=excluded,
)
@dataclass(frozen=True, slots=True)
class _RawRow:
page: int | None
refdes: str
part_number: str
description: str
def _scope_components(
snapshot: DesignSnapshot, scope: str
) -> tuple[ComponentRecord, ...]:
if scope == "selected":
return tuple(c for c in snapshot.components if c.selected)
if scope == "current-sheet":
return tuple(c for c in snapshot.components if c.current_sheet)
if scope == "full":
return snapshot.components
raise ValueError(f"unsupported BOM scope: {scope!r}")
def _merge(rows: list[_RawRow]) -> list[BOMRow]:
"""Merge rows sharing (part number, description); drop exact duplicates.
Mirrors Mergeduplicates: first remove rows where refdes+part number repeat
(resistor arrays share one part), then combine same part+description rows
by appending refdes and incrementing qty.
"""
merged: list[BOMRow] = []
seen_exact: dict[tuple[str, str], int] = {}
for row in rows:
exact = (row.refdes.casefold(), row.part_number.casefold())
if exact in seen_exact:
continue
seen_exact[exact] = 1
merged.append(
BOMRow(
page=row.page,
qty=1,
refdes=row.refdes,
part_number=row.part_number,
description=row.description,
)
)
combined: dict[tuple[str, str], BOMRow] = {}
order: list[tuple[str, str]] = []
for row in merged:
key = (row.part_number.casefold(), row.description.casefold())
if key in combined:
existing = combined[key]
combined[key] = BOMRow(
page=existing.page,
qty=existing.qty + 1,
refdes=f"{existing.refdes},{row.refdes}",
part_number=existing.part_number,
description=existing.description,
)
else:
combined[key] = row
order.append(key)
return [combined[key] for key in order]
def _duplicate_refdes(rows: list[BOMRow]) -> set[str]:
counts: dict[str, int] = {}
for row in rows:
for refdes in row.refdes.split(","):
refdes = refdes.strip()
if refdes:
counts[refdes.casefold()] = (
counts.get(refdes.casefold(), 0) + 1
)
return {refdes for refdes, count in counts.items() if count > 1}
def _part_number(component: ComponentRecord) -> str:
value = _attribute(component.attributes, "Part Number")
if value:
return value
return component.part_number
def _description(
component: ComponentRecord, description_source: str
) -> str:
if description_source == "part-label":
return _attribute(component.attributes, "Part Label")
if description_source == "value":
return _attribute(component.attributes, "VALUE") or component.value
raise ValueError(f"unsupported description source: {description_source!r}")
def _attribute(
attributes: tuple[AttributeRecord, ...], name: str
) -> str:
folded = name.casefold()
for attribute in attributes:
if attribute.name.casefold() == folded:
return attribute.value
return ""
def pv_check(part_number: str, description: str) -> tuple[bool, str]:
"""Skyworth part-number verification (legacy PVCheck).
Returns ``(mismatch, reason)``. Ported branch-for-branch from the original
VBScript, including its StrComp-based ``not equal`` semantics.
"""
part_num = part_number
part_val = description.upper()
if len(part_val) <= 1:
return False, ""
if part_num[2:4] == "XX":
return False, ""
if "USE" in part_val:
return False, ""
if len(part_num) < 11:
return False, ""
v1 = part_num[7]
v2 = part_num[8]
v3 = part_num[9]
v4 = part_num[10]
temp: str | None = None
precision: str | None = None
def ne(left: str, right: str) -> bool:
return left != right
if part_num[:2] == "41":
if v3 == "D":
if ne(v4, "0"):
temp = f"0.00{v1}{v2}{v4}R"
elif ne(v2, "0"):
temp = f"0.00{v1}{v2}R"
else:
temp = f"0.00{v1}R"
elif v3 == "C":
if ne(v4, "0"):
temp = f"0.0{v1}{v2}{v4}R"
elif ne(v2, "0"):
temp = f"0.0{v1}{v2}R"
else:
temp = f"0.0{v1}R"
elif v3 == "B":
if ne(v4, "0"):
temp = f"0.{v1}{v2}{v4}R"
elif ne(v2, "0"):
temp = f"0.{v1}{v2}R"
else:
temp = f"0.{v1}R"
elif v3 == "A":
if ne(v4, "0"):
temp = f"{v1}.{v2}{v4}R"
elif ne(v2, "0"):
temp = f"{v1}.{v2}R"
else:
temp = f"{v1}R"
elif v3 == "0":
if ne(v4, "0"):
temp = f"{v1}{v2}.{v4}R"
elif ne(v1, "0"):
temp = f"{v1}{v2}R"
else:
temp = "0R"
elif v3 == "1":
temp = f"{v1}{v2}{v4}R"
elif v3 == "2":
if ne(v4, "0"):
temp = f"{v1}.{v2}{v4}K"
elif ne(v2, "0"):
temp = f"{v1}.{v2}K"
else:
temp = f"{v1}K"
elif v3 == "3":
if ne(v4, "0"):
temp = f"{v1}{v2}.{v4}K"
else:
temp = f"{v1}{v2}K"
elif v3 == "4":
temp = f"{v1}{v2}{v4}K"
elif v3 == "5":
if ne(v4, "0"):
temp = f"{v1}.{v2}{v4}M"
elif ne(v2, "0"):
temp = f"{v1}.{v2}M"
else:
temp = f"{v1}M"
elif v3 == "6":
if ne(v4, "0"):
temp = f"{v1}{v2}.{v4}M"
else:
temp = f"{v1}{v2}M"
if part_num[-4:] == "2200":
precision = "1%"
if temp is not None and temp not in part_val:
return True, f"标称值 {temp} 未出现在描述中"
if precision is not None and "%1" in part_val and precision not in part_val:
return True, "描述精度与 1% 料号不符"
return False, ""
if part_num[:2] == "43":
if v3 == "B":
temp = f"0.{v1}{v2}P" if ne(v2, "0") else f"0.{v1}P"
elif v3 == "A":
temp = f"{v1}.{v2}P" if ne(v2, "0") else f"{v1}P"
elif v3 == "0":
temp = f"{v1}{v2}P"
elif v3 == "1":
temp = f"{v1}{v2}0P"
elif v3 == "2":
temp = f"{v1}.{v2}N" if ne(v2, "0") else f"{v1}N"
elif v3 == "3":
temp = f"{v1}{v2}N"
elif v3 == "4":
temp = f"{v1}{v2}0N"
elif v3 == "5":
temp = f"{v1}.{v2}U" if ne(v2, "0") else f"{v1}U"
elif v3 == "6":
temp = f"{v1}{v2}U"
elif v3 == "7":
temp = f"{v1}{v2}0U"
elif v3 == "8":
temp = f"{v1}{v2}00U"
if temp is not None and temp not in part_val:
return True, f"标称值 {temp} 未出现在描述中"
return False, ""
if part_num[:2] == "48":
if v3 == "D":
temp = f"{v1}.{v2}N" if ne(v2, "0") else f"{v1}N"
elif v3 == "C":
temp = f"{v1}{v2}N"
elif v3 == "B":
temp = f"{v1}{v2}0N"
elif v3 == "A":
temp = f"{v1}.{v2}U" if ne(v2, "0") else f"{v1}U"
elif v3 == "0":
temp = f"{v1}{v2}U"
elif v3 == "1":
temp = f"{v1}{v2}0U"
elif v3 == "2":
temp = f"{v1}.{v2}M" if ne(v2, "0") else f"{v1}M"
elif v3 == "3":
temp = f"{v1}{v2}M"
elif v3 == "4":
temp = f"{v1}{v2}0M"
if temp is not None and temp not in part_val:
return True, f"标称值 {temp} 未出现在描述中"
return False, ""
return False, ""
@@ -0,0 +1,19 @@
"""Read-only design inspection feature (legacy NET_CHECK, natively)."""
from dx_productivity.features.inspection.planner import (
InspectionRow,
has_net_data,
missing_attribute_values,
net_cross_page,
net_list,
solitary_nets,
)
__all__ = [
"InspectionRow",
"has_net_data",
"missing_attribute_values",
"net_cross_page",
"net_list",
"solitary_nets",
]
@@ -0,0 +1,144 @@
"""Read-only design inspections (legacy NET_CHECK tools, natively).
Migrated behaviours:
- NET-solitary.efm: nets whose label appears on exactly one page.
- NET-List.efm: every named net with the pages it appears on.
- NET-interactive.efm: cross-page lookup for one net name.
- Value_Check_Miss.efm / Value1_Check_Miss.efm: components whose Value/Value1
attribute exists but is empty. The legacy tool only flagged empty values;
``include_missing=True`` additionally flags components without the attribute.
All checks are read-only and never produce a schedule.
"""
from __future__ import annotations
from dataclasses import dataclass
from dx_productivity.domain.models import AttributeRecord, DesignSnapshot
SOLITARY = "孤立网络"
NET_LIST = "网络列表"
VALUE_MISS = "遗漏查找"
@dataclass(frozen=True, slots=True)
class InspectionRow:
kind: str
name: str
pages: tuple[int, ...]
detail: str
locate_net: bool = False
locate_bridge_id: str | None = None
def solitary_nets(snapshot: DesignSnapshot) -> list[InspectionRow]:
"""Nets that appear on exactly one page (no cross-page connection)."""
return [
InspectionRow(
kind=SOLITARY,
name=net.name,
pages=net.pages,
detail=f"仅出现在第 {net.pages[0]} 页"
if net.pages
else "未记录页号",
locate_net=True,
)
for net in snapshot.nets
if len(net.pages) == 1
]
def net_list(snapshot: DesignSnapshot) -> list[InspectionRow]:
return [
InspectionRow(
kind=NET_LIST,
name=net.name,
pages=net.pages,
detail="跨页网络" if len(net.pages) > 1 else "单页网络",
locate_net=True,
)
for net in snapshot.nets
]
def net_cross_page(snapshot: DesignSnapshot, name: str) -> list[InspectionRow]:
folded = name.strip().casefold()
for net in snapshot.nets:
if net.name.casefold() == folded:
return [
InspectionRow(
kind=NET_LIST,
name=net.name,
pages=(page,),
detail=f"第 {page} 页",
locate_net=True,
)
for page in net.pages
]
return []
def missing_attribute_values(
snapshot: DesignSnapshot,
attribute_name: str,
*,
include_missing: bool = False,
) -> list[InspectionRow]:
rows: list[InspectionRow] = []
folded = attribute_name.casefold()
for component in snapshot.components:
if not component.refdes.strip():
continue
value: str | None = None
for attribute in component.attributes:
if attribute.name.casefold() == folded:
value = attribute.value
break
if value is None:
if include_missing:
rows.append(
_component_row(
component.bridge_id,
component.refdes,
attribute_name,
"属性缺失",
)
)
continue
if not value.strip():
rows.append(
_component_row(
component.bridge_id,
component.refdes,
attribute_name,
"属性值为空",
)
)
return rows
def _component_row(
bridge_id: str, refdes: str, attribute_name: str, detail: str
) -> InspectionRow:
return InspectionRow(
kind=VALUE_MISS,
name=f"{refdes} {attribute_name}",
pages=(),
detail=detail,
locate_bridge_id=bridge_id,
)
def has_net_data(snapshot: DesignSnapshot) -> bool:
return bool(snapshot.nets)
def attribute_value(
attributes: tuple[AttributeRecord, ...], name: str
) -> str | None:
for attribute in attributes:
if attribute.name.casefold() == name.casefold():
return attribute.value
return None
@@ -0,0 +1,13 @@
"""Batch property value change feature (legacy Value tools, natively)."""
from dx_productivity.features.property_change.planner import (
PropertyChangeSettings,
SUPPORTED_PROPERTIES,
build_property_change_plan,
)
__all__ = [
"SUPPORTED_PROPERTIES",
"PropertyChangeSettings",
"build_property_change_plan",
]
@@ -0,0 +1,170 @@
"""Batch property value change (legacy Value/Value1/PartNumber tools).
Legacy behaviour preserved from PART_Value_CHA.efm / PART_Value1_CHA.efm /
PART_PartNumber_CHA.efm: only components that already carry the attribute are
rewritten, and components without it are skipped. The new implementation makes
those skips visible instead of silent and adds transactional restore.
"""
from __future__ import annotations
from dataclasses import dataclass
from dx_productivity.domain.models import (
AnnotationPlan,
AttributeRecord,
DesignSnapshot,
Issue,
OpType,
PlanRow,
Severity,
)
from dx_productivity.domain.schedule import build_apply_schedule
from dx_productivity.domain.validation import deduplicate_issues
SUPPORTED_PROPERTIES = ("Value", "Value1", "Part Number")
@dataclass(frozen=True, slots=True)
class PropertyChangeSettings:
property_name: str = "Value"
overrides: tuple[tuple[str, str], ...] = ()
def build_property_change_plan(
snapshot: DesignSnapshot, settings: PropertyChangeSettings
) -> AnnotationPlan:
property_name = settings.property_name.strip()
issues: list[Issue] = []
if not property_name:
issues.append(
Issue("invalid-property", Severity.BLOCKING, "属性名不能为空")
)
return AnnotationPlan(snapshot.snapshot_id, (), tuple(issues), ())
overrides: dict[str, str] = {}
duplicate_ids: list[str] = []
for bridge_id, value in settings.overrides:
key = bridge_id.strip().casefold()
if key in overrides:
duplicate_ids.append(bridge_id)
continue
overrides[key] = value
if duplicate_ids:
issues.append(
Issue(
"duplicate-override",
Severity.BLOCKING,
"同一器件被指定了多个目标值",
tuple(duplicate_ids),
)
)
rows: list[PlanRow] = []
for component in snapshot.components:
if not component.selected:
continue
key = component.bridge_id.casefold()
if key not in overrides:
continue
current = _attribute_value(component.attributes, property_name)
new_value = overrides[key]
if component.locked:
issues.append(
Issue(
"skipped-locked",
Severity.INFORMATIONAL,
"锁定器件已跳过",
(component.bridge_id,),
)
)
rows.append(
_row(snapshot, component, property_name, current, current,
"locked", False)
)
continue
if current is None:
issues.append(
Issue(
"skipped-missing",
Severity.INFORMATIONAL,
"器件没有该属性,已跳过(旧版行为为静默跳过)",
(component.bridge_id,),
)
)
rows.append(
_row(
snapshot,
component,
property_name,
None,
None,
"skipped",
False,
)
)
continue
changed = current != new_value
rows.append(
_row(
snapshot,
component,
property_name,
current,
new_value,
"pending" if changed else "preserved",
changed,
)
)
deduped = deduplicate_issues(issues)
if any(issue.severity is Severity.BLOCKING for issue in deduped):
return AnnotationPlan(snapshot.snapshot_id, tuple(rows), deduped, ())
try:
schedule = build_apply_schedule(tuple(rows))
except ValueError as exc:
return AnnotationPlan(
snapshot.snapshot_id,
tuple(rows),
deduped + (Issue("invalid-schedule", Severity.BLOCKING, str(exc)),),
(),
)
return AnnotationPlan(snapshot.snapshot_id, tuple(rows), deduped, schedule)
def _attribute_value(
attributes: tuple[AttributeRecord, ...], property_name: str
) -> str | None:
for attribute in attributes:
if attribute.name.casefold() == property_name.casefold():
return attribute.value
return None
def _row(
snapshot: DesignSnapshot,
component,
property_name: str,
current: str | None,
new_value: str | None,
status: str,
changed: bool,
) -> PlanRow:
return PlanRow(
logical_key=f"property:{property_name}:{component.bridge_id}",
bridge_ids=(component.bridge_id,),
full_path=component.full_path,
prefix=None,
old_refdes=current if current is not None else "",
new_refdes=new_value,
status=status,
changed=changed,
sheet_name=component.sheet_name,
sheet_number=component.sheet_number,
part_number=component.part_number,
value=component.value,
locked=component.locked,
op=OpType.PROPERTY_VALUE,
property_name=property_name,
)
@@ -0,0 +1,13 @@
"""Batch attribute visibility feature (legacy hide tools, natively)."""
from dx_productivity.features.property_visibility.planner import (
SUPPORTED_PROPERTIES,
PropertyVisibilitySettings,
build_property_visibility_plan,
)
__all__ = [
"SUPPORTED_PROPERTIES",
"PropertyVisibilitySettings",
"build_property_visibility_plan",
]
@@ -0,0 +1,137 @@
"""Batch attribute visibility control (legacy PartName/PartLabel Hide tools).
Legacy behaviour from PartName_Hide.efm / PartLabel_Hide.efm: hide the
"Part Name" / "Part Label" attribute on every selected component that carries
it, then refresh. The native version adds a visible preview, a show (restore)
direction, skip reporting, and transactional restore.
"""
from __future__ import annotations
from dataclasses import dataclass
from dx_productivity.domain.models import (
AnnotationPlan,
AttributeRecord,
DesignSnapshot,
Issue,
OpType,
PlanRow,
Severity,
)
from dx_productivity.domain.schedule import build_apply_schedule
from dx_productivity.domain.validation import deduplicate_issues
SUPPORTED_PROPERTIES = ("Part Name", "Part Label")
@dataclass(frozen=True, slots=True)
class PropertyVisibilitySettings:
property_name: str = "Part Name"
visible: bool = False
def build_property_visibility_plan(
snapshot: DesignSnapshot, settings: PropertyVisibilitySettings
) -> AnnotationPlan:
property_name = settings.property_name.strip()
issues: list[Issue] = []
if not property_name:
issues.append(
Issue("invalid-property", Severity.BLOCKING, "属性名不能为空")
)
return AnnotationPlan(snapshot.snapshot_id, (), tuple(issues), ())
target = "1" if settings.visible else "0"
rows: list[PlanRow] = []
for component in snapshot.components:
if not component.selected:
continue
current = _attribute_visibility(component.attributes, property_name)
if current is None:
issues.append(
Issue(
"skipped-missing",
Severity.INFORMATIONAL,
"器件没有该属性,已跳过",
(component.bridge_id,),
)
)
continue
changed = current != target
if component.locked:
issues.append(
Issue(
"skipped-locked",
Severity.INFORMATIONAL,
"锁定器件已跳过",
(component.bridge_id,),
)
)
rows.append(
PlanRow(
logical_key=(
f"visibility:{property_name}:{component.bridge_id}"
),
bridge_ids=(component.bridge_id,),
full_path=component.full_path,
prefix=None,
old_refdes=current,
new_refdes=current,
status="locked",
changed=False,
sheet_name=component.sheet_name,
sheet_number=component.sheet_number,
part_number=component.part_number,
value=component.value,
locked=True,
op=OpType.PROPERTY_VISIBILITY,
property_name=property_name,
)
)
continue
rows.append(
PlanRow(
logical_key=(
f"visibility:{property_name}:{component.bridge_id}"
),
bridge_ids=(component.bridge_id,),
full_path=component.full_path,
prefix=None,
old_refdes=current,
new_refdes=target,
status="pending" if changed else "preserved",
changed=changed,
sheet_name=component.sheet_name,
sheet_number=component.sheet_number,
part_number=component.part_number,
value=component.value,
locked=component.locked,
op=OpType.PROPERTY_VISIBILITY,
property_name=property_name,
)
)
deduped = deduplicate_issues(issues)
if any(issue.severity is Severity.BLOCKING for issue in deduped):
return AnnotationPlan(snapshot.snapshot_id, tuple(rows), deduped, ())
try:
schedule = build_apply_schedule(tuple(rows))
except ValueError as exc:
return AnnotationPlan(
snapshot.snapshot_id,
tuple(rows),
deduped + (Issue("invalid-schedule", Severity.BLOCKING, str(exc)),),
(),
)
return AnnotationPlan(snapshot.snapshot_id, tuple(rows), deduped, schedule)
def _attribute_visibility(
attributes: tuple[AttributeRecord, ...], property_name: str
) -> str | None:
for attribute in attributes:
if attribute.name.casefold() == property_name.casefold():
return "1" if attribute.visible else "0"
return None
+1
View File
@@ -0,0 +1 @@
"""PySide6 desktop interface."""
+432
View File
@@ -0,0 +1,432 @@
"""Application entry point."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import traceback
import uuid
from collections.abc import Sequence
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from PySide6.QtGui import QFont, QFontDatabase
from PySide6.QtWidgets import QApplication, QMessageBox
from dx_productivity import __version__
from dx_productivity.bridge.protocol import load_request
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import RunPaths
from dx_productivity.ui.bom_controller import BomController
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.property_change_controller import PropertyChangeController
from dx_productivity.ui.property_change_page import PropertyChangePage
from dx_productivity.ui.property_visibility_controller import (
PropertyVisibilityController,
)
from dx_productivity.ui.property_visibility_page import PropertyVisibilityPage
from dx_productivity.ui.history_controller import HistoryController
from dx_productivity.ui.history_page import HistoryPage
from dx_productivity.ui.inspection_controller import InspectionController
from dx_productivity.ui.inspection_page import InspectionPage
from dx_productivity.ui.settings_controller import SettingsController
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.ui.refdes_controller import RefDesController
from dx_productivity.ui.refdes_page import RefDesPage
def create_application(argv: Sequence[str]) -> QApplication:
existing = QApplication.instance()
if existing is not None:
_load_windows_ui_fonts(existing)
return existing
application = QApplication(list(argv))
_load_windows_ui_fonts(application)
return application
def _load_windows_ui_fonts(application: QApplication) -> None:
if sys.platform != "win32":
return
font_root = Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts"
for filename in ("msyh.ttc", "msyhbd.ttc", "msyhl.ttc"):
path = font_root / filename
if path.exists():
QFontDatabase.addApplicationFont(str(path))
application.setFont(QFont("Microsoft YaHei UI", 13))
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="DxDesigner productivity tools")
parser.add_argument("--request", type=Path)
parser.add_argument("--feature", choices=sorted(FEATURE_PAGE_INDEX))
parser.add_argument("--smoke-test-ms", type=int)
return parser
FEATURE_PAGE_INDEX = {
"refdes": 0,
"property-change": 1,
"property-visibility": 2,
"inspection": 3,
"bom": 5,
"history": 6,
"settings": 7,
}
STATUS_TEXT = {
"applied": "位号已应用",
"rolled-back": "已回滚",
"rejected": "已拒绝:设计状态与预览不一致",
"rollback-failed": "回滚失败,请检查设计",
}
def _status_text(state: str) -> str:
return STATUS_TEXT.get(state, state)
def create_main_window(request_path: Path | None = None) -> MainWindow:
window = MainWindow()
page = RefDesPage()
run_paths = None
run_store = None
snapshot = None
if request_path is not None:
snapshot = load_request(request_path)
run_root = request_path.parent
run_paths = RunPaths(
snapshot.run_id,
run_root,
request_path,
run_root / "result.tsv",
run_root / "locate.tsv",
run_root / "apply-status.json",
)
local_app_data = Path(os.environ.get("LOCALAPPDATA", run_root.parent))
run_store = RunStore(local_app_data / "DxProductivity")
controller = RefDesController(
page,
run_store=run_store,
run_paths=run_paths,
)
window.refdes_controller = controller
window.set_page(0, page, "自动位号")
controller.can_apply_changed.connect(window.apply_button.setEnabled)
controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
)
controller.apply_failed.connect(
lambda message: _report_error(window, "应用位号失败", message)
)
window.refresh_requested.connect(
lambda: _request_refresh(window, controller, run_paths)
)
window.preview_requested.connect(controller.refresh_plan)
window.apply_requested.connect(controller.apply)
history_page = HistoryPage()
window.set_page(6, history_page, "操作历史")
history_controller = None
if run_store is not None and run_paths is not None:
history_controller = HistoryController(
history_page,
run_store=run_store,
run_paths=run_paths,
)
history_controller.status_changed.connect(
lambda state: window.operation_status.setText(_status_text(state))
)
history_controller.restore_failed.connect(
lambda message: _report_error(window, "恢复位号失败", message)
)
window.history_controller = history_controller
property_change_page = PropertyChangePage()
property_change_controller = PropertyChangeController(
property_change_page,
run_store=run_store,
run_paths=run_paths,
)
property_change_controller.can_apply_changed.connect(
property_change_page.set_can_apply
)
property_change_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
)
property_change_controller.apply_failed.connect(
lambda message: _report_error(window, "应用属性修改失败", message)
)
window.set_page(1, property_change_page, "属性批改")
window.property_change_controller = property_change_controller
property_visibility_page = PropertyVisibilityPage()
property_visibility_controller = PropertyVisibilityController(
property_visibility_page,
run_store=run_store,
run_paths=run_paths,
)
property_visibility_controller.can_apply_changed.connect(
property_visibility_page.set_can_apply
)
property_visibility_controller.apply_completed.connect(
lambda state: window.operation_status.setText(_status_text(state))
)
property_visibility_controller.apply_failed.connect(
lambda message: _report_error(window, "应用显示状态失败", message)
)
window.set_page(2, property_visibility_page, "属性显示")
window.property_visibility_controller = property_visibility_controller
inspection_page = InspectionPage()
inspection_controller = InspectionController(
inspection_page,
run_paths=run_paths,
)
inspection_controller.status_changed.connect(window.operation_status.setText)
window.set_page(3, inspection_page, "设计检查")
window.inspection_controller = inspection_controller
bom_page = BomPage()
bom_controller = BomController(
bom_page,
run_paths=run_paths,
template_path=_tool_root() / "templates" / "BOM模板.xls",
design_name=(
Path(snapshot.design_path).name if snapshot is not None else ""
),
)
bom_controller.status_changed.connect(window.operation_status.setText)
bom_controller.export_failed.connect(
lambda message: _report_error(window, "BOM 导出失败", message)
)
bom_controller.export_completed.connect(
lambda path: window.operation_status.setText(f"BOM 已导出:{path}")
)
window.set_page(5, bom_page, "BOM 工具")
window.bom_controller = bom_controller
settings_controller = SettingsController()
settings_page = SettingsPage(current_version=__version__)
persisted_settings = settings_controller.load_settings()
settings_page.source_input.setText(str(persisted_settings["source"]))
channel_index = settings_page.channel_combo.findData(persisted_settings["channel"])
if channel_index >= 0:
settings_page.channel_combo.setCurrentIndex(channel_index)
settings_page.auto_check_checkbox.setChecked(bool(persisted_settings["auto_check"]))
settings_page.check_requested.connect(settings_controller.check_updates)
settings_page.download_requested.connect(settings_controller.stage_update)
settings_controller.check_started.connect(settings_page.set_checking)
settings_controller.check_finished.connect(settings_page.show_result)
settings_controller.check_finished.connect(lambda _result: settings_controller.record_check())
settings_controller.stage_finished.connect(settings_page.show_stage_result)
settings_page.install_requested.connect(settings_controller.request_install)
settings_controller.install_requested.connect(
lambda manifest: _launch_update(window, settings_controller, manifest)
)
settings_page.source_input.editingFinished.connect(
lambda: settings_controller.save_settings(
settings_page.source_input.text(),
settings_page.channel_combo.currentData(),
settings_page.auto_check_checkbox.isChecked(),
)
)
settings_page.channel_combo.currentIndexChanged.connect(
lambda: settings_controller.save_settings(
settings_page.source_input.text(),
settings_page.channel_combo.currentData(),
settings_page.auto_check_checkbox.isChecked(),
)
)
settings_page.auto_check_checkbox.toggled.connect(
lambda: settings_controller.save_settings(
settings_page.source_input.text(),
settings_page.channel_combo.currentData(),
settings_page.auto_check_checkbox.isChecked(),
)
)
window.set_page(7, settings_page, "设置")
window.settings_controller = settings_controller
window.settings_page = settings_page
if settings_controller.auto_check_due(persisted_settings):
QTimer.singleShot(
0,
lambda: settings_page.check_requested.emit(
settings_page.source_input.text().strip(), settings_page.channel_combo.currentData()
),
)
if snapshot is not None:
window.project_label.setText(Path(snapshot.design_path).name or snapshot.design_id)
window.bridge_status.setText("桥接已连接")
controller.load_snapshot(snapshot)
if window.property_change_controller is not None:
window.property_change_controller.load_snapshot(snapshot)
if window.property_visibility_controller is not None:
window.property_visibility_controller.load_snapshot(snapshot)
if window.inspection_controller is not None:
window.inspection_controller.load_snapshot(snapshot)
if window.bom_controller is not None:
window.bom_controller.load_snapshot(snapshot)
if history_controller is not None:
history_controller.load_snapshot(snapshot)
if run_paths is not None:
watcher = _install_snapshot_watcher(window, request_path, run_paths)
if watcher is not None and history_controller is not None:
watcher.snapshot_reloaded.connect(
lambda _snapshot: history_controller.refresh()
)
window.navigation.setCurrentRow(0)
window.pages.setCurrentIndex(0)
window.page_title.setText("自动位号")
return window
def _request_refresh(
window: MainWindow,
controller: RefDesController,
run_paths: RunPaths | None,
) -> None:
if run_paths is None:
controller.refresh_plan()
return
refresh_request = run_paths.root / "refresh.request"
try:
refresh_request.write_text("snapshot\n", encoding="utf-8")
window.operation_status.setText("已请求宿主刷新设计快照…")
except OSError as error:
_report_error(window, "刷新失败", str(error))
class _SnapshotWatcher(QObject):
snapshot_reloaded = Signal(object)
def __init__(self, window: MainWindow, request_path: Path) -> None:
super().__init__(window)
self._window = window
self._request_path = request_path
self._last_mtime: float | None = None
self._timer = QTimer(self)
self._timer.setInterval(1000)
self._timer.timeout.connect(self._check)
self._timer.start()
self._check(silent=True)
def _check(self, silent: bool = False) -> None:
try:
mtime = self._request_path.stat().st_mtime
except OSError:
return
if self._last_mtime is None:
self._last_mtime = mtime
return
if mtime == self._last_mtime:
return
self._last_mtime = mtime
try:
snapshot = load_request(self._request_path)
except Exception as error:
if not silent:
_report_error(
self._window, "设计快照刷新失败", str(error)
)
return
if self._window.refdes_controller is not None:
self._window.refdes_controller.load_snapshot(snapshot)
self.snapshot_reloaded.emit(snapshot)
self._window.operation_status.setText("设计快照已刷新")
def _install_snapshot_watcher(
window: MainWindow, request_path: Path, run_paths: RunPaths
) -> _SnapshotWatcher | None:
try:
return _SnapshotWatcher(window, request_path)
except RuntimeError:
return None
def _report_error(window: MainWindow, title: str, message: str) -> None:
window.operation_status.setText(f"{title}:{message}")
QMessageBox.warning(window, title, message)
def _install_excepthook() -> None:
def _hook(exc_type, exc_value, exc_traceback) -> None:
sys.__excepthook__(exc_type, exc_value, exc_traceback)
window = QApplication.activeWindow()
message = "".join(
traceback.format_exception_only(exc_type, exc_value)
).strip()
if window is not None:
QMessageBox.critical(window, "程序异常", message)
sys.excepthook = _hook
def _tool_root() -> Path:
configured = os.environ.get("DXTOOLS_HOME")
if configured:
return Path(configured)
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parents[3] / "integration" / "dxdesigner795"
def _launch_update(window: MainWindow, controller: SettingsController, manifest: object) -> None:
"""Write a post-exit install plan and hand control to the portable updater."""
staged_zip = controller.staged_path(manifest)
if staged_zip is None or not staged_zip.is_file():
window.operation_status.setText("更新包尚未准备好,请重新检查")
return
if not getattr(sys, "frozen", False):
window.operation_status.setText("开发运行环境已完成校验,便携式包中可执行安装")
return
from dx_productivity.update.installer import InstallPlan
current_root = Path(sys.executable).resolve().parent
update_root = Path(os.environ.get("LOCALAPPDATA", current_root)) / "DxProductivity" / "updates"
update_root.mkdir(parents=True, exist_ok=True)
plan_path = update_root / "install-plan.json"
executable = current_root / "DxDesignerTools.exe"
plan = InstallPlan(
current_root=current_root,
staged_zip=staged_zip,
backup_root=update_root / "backups",
restart_command=(str(executable), "ui", "--smoke-test-ms", "1000"),
sha256=str(getattr(manifest, "sha256", "") or "") or None,
)
temporary = plan_path.with_suffix(f".{uuid.uuid4().hex[:8]}.tmp")
temporary.write_text(json.dumps(plan.to_mapping(), ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(plan_path)
try:
subprocess.Popen(
[str(executable), "update", "--plan", str(plan_path)],
cwd=str(current_root),
close_fds=True,
)
except OSError as error:
window.operation_status.setText(f"无法启动更新器:{error}")
return
window.operation_status.setText(f"已确认安装 {manifest.version},程序即将退出更新")
application = QApplication.instance()
if application is not None:
application.quit()
def main(argv: Sequence[str] | None = None) -> int:
arguments = list(sys.argv[1:] if argv is None else argv)
parser = build_parser()
options = parser.parse_args(arguments)
if options.smoke_test_ms is not None and options.smoke_test_ms <= 0:
parser.error("--smoke-test-ms must be positive")
_install_excepthook()
app = create_application([sys.argv[0], *arguments])
window = create_main_window(options.request)
window.show()
if options.feature is not None:
index = FEATURE_PAGE_INDEX[options.feature]
window.set_active_page(index)
if options.smoke_test_ms is not None:
QTimer.singleShot(options.smoke_test_ms, app.quit)
return app.exec()
+135
View File
@@ -0,0 +1,135 @@
"""Controller for the native BOM export page."""
from __future__ import annotations
import json
import time
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from dx_productivity.bridge.protocol import atomic_write_text
from dx_productivity.bridge.run_store import RunPaths
from dx_productivity.domain.models import DesignSnapshot
from dx_productivity.features.bom import BOMResult, BOMSettings, build_bom
from dx_productivity.ui.bom_page import BomPage
class BomController(QObject):
status_changed = Signal(str)
export_failed = Signal(str)
export_completed = Signal(str)
def __init__(
self,
page: BomPage,
*,
run_paths: RunPaths | None = None,
template_path: Path | None = None,
design_name: str = "",
) -> None:
super().__init__(page)
self.page = page
self.run_paths = run_paths
self.template_path = template_path
self.design_name = design_name
self.snapshot: DesignSnapshot | None = None
self._result: BOMResult | None = None
self._export_in_flight = False
self._export_started_at = 0.0
self._status_timer = QTimer(self)
self._status_timer.setInterval(300)
self._status_timer.timeout.connect(self._poll_export_status)
page.settings_changed.connect(self.refresh_preview)
page.export_requested.connect(self.export_to)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.refresh_preview()
def refresh_preview(self) -> None:
if self.snapshot is None:
return
try:
self._result = build_bom(self.snapshot, self.page.settings())
except ValueError as error:
self.page.set_summary(str(error))
self.page.set_can_export(False)
return
self.page.set_result(self._result)
self.page.set_can_export(bool(self._result.rows))
def export_to(self, output_path: str) -> None:
if self._export_in_flight:
return
if self.run_paths is None:
raise RuntimeError("BOM export requires a bridge mailbox")
if self._result is None or not self._result.rows:
raise RuntimeError("BOM preview is empty")
if self.template_path is None or not self.template_path.is_file():
raise RuntimeError(f"BOM 模板不存在:{self.template_path}")
self._export_in_flight = True
self._export_started_at = time.monotonic()
payload = self._build_payload(output_path)
atomic_write_text(
self.run_paths.root / "bom-export.json",
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
)
self._status_timer.start()
def _build_payload(self, output_path: str) -> dict[str, object]:
assert self._result is not None
records: list[str] = []
for page, rows in self._result.sections:
records.append(f"S|{'' if page is None else page}")
for row in rows:
flags = f"{'D' if row.duplicate_refdes else ''}{'' }"
flags = ("D" if row.duplicate_refdes else "") + (
"M" if row.part_number_mismatch else ""
)
records.append(
"R|{qty}|{refdes}|{pn}|{desc}|{flags}".format(
qty=row.qty,
refdes=row.refdes.replace("|", " "),
pn=row.part_number.replace("|", " "),
desc=row.description.replace("|", " "),
flags=flags,
)
)
return {
"template_path": str(self.template_path),
"output_path": output_path,
"design_name": self.design_name,
"description_header": (
"VALUE"
if self.page.settings().description_source == "value"
else "PART LABEL"
),
"records": "\n".join(records),
}
def _poll_export_status(self) -> None:
if self.run_paths is None:
return
status_path = self.run_paths.root / "bom-export-status.json"
if not status_path.exists():
if time.monotonic() - self._export_started_at > 120:
self._fail_export("宿主未响应 BOM 导出请求")
return
self._status_timer.stop()
self._export_in_flight = False
try:
data = json.loads(status_path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError) as error:
self.export_failed.emit(str(error))
return
if data.get("state") == "ok":
self.export_completed.emit(str(data.get("output_path", "")))
self.status_changed.emit("BOM 已导出,Excel 已打开")
else:
self.export_failed.emit(str(data.get("error") or "BOM 导出失败"))
def _fail_export(self, message: str) -> None:
self._status_timer.stop()
self._export_in_flight = False
self.export_failed.emit(message)
+164
View File
@@ -0,0 +1,164 @@
"""BOM export page (legacy Bom.efm, natively computed)."""
from __future__ import annotations
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QFileDialog,
QHBoxLayout,
QLabel,
QPushButton,
QRadioButton,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.features.bom import BOMResult, BOMSettings
class BomPage(QWidget):
export_requested = Signal(str)
settings_changed = Signal()
def __init__(self) -> None:
super().__init__()
self._build_ui()
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"BOM 导出:按页分组、合并同料号、NC 过滤与创维料号校验全部在本地完成;"
"点击导出后由 DxDesigner 宿主调用 Excel 按模板输出。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
options = QHBoxLayout()
options.addWidget(QLabel("范围"))
self.full_button = QRadioButton("整个工程")
self.full_button.setChecked(True)
self.current_sheet_button = QRadioButton("当前页")
self.selected_button = QRadioButton("选中器件")
for button in (
self.full_button,
self.current_sheet_button,
self.selected_button,
):
options.addWidget(button)
options.addWidget(QLabel("描述来源"))
self.description_combo = QComboBox()
self.description_combo.addItem("Value", "value")
self.description_combo.addItem("Part Label", "part-label")
options.addWidget(self.description_combo)
self.nc_checkbox = QCheckBox("剔除 NC 器件")
options.addWidget(self.nc_checkbox)
options.addStretch(1)
layout.addLayout(options)
self.model = QStandardItemModel(0, 6, self)
self.model.setHorizontalHeaderLabels(
("页", "数量", "位号", "料号", "描述", "校验")
)
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
layout.addWidget(self.table, 1)
self.summary_label = QLabel("")
self.summary_label.setObjectName("secondaryLabel")
self.summary_label.setWordWrap(True)
layout.addWidget(self.summary_label)
actions = QHBoxLayout()
actions.addStretch(1)
self.export_button = QPushButton("导出 Excel…")
self.export_button.setObjectName("primaryButton")
self.export_button.setEnabled(False)
self.export_button.clicked.connect(self._emit_export)
actions.addWidget(self.export_button)
layout.addLayout(actions)
for button in (self.full_button, self.current_sheet_button, self.selected_button):
button.toggled.connect(self.settings_changed)
self.description_combo.currentIndexChanged.connect(self.settings_changed)
self.nc_checkbox.toggled.connect(self.settings_changed)
def _emit_export(self) -> None:
path, _ = QFileDialog.getSaveFileName(
self,
"导出 BOM",
"BOM导出.xls",
"Excel 工作簿 (*.xls *.xlsx)",
)
if path:
self.export_requested.emit(path)
def settings(self) -> BOMSettings:
if self.current_sheet_button.isChecked():
scope = "current-sheet"
elif self.selected_button.isChecked():
scope = "selected"
else:
scope = "full"
return BOMSettings(
scope=scope,
description_source=self.description_combo.currentData() or "value",
exclude_nc=self.nc_checkbox.isChecked(),
)
def set_result(self, result: BOMResult) -> None:
self.model.setRowCount(0)
for page, rows in result.sections:
page_item = QStandardItem(f"第 {page} 页" if page is not None else "未编号")
page_item.setEditable(False)
self.model.appendRow(
(
page_item,
QStandardItem(""),
QStandardItem(""),
QStandardItem(""),
QStandardItem(""),
QStandardItem(""),
)
)
for row in rows:
flags: list[str] = []
if row.duplicate_refdes:
flags.append("位号重复")
if row.part_number_mismatch:
flags.append(f"料号校验:{row.mismatch_reason}")
self.model.appendRow(
(
_read_only(""),
_read_only(str(row.qty)),
_read_only(row.refdes),
_read_only(row.part_number),
_read_only(row.description),
_read_only(";".join(flags)),
)
)
summary = f"BOM 行数:{len(result.rows)}"
if result.excluded_count:
summary += f";NC 剔除:{result.excluded_count} 个器件"
self.summary_label.setText(summary)
def set_summary(self, text: str) -> None:
self.summary_label.setText(text)
def set_can_export(self, enabled: bool) -> None:
self.export_button.setEnabled(enabled)
def _read_only(text: str) -> QStandardItem:
item = QStandardItem(text)
item.setEditable(False)
return item
@@ -0,0 +1,167 @@
"""Publish verified restore transactions from operation history."""
from __future__ import annotations
import time
from collections.abc import Callable
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from PySide6.QtWidgets import QMessageBox
from dx_productivity.bridge.protocol import (
load_apply_status,
schedule_sha256,
write_apply_request,
write_schedule,
)
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import (
AnnotationPlan,
ApplyRequest,
DesignSnapshot,
HistoryEntry,
RunPaths,
)
from dx_productivity.domain.restore import build_restore_plan
from dx_productivity.ui.history_page import HistoryPage
from dx_productivity.ui.polling import watchdog_failure
ConfirmRestore = Callable[[HistoryEntry, int], bool]
class HistoryController(QObject):
status_changed = Signal(str)
restore_failed = Signal(str)
def __init__(
self,
page: HistoryPage,
*,
run_store: RunStore,
run_paths: RunPaths,
confirm_restore: ConfirmRestore | None = None,
) -> None:
super().__init__(page)
self.page = page
self.run_store = run_store
self.run_paths = run_paths
self.confirm_restore = confirm_restore or self._confirm_restore
self.snapshot: DesignSnapshot | None = None
self.pending_plan: AnnotationPlan | None = None
self.pending_backup: Path | None = None
self._status_recorded = False
self._restore_in_flight = False
self._restore_started_at = 0.0
self._timer = QTimer(self)
self._timer.setInterval(200)
self._timer.timeout.connect(self._poll_status)
self.page.restore_requested.connect(self.restore_latest)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.refresh()
def refresh(self) -> None:
if self.snapshot is None:
self.page.set_entries(())
return
self.page.set_entries(
self.run_store.list_history(self.snapshot.design_id)
)
def restore_latest(self) -> Path | None:
if self._restore_in_flight:
return None
if self.snapshot is None:
raise RuntimeError("restore requires a live design snapshot")
entry = self.page.selected_entry()
if entry is None:
raise RuntimeError("no history entry is selected")
if entry.backup_path is None:
raise RuntimeError("selected history entry has no backup")
request = self.run_store.build_restore_settings(entry)
plan = build_restore_plan(self.snapshot, request)
if not plan.can_apply:
raise RuntimeError("selected history entry cannot be restored")
changed_count = sum(row.changed for row in plan.rows)
if not self.confirm_restore(entry, changed_count):
return None
self._restore_in_flight = True
self._restore_started_at = time.monotonic()
self.pending_plan = plan
self.pending_backup = self.run_store.write_backup(self.snapshot, plan)
self._clear_previous_mailbox()
write_apply_request(
self.run_paths.apply_request,
ApplyRequest(
format_version=self.snapshot.format_version,
run_id=self.snapshot.run_id,
snapshot_id=self.snapshot.snapshot_id,
backup_path=self.pending_backup.resolve(),
schedule_sha256=schedule_sha256(plan.schedule),
),
)
write_schedule(self.run_paths.result, plan.schedule)
self._status_recorded = False
self._timer.start()
return self.run_paths.result
def stop(self) -> None:
self._timer.stop()
def _clear_previous_mailbox(self) -> None:
for path in (
self.run_paths.apply_status,
self.run_paths.apply_request,
self.run_paths.result,
):
path.unlink(missing_ok=True)
def _poll_status(self) -> None:
if not self.run_paths.apply_status.exists():
self._check_watchdog()
return
self._timer.stop()
self._restore_in_flight = False
try:
status = load_apply_status(self.run_paths.apply_status)
except Exception as exc:
self.restore_failed.emit(str(exc))
self.refresh()
return
if not self._status_recorded:
self._status_recorded = True
try:
self.run_store.record_status(
status,
design_id=self.snapshot.design_id if self.snapshot else None,
)
except Exception:
pass
self.status_changed.emit(status.state)
self.refresh()
def _check_watchdog(self) -> None:
failure = watchdog_failure(self._restore_started_at, self.run_paths.root)
if failure is not None:
self._fail_restore(failure)
def _fail_restore(self, message: str) -> None:
self._timer.stop()
self._restore_in_flight = False
self.restore_failed.emit(message)
def _confirm_restore(self, entry: HistoryEntry, changed_count: int) -> bool:
answer = QMessageBox.question(
self.page,
"恢复上次位号",
(
f"将恢复 {changed_count} 个器件的位号。\n"
f"备份时间:{entry.timestamp.astimezone():%Y-%m-%d %H:%M:%S}"
),
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
QMessageBox.StandardButton.Cancel,
)
return answer is QMessageBox.StandardButton.Yes
+117
View File
@@ -0,0 +1,117 @@
"""Operation history and verified restore controls."""
from __future__ import annotations
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QAbstractItemView,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.domain.models import HistoryEntry
from dx_productivity.ui.theme import Theme, themed_icon
class HistoryPage(QWidget):
restore_requested = Signal()
def __init__(self) -> None:
super().__init__()
self._entries: tuple[HistoryEntry, ...] = ()
self._build_ui()
def set_entries(self, entries: tuple[HistoryEntry, ...]) -> None:
self._entries = tuple(
sorted(entries, key=lambda entry: entry.timestamp, reverse=True)
)
self.model.removeRows(0, self.model.rowCount())
for entry in self._entries:
values = (
entry.timestamp.astimezone().strftime("%Y-%m-%d %H:%M:%S"),
_state_text(entry.state),
str(entry.changed_count),
entry.design_id,
str(entry.backup_path),
)
items = [QStandardItem(value) for value in values]
for item in items:
item.setEditable(False)
self.model.appendRow(items)
if self._entries:
self.table.selectRow(0)
self._update_restore_state()
def selected_entry(self) -> HistoryEntry | None:
indexes = self.table.selectionModel().selectedRows()
if not indexes:
return None
row = indexes[0].row()
if 0 <= row < len(self._entries):
return self._entries[row]
return None
def row_run_id(self, row: int) -> str:
return self._entries[row].run_id
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 18, 20, 18)
layout.setSpacing(12)
toolbar = QHBoxLayout()
title = QLabel("操作历史")
title.setObjectName("pageTitle")
toolbar.addWidget(title)
toolbar.addStretch(1)
self.restore_button = QPushButton("恢复上次位号")
self.restore_button.setIcon(
themed_icon("fa6s.clock-rotate-left", Theme.LIGHT)
)
self.restore_button.setEnabled(False)
self.restore_button.clicked.connect(self.restore_requested)
toolbar.addWidget(self.restore_button)
layout.addLayout(toolbar)
self.model = QStandardItemModel(0, 5, self)
self.model.setHorizontalHeaderLabels(
("时间", "结果", "变更数", "设计", "备份文件")
)
self.table = QTableView()
self.table.setModel(self.model)
self.table.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows
)
self.table.setSelectionMode(
QAbstractItemView.SelectionMode.SingleSelection
)
self.table.setAlternatingRowColors(True)
self.table.verticalHeader().setVisible(False)
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
self.table.selectionModel().selectionChanged.connect(
self._update_restore_state
)
layout.addWidget(self.table, 1)
def _update_restore_state(self, *_args) -> None:
self.restore_button.setEnabled(self.selected_entry() is not None)
def _state_text(state: str) -> str:
return {
"applied": "已应用",
"rolled-back": "已回滚",
"rollback-failed": "回滚失败",
"rejected": "已拒绝",
}.get(state, state)
@@ -0,0 +1,118 @@
"""Controller for the read-only design inspection page."""
from __future__ import annotations
from PySide6.QtCore import QObject, Signal
from dx_productivity.bridge.protocol import atomic_write_text
from dx_productivity.bridge.run_store import RunPaths
from dx_productivity.domain.models import DesignSnapshot
from dx_productivity.features.inspection import (
InspectionRow,
missing_attribute_values,
net_cross_page,
net_list,
solitary_nets,
)
from dx_productivity.ui.inspection_page import InspectionPage
class InspectionController(QObject):
status_changed = Signal(str)
def __init__(
self,
page: InspectionPage,
*,
run_paths: RunPaths | None = None,
) -> None:
super().__init__(page)
self.page = page
self.run_paths = run_paths
self.snapshot: DesignSnapshot | None = None
page.solitary_requested.connect(self.show_solitary)
page.net_list_requested.connect(self.show_net_list)
page.value_miss_requested.connect(self.show_value_miss)
page.cross_page_requested.connect(self.show_cross_page)
page.locate_net_requested.connect(self.locate_net)
page.locate_component_requested.connect(self.locate_component)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
def _require_snapshot(self) -> DesignSnapshot:
if self.snapshot is None:
raise RuntimeError("inspection requires a live design snapshot")
return self.snapshot
def show_solitary(self) -> None:
snapshot = self._require_snapshot()
if not net_data_available(snapshot):
self.page.show_no_net_data()
return
rows = solitary_nets(snapshot)
self.page.set_rows(rows, f"孤立网络:{len(rows)} 个")
def show_net_list(self) -> None:
snapshot = self._require_snapshot()
if not net_data_available(snapshot):
self.page.show_no_net_data()
return
rows = net_list(snapshot)
self.page.set_rows(rows, f"网络总数:{len(rows)}")
def show_value_miss(self, attribute_name: str) -> None:
snapshot = self._require_snapshot()
rows = missing_attribute_values(
snapshot,
attribute_name,
include_missing=self.page.include_missing(),
)
self.page.set_rows(
rows, f"{attribute_name} 遗漏:{len(rows)} 个器件"
)
def show_cross_page(self, net_name: str) -> None:
snapshot = self._require_snapshot()
if not net_data_available(snapshot):
self.page.show_no_net_data()
return
name = net_name.strip()
if not name:
self.page.set_rows([], "请输入网络名")
return
rows = net_cross_page(snapshot, name)
if not rows:
self.page.set_rows([], f"未找到网络:{name}")
return
self.page.set_rows(
rows,
f"{name} 出现在 {len(rows)} 页",
)
def locate_net(self, net_name: str, page: int) -> None:
if self.run_paths is None:
return
safe_name = net_name.replace("\t", " ").replace("\r", " ").replace(
"\n", " "
)
if not safe_name:
return
atomic_write_text(
self.run_paths.locate, f"net|{safe_name}|{page}\n"
)
self.status_changed.emit(f"已请求定位网络:{safe_name}")
def locate_component(self, bridge_id: str) -> None:
if self.run_paths is None:
return
if any(char in bridge_id for char in "\t\r\n") or not bridge_id:
raise ValueError("invalid bridge ID")
atomic_write_text(self.run_paths.locate, f"{bridge_id}\n")
self.status_changed.emit(f"已请求定位器件:{bridge_id}")
def net_data_available(snapshot: DesignSnapshot) -> bool:
from dx_productivity.features.inspection import has_net_data
return has_net_data(snapshot)
+131
View File
@@ -0,0 +1,131 @@
"""Design inspection page (legacy NET_CHECK tools, read-only)."""
from __future__ import annotations
from PySide6.QtCore import Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QCheckBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.features.inspection import InspectionRow
class InspectionPage(QWidget):
solitary_requested = Signal()
net_list_requested = Signal()
value_miss_requested = Signal(str)
cross_page_requested = Signal(str)
locate_net_requested = Signal(str, int)
locate_component_requested = Signal(str)
def __init__(self) -> None:
super().__init__()
self._rows: list[InspectionRow] = []
self._build_ui()
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"只读设计检查:孤立网络、网络列表、属性遗漏。"
"双击结果行可在原理图中定位。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
buttons_row = QHBoxLayout()
self.solitary_button = QPushButton("孤立网络检查")
self.net_list_button = QPushButton("全部网络列表")
self.value_miss_button = QPushButton("Value 遗漏")
self.value1_miss_button = QPushButton("Value1 遗漏")
for button in (
self.solitary_button,
self.net_list_button,
self.value_miss_button,
self.value1_miss_button,
):
buttons_row.addWidget(button)
self.include_missing_checkbox = QCheckBox("属性缺失也算遗漏")
buttons_row.addWidget(self.include_missing_checkbox)
buttons_row.addStretch(1)
layout.addLayout(buttons_row)
search_row = QHBoxLayout()
search_row.addWidget(QLabel("跨页互动"))
self.net_name_edit = QLineEdit()
self.net_name_edit.setPlaceholderText("输入网络名,查看其所有页分布")
search_row.addWidget(self.net_name_edit, 1)
self.cross_page_button = QPushButton("查询")
search_row.addWidget(self.cross_page_button)
layout.addLayout(search_row)
self.model = QStandardItemModel(0, 4, self)
self.model.setHorizontalHeaderLabels(("检查项", "名称", "页号", "说明"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(380)
self.table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
self.table.doubleClicked.connect(self._on_double_click)
layout.addWidget(self.table, 1)
self.summary_label = QLabel("")
self.summary_label.setObjectName("secondaryLabel")
layout.addWidget(self.summary_label)
self.solitary_button.clicked.connect(self.solitary_requested)
self.net_list_button.clicked.connect(self.net_list_requested)
self.value_miss_button.clicked.connect(
lambda: self.value_miss_requested.emit("Value")
)
self.value1_miss_button.clicked.connect(
lambda: self.value_miss_requested.emit("Value1")
)
self.cross_page_button.clicked.connect(
lambda: self.cross_page_requested.emit(self.net_name_edit.text())
)
def include_missing(self) -> bool:
return self.include_missing_checkbox.isChecked()
def _on_double_click(self, index) -> None:
row = index.row()
if 0 <= row < len(self._rows):
self._locate(self._rows[row])
def _locate(self, row: InspectionRow) -> None:
if row.locate_net and row.pages:
self.locate_net_requested.emit(row.name, row.pages[0])
elif row.locate_bridge_id:
self.locate_component_requested.emit(row.locate_bridge_id)
def set_rows(self, rows: list[InspectionRow], summary: str) -> None:
self._rows = rows
self.model.setRowCount(0)
for row in rows:
pages_text = "、".join(str(page) for page in row.pages) or "—"
kind_item = QStandardItem(row.kind)
kind_item.setEditable(False)
name_item = QStandardItem(row.name)
name_item.setEditable(False)
page_item = QStandardItem(pages_text)
page_item.setEditable(False)
detail_item = QStandardItem(row.detail)
detail_item.setEditable(False)
self.model.appendRow((kind_item, name_item, page_item, detail_item))
self.summary_label.setText(summary)
def show_no_net_data(self) -> None:
self.set_rows(
[], "当前快照未包含网络数据,请在宿主重新刷新设计快照。"
)
+242
View File
@@ -0,0 +1,242 @@
"""Shared productivity-suite window shell."""
from __future__ import annotations
from PySide6.QtCore import QSize, Qt, Signal
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QListWidget,
QListWidgetItem,
QMainWindow,
QPushButton,
QApplication,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from dx_productivity import __version__
from dx_productivity.ui.theme import Theme, apply_theme, themed_icon, theme_tokens
NAVIGATION = (
("自动位号", "fa6s.hashtag"),
("属性批改", "fa6s.pen"),
("属性显示", "fa6s.tag"),
("设计检查", "fa6s.clipboard-check"),
("网络工具", "fa6s.share-nodes"),
("BOM 工具", "fa6s.table"),
("操作历史", "fa6s.clock-rotate-left"),
("设置", "fa6s.gear"),
)
class MainWindow(QMainWindow):
refresh_requested = Signal()
preview_requested = Signal()
apply_requested = Signal()
page_changed = Signal(int)
def __init__(self, *, theme: Theme = Theme.LIGHT) -> None:
super().__init__()
self.theme = theme
self.setWindowTitle("一叶知秋_重构版")
self.setMinimumSize(1100, 700)
self.resize(1240, 780)
self._build_ui()
self._refresh_icons()
application = QApplication.instance()
if application is not None:
apply_theme(application, self.theme)
def navigation_items(self) -> list[str]:
return [self.navigation.item(index).text() for index in range(self.navigation.count())]
def set_page(self, index: int, widget: QWidget, title: str) -> None:
previous = self.pages.widget(index)
self.pages.removeWidget(previous)
previous.deleteLater()
self.pages.insertWidget(index, widget)
self.pages.setCurrentIndex(index)
self.page_title.setText(title)
def set_active_page(self, index: int) -> None:
if 0 <= index < self.pages.count():
self.navigation.setCurrentRow(index)
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
def closeEvent(self, event) -> None:
for controller in (
getattr(self, "settings_controller", None),
getattr(self, "refdes_controller", None),
getattr(self, "history_controller", None),
):
shutdown = getattr(controller, "shutdown", None)
if callable(shutdown):
shutdown()
super().closeEvent(event)
def _build_ui(self) -> None:
root = QWidget()
root.setObjectName("appRoot")
root_layout = QVBoxLayout(root)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
root_layout.addWidget(self._build_title_bar())
body = QWidget()
body_layout = QHBoxLayout(body)
body_layout.setContentsMargins(0, 0, 0, 0)
body_layout.setSpacing(0)
body_layout.addWidget(self._build_navigation())
body_layout.addWidget(self._build_content(), 1)
root_layout.addWidget(body, 1)
root_layout.addWidget(self._build_status_strip())
self.setCentralWidget(root)
def _build_title_bar(self) -> QFrame:
bar = QFrame()
bar.setObjectName("titleBar")
bar.setFixedHeight(52)
layout = QHBoxLayout(bar)
layout.setContentsMargins(18, 0, 14, 0)
layout.setSpacing(10)
brand = QLabel("一叶知秋_重构版")
self.brand_label = brand
brand.setObjectName("brandLabel")
layout.addWidget(brand)
self.project_label = QLabel("未连接设计")
self.project_label.setObjectName("projectLabel")
layout.addWidget(self.project_label)
layout.addStretch(1)
self.theme_button = self._tool_button("切换明暗主题")
self.theme_button.clicked.connect(self._toggle_theme)
layout.addWidget(self.theme_button)
self.refresh_button = self._tool_button("刷新设计快照")
self.refresh_button.clicked.connect(self.refresh_requested)
layout.addWidget(self.refresh_button)
self.preview_button = self._tool_button("生成预览")
self.preview_button.clicked.connect(self.preview_requested)
layout.addWidget(self.preview_button)
self.apply_button = QPushButton("应用位号")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setMinimumWidth(112)
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
layout.addWidget(self.apply_button)
return bar
def _build_navigation(self) -> QFrame:
rail = QFrame()
rail.setObjectName("navigationRail")
rail.setFixedWidth(218)
layout = QVBoxLayout(rail)
layout.setContentsMargins(8, 10, 8, 10)
layout.setSpacing(6)
section = QLabel("工作台")
section.setObjectName("secondaryLabel")
layout.addWidget(section)
self.navigation = QListWidget()
self.navigation.setObjectName("navigationList")
self.navigation.setIconSize(QSize(16, 16))
self.navigation.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
for text, _ in NAVIGATION:
self.navigation.addItem(QListWidgetItem(text))
self.navigation.setCurrentRow(0)
self.navigation.currentRowChanged.connect(self._select_page)
layout.addWidget(self.navigation, 1)
version = QLabel(f"DxDesigner 7.9.5 · v{__version__}")
version.setObjectName("secondaryLabel")
layout.addWidget(version)
return rail
def _build_content(self) -> QWidget:
content = QWidget()
layout = QVBoxLayout(content)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
header = QFrame()
header.setObjectName("contentHeader")
header.setFixedHeight(58)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(20, 0, 20, 0)
self.page_title = QLabel(NAVIGATION[0][0])
self.page_title.setObjectName("pageTitle")
header_layout.addWidget(self.page_title)
header_layout.addStretch(1)
layout.addWidget(header)
self.pages = QStackedWidget()
for text, _ in NAVIGATION:
placeholder = QLabel(text)
placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
placeholder.setObjectName("secondaryLabel")
self.pages.addWidget(placeholder)
layout.addWidget(self.pages, 1)
return content
def _build_status_strip(self) -> QFrame:
strip = QFrame()
strip.setObjectName("statusStrip")
strip.setFixedHeight(32)
layout = QHBoxLayout(strip)
layout.setContentsMargins(14, 0, 14, 0)
self.bridge_status = QLabel("桥接待连接")
self.bridge_status.setObjectName("secondaryLabel")
layout.addWidget(self.bridge_status)
layout.addStretch(1)
self.operation_status = QLabel("就绪")
self.operation_status.setObjectName("secondaryLabel")
layout.addWidget(self.operation_status)
return strip
def _tool_button(self, label: str) -> QToolButton:
button = QToolButton()
button.setAccessibleName(label)
button.setToolTip(label)
button.setIconSize(QSize(16, 16))
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
return button
def _select_page(self, index: int) -> None:
if index < 0:
return
self.pages.setCurrentIndex(index)
self.page_title.setText(NAVIGATION[index][0])
self.page_changed.emit(index)
def _toggle_theme(self) -> None:
self.theme = Theme.DARK if self.theme is Theme.LIGHT else Theme.LIGHT
application = QApplication.instance()
if application is not None:
apply_theme(application, self.theme)
self._refresh_icons()
def _refresh_icons(self) -> None:
tokens = theme_tokens(self.theme)
self.theme_button.setIcon(
themed_icon(
"fa6s.sun" if self.theme is Theme.DARK else "fa6s.moon",
self.theme,
)
)
self.refresh_button.setIcon(themed_icon("fa6s.arrows-rotate", self.theme))
self.preview_button.setIcon(themed_icon("fa6s.eye", self.theme))
self.apply_button.setIcon(
themed_icon("fa6s.check", self.theme, color=tokens.accent_text)
)
for index, (_, icon_name) in enumerate(NAVIGATION):
self.navigation.item(index).setIcon(themed_icon(icon_name, self.theme))
for index in range(self.pages.count()):
page = self.pages.widget(index)
refresh_icons = getattr(page, "refresh_icons", None)
if refresh_icons is not None:
refresh_icons(self.theme)
+29
View File
@@ -0,0 +1,29 @@
"""Shared apply-transaction watchdog helpers for UI controllers."""
from __future__ import annotations
import time
from pathlib import Path
HEARTBEAT_MISSING_GRACE_SECONDS = 90.0
HEARTBEAT_ABSOLUTE_TIMEOUT_SECONDS = 1800.0
def watchdog_failure(started_at: float, run_root: Path) -> str | None:
"""Return a user-facing failure message when the host looks dead.
The host writes ``apply-progress.json`` roughly once per second while the
mailbox loop is alive. A missing heartbeat means an older host (or a dead
one); a present heartbeat only fails on the absolute cap because a long
apply legitimately pauses the loop.
"""
elapsed = time.monotonic() - started_at
progress = run_root / "apply-progress.json"
if progress.exists():
if elapsed > HEARTBEAT_ABSOLUTE_TIMEOUT_SECONDS:
return "宿主长时间未完成事务"
return None
if elapsed > HEARTBEAT_MISSING_GRACE_SECONDS:
return "未收到 DxDesigner 宿主的心跳,事务已中止"
return None
@@ -0,0 +1,193 @@
"""Controller for the native property-change feature page."""
from __future__ import annotations
import time
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from dx_productivity.bridge.protocol import (
atomic_write_text,
load_apply_status,
schedule_sha256,
write_apply_request,
write_schedule,
)
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import (
ApplyRequest,
DesignSnapshot,
RunPaths,
Severity,
)
from dx_productivity.features.property_change import (
PropertyChangeSettings,
build_property_change_plan,
)
from dx_productivity.ui.polling import watchdog_failure
from dx_productivity.ui.property_change_page import PropertyChangePage
class PropertyChangeController(QObject):
can_apply_changed = Signal(bool)
apply_completed = Signal(str)
apply_failed = Signal(str)
def __init__(
self,
page: PropertyChangePage,
*,
run_store: RunStore | None = None,
run_paths: RunPaths | None = None,
) -> None:
super().__init__(page)
self.page = page
self.run_store = run_store
self.run_paths = run_paths
self.snapshot: DesignSnapshot | None = None
self.can_apply = False
self._apply_in_flight = False
self._apply_started_at = 0.0
self._status_timer = QTimer(self)
self._status_timer.setInterval(200)
self._status_timer.timeout.connect(self._poll_apply_status)
page.settings_changed.connect(self.refresh_plan)
page.apply_requested.connect(self.apply)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self._fill_rows()
self.refresh_plan()
def _fill_rows(self) -> None:
if self.snapshot is None:
self.page.set_rows([], editable=False)
return
rows = [
(component.bridge_id, component.refdes or "(无位号)", "")
for component in self.snapshot.components
if component.selected
]
self.page.set_rows(rows, editable=True)
def refresh_plan(self) -> None:
if self._apply_in_flight or self.snapshot is None:
return
settings = self.page.settings()
if not settings.property_name:
self.page.set_issue_text("请选择或输入属性名")
self._set_can_apply(False)
return
plan = build_property_change_plan(self.snapshot, settings)
blocking = [
issue for issue in plan.issues if issue.severity is Severity.BLOCKING
]
warnings = [
issue
for issue in plan.issues
if issue.severity is not Severity.BLOCKING
]
texts = [f"[{issue.severity.value}] {issue.message}" for issue in blocking + warnings]
self.page.set_issue_text(";".join(texts[:8]))
self._set_can_apply(plan.can_apply)
def apply(self) -> Path:
if self._apply_in_flight:
raise RuntimeError("an apply transaction is already in flight")
if self.snapshot is None or self.run_store is None or self.run_paths is None:
raise RuntimeError("bridge mailbox is not configured")
settings = self.page.settings()
plan = build_property_change_plan(self.snapshot, settings)
if not plan.can_apply:
raise RuntimeError("property change plan is not applicable")
self._apply_in_flight = True
self._apply_started_at = time.monotonic()
changes = tuple(
change
for row in plan.rows
if row.changed
for change in (self._operation_change(row),)
)
backup = self.run_store.write_operation_backup(self.snapshot, changes)
for path in (
self.run_paths.apply_status,
self.run_paths.apply_request,
self.run_paths.result,
):
path.unlink(missing_ok=True)
write_apply_request(
self.run_paths.apply_request,
ApplyRequest(
format_version=self.snapshot.format_version,
run_id=self.snapshot.run_id,
snapshot_id=self.snapshot.snapshot_id,
backup_path=backup.resolve(),
schedule_sha256=schedule_sha256(plan.schedule),
),
)
write_schedule(self.run_paths.result, plan.schedule)
self._set_can_apply(False)
self._status_timer.start()
return self.run_paths.result
def _operation_change(self, row):
from dx_productivity.domain.models import OperationChange, OpType
by_bridge = {c.bridge_id: c for c in self.snapshot.components}
component = by_bridge[row.bridge_ids[0]]
current = ""
for attribute in component.attributes:
if attribute.name.casefold() == row.property_name.casefold():
current = attribute.value
break
return OperationChange(
bridge_id=component.bridge_id,
stable_uid=component.stable_uid,
full_path=component.full_path,
op=OpType.PROPERTY_VALUE,
property_name=row.property_name,
old_value=current,
new_value=row.new_refdes or "",
)
def locate(self, bridge_id: str) -> None:
if self.run_paths is None:
return
if any(char in bridge_id for char in "\t\r\n") or not bridge_id:
raise ValueError("invalid bridge ID")
atomic_write_text(self.run_paths.locate, f"{bridge_id}\n")
def _poll_apply_status(self) -> None:
if self.run_paths is None or not self.run_paths.apply_status.exists():
failure = watchdog_failure(self._apply_started_at, self.run_paths.root)
if failure is not None:
self._fail_apply(failure)
return
self._status_timer.stop()
self._apply_in_flight = False
try:
status = load_apply_status(self.run_paths.apply_status)
except Exception as exc:
self.apply_failed.emit(str(exc))
self.refresh_plan()
return
if self.run_store is not None:
try:
self.run_store.record_status(
status,
design_id=self.snapshot.design_id if self.snapshot else None,
)
except Exception:
pass
self.apply_completed.emit(status.state)
def _fail_apply(self, message: str) -> None:
self._status_timer.stop()
self._apply_in_flight = False
self.apply_failed.emit(message)
def _set_can_apply(self, enabled: bool) -> None:
if enabled != self.can_apply:
self.can_apply = enabled
self.can_apply_changed.emit(enabled)
@@ -0,0 +1,133 @@
"""Batch property value change page (legacy Value tools, natively)."""
from __future__ import annotations
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QComboBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.features.property_change import (
SUPPORTED_PROPERTIES,
PropertyChangeSettings,
)
class PropertyChangePage(QWidget):
apply_requested = Signal()
settings_changed = Signal()
def __init__(self) -> None:
super().__init__()
self._build_ui()
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"修改选中器件的属性值。先在 DxDesigner 中选中器件,"
"再为每个器件填写新值;没有该属性的器件会被跳过并在下方提示。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
selector_row = QHBoxLayout()
selector_row.addWidget(QLabel("属性"))
self.property_combo = QComboBox()
for name in SUPPORTED_PROPERTIES:
self.property_combo.addItem(name)
self.property_combo.addItem("自定义…")
selector_row.addWidget(self.property_combo)
self.custom_property_edit = QLineEdit()
self.custom_property_edit.setPlaceholderText("输入自定义属性名")
self.custom_property_edit.setVisible(False)
selector_row.addWidget(self.custom_property_edit, 1)
layout.addLayout(selector_row)
self.model = QStandardItemModel(0, 3, self)
self.model.setHorizontalHeaderLabels(("位号", "当前值", "新值"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
layout.addWidget(self.table, 1)
self.issue_label = QLabel("")
self.issue_label.setObjectName("secondaryLabel")
self.issue_label.setWordWrap(True)
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
actions.addStretch(1)
self.apply_button = QPushButton("应用属性修改")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
actions.addWidget(self.apply_button)
layout.addLayout(actions)
self.property_combo.currentIndexChanged.connect(
self._on_property_selected
)
self.custom_property_edit.textChanged.connect(self.settings_changed)
self.model.itemChanged.connect(lambda _item: self.settings_changed())
def _on_property_selected(self) -> None:
custom = self.property_name() is None
self.custom_property_edit.setVisible(custom)
self.settings_changed.emit()
def property_name(self) -> str | None:
"""Return the selected property, or None while custom text is empty."""
current = self.property_combo.currentText()
if current == "自定义…":
text = self.custom_property_edit.text().strip()
return text or None
return current
def settings(self) -> PropertyChangeSettings:
property_name = self.property_name()
overrides = tuple(
(
self.model.item(row, 0).data(Qt.ItemDataRole.UserRole) or "",
self.model.item(row, 2).text(),
)
for row in range(self.model.rowCount())
)
return PropertyChangeSettings(
property_name=property_name or "",
overrides=overrides,
)
def set_rows(
self, rows: list[tuple[str, str, str]], *, editable: bool
) -> None:
"""rows: (bridge_id, refdes, current_value)."""
self.model.blockSignals(True)
self.model.setRowCount(0)
for bridge_id, refdes, current in rows:
ref_item = QStandardItem(refdes)
ref_item.setData(bridge_id, Qt.ItemDataRole.UserRole)
ref_item.setEditable(False)
current_item = QStandardItem(current)
current_item.setEditable(False)
new_item = QStandardItem(current)
new_item.setEditable(editable)
self.model.appendRow((ref_item, current_item, new_item))
self.model.blockSignals(False)
def set_issue_text(self, text: str) -> None:
self.issue_label.setText(text)
def set_can_apply(self, enabled: bool) -> None:
self.apply_button.setEnabled(enabled)
@@ -0,0 +1,187 @@
"""Controller for the native attribute visibility page."""
from __future__ import annotations
import time
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from dx_productivity.bridge.protocol import (
load_apply_status,
schedule_sha256,
write_apply_request,
write_schedule,
)
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import (
ApplyRequest,
DesignSnapshot,
OperationChange,
OpType,
RunPaths,
Severity,
)
from dx_productivity.features.property_visibility import (
build_property_visibility_plan,
)
from dx_productivity.ui.polling import watchdog_failure
from dx_productivity.ui.property_visibility_page import PropertyVisibilityPage
class PropertyVisibilityController(QObject):
can_apply_changed = Signal(bool)
apply_completed = Signal(str)
apply_failed = Signal(str)
def __init__(
self,
page: PropertyVisibilityPage,
*,
run_store: RunStore | None = None,
run_paths: RunPaths | None = None,
) -> None:
super().__init__(page)
self.page = page
self.run_store = run_store
self.run_paths = run_paths
self.snapshot: DesignSnapshot | None = None
self.can_apply = False
self._apply_in_flight = False
self._apply_started_at = 0.0
self._status_timer = QTimer(self)
self._status_timer.setInterval(200)
self._status_timer.timeout.connect(self._poll_apply_status)
page.settings_changed.connect(self.refresh_plan)
page.apply_requested.connect(self.apply)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.refresh_plan()
def refresh_plan(self) -> None:
if self._apply_in_flight or self.snapshot is None:
return
settings = self.page.settings()
plan = build_property_visibility_plan(self.snapshot, settings)
blocking = [
issue for issue in plan.issues if issue.severity is Severity.BLOCKING
]
others = [
issue
for issue in plan.issues
if issue.severity is not Severity.BLOCKING
]
texts = [f"[{issue.severity.value}] {issue.message}" for issue in blocking + others]
self.page.set_issue_text(";".join(texts[:8]))
self._set_can_apply(plan.can_apply)
self._fill_rows(settings)
def _fill_rows(self, settings) -> None:
if self.snapshot is None:
self.page.set_rows([])
return
rows = []
for component in self.snapshot.components:
if not component.selected:
continue
value = ""
state = ""
for attribute in component.attributes:
if attribute.name.casefold() == settings.property_name.casefold():
value = attribute.value
state = "1" if attribute.visible else "0"
break
rows.append((component.refdes or "(无位号)", value, state))
self.page.set_rows(rows)
def apply(self) -> Path:
if self._apply_in_flight:
raise RuntimeError("an apply transaction is already in flight")
if self.snapshot is None or self.run_store is None or self.run_paths is None:
raise RuntimeError("bridge mailbox is not configured")
settings = self.page.settings()
plan = build_property_visibility_plan(self.snapshot, settings)
if not plan.can_apply:
raise RuntimeError("visibility plan is not applicable")
self._apply_in_flight = True
self._apply_started_at = time.monotonic()
by_bridge = {c.bridge_id: c for c in self.snapshot.components}
changes = []
for row in plan.rows:
if not row.changed:
continue
component = by_bridge[row.bridge_ids[0]]
current = "1"
for attribute in component.attributes:
if attribute.name.casefold() == row.property_name.casefold():
current = "1" if attribute.visible else "0"
break
changes.append(
OperationChange(
bridge_id=component.bridge_id,
stable_uid=component.stable_uid,
full_path=component.full_path,
op=OpType.PROPERTY_VISIBILITY,
property_name=row.property_name,
old_value=current,
new_value=row.new_refdes or "",
)
)
backup = self.run_store.write_operation_backup(
self.snapshot, tuple(changes)
)
for path in (
self.run_paths.apply_status,
self.run_paths.apply_request,
self.run_paths.result,
):
path.unlink(missing_ok=True)
write_apply_request(
self.run_paths.apply_request,
ApplyRequest(
format_version=self.snapshot.format_version,
run_id=self.snapshot.run_id,
snapshot_id=self.snapshot.snapshot_id,
backup_path=backup.resolve(),
schedule_sha256=schedule_sha256(plan.schedule),
),
)
write_schedule(self.run_paths.result, plan.schedule)
self._set_can_apply(False)
self._status_timer.start()
return self.run_paths.result
def _poll_apply_status(self) -> None:
if self.run_paths is None or not self.run_paths.apply_status.exists():
failure = watchdog_failure(self._apply_started_at, self.run_paths.root)
if failure is not None:
self._fail_apply(failure)
return
self._status_timer.stop()
self._apply_in_flight = False
try:
status = load_apply_status(self.run_paths.apply_status)
except Exception as exc:
self.apply_failed.emit(str(exc))
self.refresh_plan()
return
if self.run_store is not None:
try:
self.run_store.record_status(
status,
design_id=self.snapshot.design_id if self.snapshot else None,
)
except Exception:
pass
self.apply_completed.emit(status.state)
def _fail_apply(self, message: str) -> None:
self._status_timer.stop()
self._apply_in_flight = False
self.apply_failed.emit(message)
def _set_can_apply(self, enabled: bool) -> None:
if enabled != self.can_apply:
self.can_apply = enabled
self.can_apply_changed.emit(enabled)
@@ -0,0 +1,123 @@
"""Batch attribute visibility page (legacy PartName/PartLabel Hide tools)."""
from __future__ import annotations
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QComboBox,
QHBoxLayout,
QLabel,
QPushButton,
QRadioButton,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.features.property_visibility import (
SUPPORTED_PROPERTIES,
PropertyVisibilitySettings,
)
class PropertyVisibilityPage(QWidget):
apply_requested = Signal()
settings_changed = Signal()
def __init__(self) -> None:
super().__init__()
self._build_ui()
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 16, 20, 16)
layout.setSpacing(10)
hint = QLabel(
"批量切换选中器件的属性显示状态。先在 DxDesigner 中选中器件,"
"选择属性与目标状态后生成预览。"
)
hint.setObjectName("secondaryLabel")
hint.setWordWrap(True)
layout.addWidget(hint)
selector_row = QHBoxLayout()
selector_row.addWidget(QLabel("属性"))
self.property_combo = QComboBox()
for name in SUPPORTED_PROPERTIES:
self.property_combo.addItem(name)
selector_row.addWidget(self.property_combo)
selector_row.addStretch(1)
layout.addLayout(selector_row)
direction_row = QHBoxLayout()
direction_row.addWidget(QLabel("目标状态"))
self.hide_button = QRadioButton("隐藏")
self.hide_button.setChecked(True)
self.show_button = QRadioButton("显示")
direction_row.addWidget(self.hide_button)
direction_row.addWidget(self.show_button)
direction_row.addStretch(1)
layout.addLayout(direction_row)
self.model = QStandardItemModel(0, 3, self)
self.model.setHorizontalHeaderLabels(("位号", "属性值", "当前状态"))
self.table = QTableView()
self.table.setModel(self.model)
self.table.setMinimumHeight(360)
self.table.setEditTriggers(
QTableView.EditTrigger.NoEditTriggers
)
layout.addWidget(self.table, 1)
self.issue_label = QLabel("")
self.issue_label.setObjectName("secondaryLabel")
self.issue_label.setWordWrap(True)
layout.addWidget(self.issue_label)
actions = QHBoxLayout()
actions.addStretch(1)
self.apply_button = QPushButton("应用显示状态")
self.apply_button.setObjectName("primaryButton")
self.apply_button.setEnabled(False)
self.apply_button.clicked.connect(self.apply_requested)
actions.addWidget(self.apply_button)
layout.addLayout(actions)
self.property_combo.currentIndexChanged.connect(self.settings_changed)
self.hide_button.toggled.connect(self.settings_changed)
def settings(self) -> PropertyVisibilitySettings:
return PropertyVisibilitySettings(
property_name=self.property_combo.currentText(),
visible=self.show_button.isChecked(),
)
def set_rows(self, rows: list[tuple[str, str, str]]) -> None:
"""rows: (refdes, attribute value, current visibility)."""
self.model.setRowCount(0)
for refdes, value, visibility in rows:
ref_item = QStandardItem(refdes)
ref_item.setEditable(False)
value_item = QStandardItem(value)
value_item.setEditable(False)
state_item = QStandardItem("显示" if visibility == "1" else "隐藏")
state_item.setEditable(False)
self.model.appendRow((ref_item, value_item, state_item))
def set_issue_text(self, text: str) -> None:
self.issue_label.setText(text)
def set_can_apply(self, enabled: bool) -> None:
self.apply_button.setEnabled(enabled)
def visibility_state(self, component_attributes) -> str:
"""Helper used by controllers to map an AttributeRecord to state text."""
for attribute in component_attributes:
if (
attribute.name.casefold()
== self.property_combo.currentText().casefold()
):
return "1" if attribute.visible else "0"
return ""
+161
View File
@@ -0,0 +1,161 @@
"""Bind the immutable annotation planner to the RefDes page."""
from __future__ import annotations
import time
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from dx_productivity.bridge.protocol import (
atomic_write_text,
load_apply_status,
schedule_sha256,
write_apply_request,
write_schedule,
)
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import (
AnnotationPlan,
AnnotationSettings,
ApplyRequest,
DesignSnapshot,
RunPaths,
)
from dx_productivity.domain.planner import build_annotation_plan
from dx_productivity.ui.polling import watchdog_failure
from dx_productivity.ui.refdes_page import RefDesPage
class RefDesController(QObject):
can_apply_changed = Signal(bool)
apply_completed = Signal(str)
apply_failed = Signal(str)
def __init__(
self,
page: RefDesPage,
*,
run_store: RunStore | None = None,
run_paths: RunPaths | None = None,
) -> None:
super().__init__(page)
self.page = page
self.run_store = run_store
self.run_paths = run_paths
self.snapshot: DesignSnapshot | None = None
self.plan: AnnotationPlan | None = None
self.pending_backup: Path | None = None
self.can_apply = False
self._status_recorded = False
self._apply_in_flight = False
self._apply_started_at = 0.0
self._status_timer = QTimer(self)
self._status_timer.setInterval(200)
self._status_timer.timeout.connect(self._poll_apply_status)
self.page.settings_changed.connect(self.refresh_plan)
self.page.locate_requested.connect(self.locate)
def load_snapshot(self, snapshot: DesignSnapshot) -> None:
self.snapshot = snapshot
self.refresh_plan()
def refresh_plan(self) -> None:
if self._apply_in_flight:
return
if self.snapshot is None:
return
self.plan = build_annotation_plan(self.snapshot, self._settings())
self.page.set_plan(self.plan)
can_apply = self.plan.can_apply
if can_apply != self.can_apply:
self.can_apply = can_apply
self.can_apply_changed.emit(can_apply)
def apply(self) -> Path:
if self._apply_in_flight:
raise RuntimeError("an apply transaction is already in flight")
if not self.can_apply or self.snapshot is None or self.plan is None:
raise RuntimeError("annotation plan is not applicable")
if self.run_store is None or self.run_paths is None:
raise RuntimeError("bridge mailbox is not configured")
self._apply_in_flight = True
self._apply_started_at = time.monotonic()
self.pending_backup = self.run_store.write_backup(self.snapshot, self.plan)
for path in (
self.run_paths.apply_status,
self.run_paths.apply_request,
self.run_paths.result,
):
path.unlink(missing_ok=True)
write_apply_request(
self.run_paths.apply_request,
ApplyRequest(
format_version=self.snapshot.format_version,
run_id=self.snapshot.run_id,
snapshot_id=self.snapshot.snapshot_id,
backup_path=self.pending_backup.resolve(),
schedule_sha256=schedule_sha256(self.plan.schedule),
),
)
write_schedule(self.run_paths.result, self.plan.schedule)
self._status_recorded = False
self.can_apply = False
self.can_apply_changed.emit(False)
self._status_timer.start()
return self.run_paths.result
def locate(self, bridge_id: str) -> None:
if self.run_paths is None:
return
if any(char in bridge_id for char in "\t\r\n") or not bridge_id:
raise ValueError("invalid bridge ID")
atomic_write_text(self.run_paths.locate, f"{bridge_id}\n")
def _poll_apply_status(self) -> None:
if self.run_paths is None or not self.run_paths.apply_status.exists():
self._check_watchdog()
return
self._status_timer.stop()
self._apply_in_flight = False
try:
status = load_apply_status(self.run_paths.apply_status)
except Exception as exc:
self.apply_failed.emit(str(exc))
self.refresh_plan()
return
if self.run_store is not None and not self._status_recorded:
self._status_recorded = True
try:
self.run_store.record_status(
status,
design_id=self.snapshot.design_id if self.snapshot else None,
)
except Exception:
pass
self.apply_completed.emit(status.state)
def _check_watchdog(self) -> None:
if self.run_paths is None:
return
failure = watchdog_failure(self._apply_started_at, self.run_paths.root)
if failure is not None:
self._fail_apply(failure)
def _fail_apply(self, message: str) -> None:
self._status_timer.stop()
self._apply_in_flight = False
self.apply_failed.emit(message)
self.refresh_plan()
def _settings(self) -> AnnotationSettings:
return AnnotationSettings(
scope=self.page.scope(),
processing_mode=self.page.processing_mode(),
numbering_mode=self.page.numbering_mode(),
sort_order=self.page.sort_order(),
start_number=self.page.start_number(),
page_step=self.page.page_step_spin.value(),
page_start=self.page.page_start_spin.value(),
row_tolerance=self.page.row_tolerance(),
)
+315
View File
@@ -0,0 +1,315 @@
"""Automatic reference-designator rules and preview page."""
from __future__ import annotations
from decimal import Decimal
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import (
QAbstractItemView,
QButtonGroup,
QComboBox,
QDoubleSpinBox,
QFrame,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPushButton,
QSpinBox,
QTableView,
QVBoxLayout,
QWidget,
)
from dx_productivity.domain.models import (
AnnotationPlan,
NumberingMode,
ProcessingMode,
Scope,
Severity,
SortOrder,
)
class RefDesPage(QWidget):
settings_changed = Signal()
locate_requested = Signal(str)
def __init__(self) -> None:
super().__init__()
self._plan: AnnotationPlan | None = None
self._build_ui()
self._connect_controls()
def scope(self) -> Scope:
if self.current_sheet_button.isChecked():
return Scope.CURRENT_SHEET
if self.full_design_button.isChecked():
return Scope.FULL_DESIGN
return Scope.SELECTED
def processing_mode(self) -> ProcessingMode:
return (
ProcessingMode.REANNOTATE
if self.reannotate_button.isChecked()
else ProcessingMode.FILL_ONLY
)
def numbering_mode(self) -> NumberingMode:
return NumberingMode(self.numbering_combo.currentData())
def sort_order(self) -> SortOrder:
return SortOrder(self.sort_combo.currentData())
def start_number(self) -> int:
return self.start_spin.value()
def row_tolerance(self) -> Decimal:
return Decimal(str(self.tolerance_spin.value()))
def issue_text(self) -> str:
return self.issue_label.text()
def set_plan(self, plan: AnnotationPlan) -> None:
self._plan = plan
self.preview_model.removeRows(0, self.preview_model.rowCount())
for row in plan.rows:
status = _status_text(row.status, row.changed)
values = (
status,
row.old_refdes or "—",
row.new_refdes or "—",
row.prefix or "—",
row.sheet_name or "—",
row.part_number or "—",
row.value or "—",
row.full_path,
)
items = [QStandardItem(value) for value in values]
for item in items:
item.setEditable(False)
items[0].setData(row.bridge_ids, Qt.ItemDataRole.UserRole)
self.preview_model.appendRow(items)
blocking = sum(
issue.severity is Severity.BLOCKING for issue in plan.issues
)
warnings = sum(issue.severity is Severity.WARNING for issue in plan.issues)
if blocking:
self.issue_label.setText(f"{blocking} 个阻断项")
elif warnings:
self.issue_label.setText(f"{warnings} 个提醒")
else:
changed = sum(row.changed for row in plan.rows)
self.issue_label.setText(f"{changed} 项待更新")
self._apply_filter()
def _build_ui(self) -> None:
root = QHBoxLayout(self)
root.setContentsMargins(20, 18, 20, 18)
root.setSpacing(20)
root.addWidget(self._build_rules_panel())
root.addWidget(self._build_preview_panel(), 1)
def _build_rules_panel(self) -> QFrame:
panel = QFrame()
panel.setObjectName("rulesPanel")
panel.setFixedWidth(318)
layout = QVBoxLayout(panel)
layout.setContentsMargins(0, 0, 20, 0)
layout.setSpacing(10)
title = QLabel("标注规则")
title.setObjectName("pageTitle")
layout.addWidget(title)
subtitle = QLabel("所选规则会立即更新右侧预览")
subtitle.setObjectName("secondaryLabel")
layout.addWidget(subtitle)
layout.addWidget(_field_label("处理范围"))
scope_row, scope_group = _segmented_row(
("选中器件", "当前页", "全设计")
)
self.selected_button, self.current_sheet_button, self.full_design_button = (
scope_group.buttons()
)
self.selected_button.setChecked(True)
layout.addWidget(scope_row)
layout.addWidget(_field_label("处理方式"))
mode_row, mode_group = _segmented_row(("仅补空缺", "全部重编"))
self.fill_only_button, self.reannotate_button = mode_group.buttons()
self.fill_only_button.setChecked(True)
layout.addWidget(mode_row)
self.numbering_combo = QComboBox()
self.numbering_combo.addItem("连续编号", NumberingMode.CONTINUOUS)
self.numbering_combo.addItem("按页编号", NumberingMode.PAGE)
layout.addWidget(_labeled_control("编号方式", self.numbering_combo))
self.start_spin = QSpinBox()
self.start_spin.setRange(1, 999999)
self.start_spin.setValue(1)
layout.addWidget(_labeled_control("起始编号", self.start_spin))
self.page_step_spin = QSpinBox()
self.page_step_spin.setRange(1, 999999)
self.page_step_spin.setValue(100)
layout.addWidget(_labeled_control("每页跨度", self.page_step_spin))
self.page_start_spin = QSpinBox()
self.page_start_spin.setRange(0, 999999)
self.page_start_spin.setValue(1)
layout.addWidget(_labeled_control("页内起始", self.page_start_spin))
self.sort_combo = QComboBox()
self.sort_combo.addItem("从上到下 · 从左到右", SortOrder.TOP_DOWN_LEFT_RIGHT)
self.sort_combo.addItem("从上到下 · 从右到左", SortOrder.TOP_DOWN_RIGHT_LEFT)
self.sort_combo.addItem("从左到右 · 从上到下", SortOrder.LEFT_RIGHT_TOP_DOWN)
self.sort_combo.addItem("从右到左 · 从上到下", SortOrder.RIGHT_LEFT_TOP_DOWN)
layout.addWidget(_labeled_control("排列顺序", self.sort_combo))
self.tolerance_spin = QDoubleSpinBox()
self.tolerance_spin.setRange(0, 100)
self.tolerance_spin.setDecimals(1)
self.tolerance_spin.setSingleStep(0.5)
self.tolerance_spin.setValue(5)
self.tolerance_spin.setSuffix(" mm")
layout.addWidget(_labeled_control("同行容差", self.tolerance_spin))
layout.addStretch(1)
return panel
def _build_preview_panel(self) -> QWidget:
panel = QWidget()
layout = QVBoxLayout(panel)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
toolbar = QHBoxLayout()
preview_title = QLabel("变更预览")
preview_title.setObjectName("pageTitle")
toolbar.addWidget(preview_title)
toolbar.addStretch(1)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("搜索位号、料号或路径")
self.search_input.setClearButtonEnabled(True)
self.search_input.setMaximumWidth(280)
toolbar.addWidget(self.search_input)
self.status_filter = QComboBox()
self.status_filter.addItems(("全部状态", "待更新", "已保留", "需确认", "阻断"))
self.status_filter.setMaximumWidth(130)
toolbar.addWidget(self.status_filter)
layout.addLayout(toolbar)
self.preview_model = QStandardItemModel(0, 8, self)
self.preview_model.setHorizontalHeaderLabels(
("状态", "原位号", "新位号", "前缀", "页", "料号", "值", "层级路径")
)
self.preview_table = QTableView()
self.preview_table.setModel(self.preview_model)
self.preview_table.setAlternatingRowColors(True)
self.preview_table.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows
)
self.preview_table.setSelectionMode(
QAbstractItemView.SelectionMode.SingleSelection
)
self.preview_table.setSortingEnabled(False)
self.preview_table.verticalHeader().setVisible(False)
header = self.preview_table.horizontalHeader()
header.setMinimumSectionSize(44)
header.setStretchLastSection(True)
for column in range(7):
header.setSectionResizeMode(column, QHeaderView.ResizeMode.ResizeToContents)
layout.addWidget(self.preview_table, 1)
self.issue_label = QLabel("0 项待更新")
self.issue_label.setObjectName("secondaryLabel")
layout.addWidget(self.issue_label)
return panel
def _connect_controls(self) -> None:
for button in (
self.selected_button,
self.current_sheet_button,
self.full_design_button,
self.fill_only_button,
self.reannotate_button,
):
button.clicked.connect(self.settings_changed)
for control in (self.numbering_combo, self.sort_combo):
control.currentIndexChanged.connect(self.settings_changed)
for control in (
self.start_spin,
self.page_step_spin,
self.page_start_spin,
self.tolerance_spin,
):
control.valueChanged.connect(self.settings_changed)
self.search_input.textChanged.connect(self._apply_filter)
self.status_filter.currentIndexChanged.connect(self._apply_filter)
self.preview_table.doubleClicked.connect(self._locate_row)
def _apply_filter(self) -> None:
query = self.search_input.text().strip().casefold()
status = self.status_filter.currentText()
for row in range(self.preview_model.rowCount()):
values = [
self.preview_model.item(row, column).text()
for column in range(self.preview_model.columnCount())
]
matches_query = not query or any(query in value.casefold() for value in values)
matches_status = status == "全部状态" or values[0] == status
self.preview_table.setRowHidden(row, not (matches_query and matches_status))
def _locate_row(self, index) -> None:
bridge_ids = self.preview_model.item(index.row(), 0).data(
Qt.ItemDataRole.UserRole
)
if bridge_ids:
self.locate_requested.emit(bridge_ids[0])
def _segmented_row(labels: tuple[str, ...]) -> tuple[QFrame, QButtonGroup]:
frame = QFrame()
frame.setObjectName("segmentedControl")
layout = QHBoxLayout(frame)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
group = QButtonGroup(frame)
group.setExclusive(True)
for label in labels:
button = QPushButton(label)
button.setCheckable(True)
button.setObjectName("segmentButton")
group.addButton(button)
layout.addWidget(button, 1)
return frame, group
def _field_label(text: str) -> QLabel:
label = QLabel(text)
label.setObjectName("secondaryLabel")
return label
def _labeled_control(text: str, control: QWidget) -> QFrame:
frame = QFrame()
layout = QHBoxLayout(frame)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(8)
label = _field_label(text)
label.setMinimumWidth(78)
layout.addWidget(label)
layout.addWidget(control, 1)
return frame
def _status_text(status: str, changed: bool) -> str:
if changed:
return "待更新"
return {
"preserved": "已保留",
"locked": "已保留",
"blocked": "阻断",
}.get(status, "需确认")
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more