feat: add complete yiyezhqiu productivity suite
This commit is contained in:
commit
e422ca8b2a
155 files changed
+18959
No files matched your search
@@ -0,0 +1,6 @@
|
||||
"""DxDesigner 7.9.5 productivity suite."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
PRODUCT_ID = "yiyezhqiu-refactored"
|
||||
DISPLAY_NAME = "一叶知秋_重构版"
|
||||
@@ -0,0 +1,5 @@
|
||||
from dx_productivity.bridge.launcher import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1 @@
|
||||
"""Pure annotation domain types and algorithms."""
|
||||
@@ -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(),
|
||||
)
|
||||
@@ -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, ...]
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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))
|
||||
@@ -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
|
||||
)
|
||||
@@ -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()
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
"""PySide6 desktop interface."""
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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(
|
||||
[], "当前快照未包含网络数据,请在宿主重新刷新设计快照。"
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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 ""
|
||||
@@ -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(),
|
||||
)
|
||||
@@ -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, "需确认")
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Background update checks and local settings persistence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QObject, QThread, Signal, Slot
|
||||
|
||||
from dx_productivity import __version__
|
||||
from dx_productivity.update.models import UpdateManifest
|
||||
from dx_productivity.update.service import UpdateCheckResult, UpdateService
|
||||
from dx_productivity.update.stager import UpdateStager
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UpdateStageResult:
|
||||
state: str
|
||||
manifest: UpdateManifest
|
||||
staged_zip: Path | None
|
||||
message: str
|
||||
|
||||
|
||||
class _CheckWorker(QObject):
|
||||
finished = Signal(object)
|
||||
|
||||
def __init__(self, service: UpdateService, source: str, current: str, channel: str) -> None:
|
||||
super().__init__()
|
||||
self.service = service
|
||||
self.source = source
|
||||
self.current = current
|
||||
self.channel = channel
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
self.finished.emit(self.service.check(self.source, self.current, self.channel))
|
||||
|
||||
|
||||
class _StageWorker(QObject):
|
||||
finished = Signal(object)
|
||||
|
||||
def __init__(self, stager: UpdateStager, manifest: UpdateManifest, destination: Path) -> None:
|
||||
super().__init__()
|
||||
self.stager = stager
|
||||
self.manifest = manifest
|
||||
self.destination = destination
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
try:
|
||||
staged_zip = self.stager.download_and_verify(self.manifest, self.destination)
|
||||
except Exception as error:
|
||||
self.finished.emit(UpdateStageResult("failed", self.manifest, None, str(error)))
|
||||
else:
|
||||
self.finished.emit(UpdateStageResult("ready", self.manifest, staged_zip, "下载并校验完成"))
|
||||
|
||||
|
||||
class SettingsController(QObject):
|
||||
check_started = Signal()
|
||||
check_finished = Signal(object)
|
||||
stage_finished = Signal(object)
|
||||
install_requested = Signal(object)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
current_version: str = __version__,
|
||||
settings_path: Path | None = None,
|
||||
service: UpdateService | None = None,
|
||||
stager: UpdateStager | None = None,
|
||||
staging_path: Path | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.current_version = current_version
|
||||
local_app_data = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
||||
self.settings_path = Path(settings_path or local_app_data / "DxProductivity" / "settings.json")
|
||||
self.service = service or UpdateService()
|
||||
self.stager = stager or UpdateStager()
|
||||
self.staging_path = Path(staging_path or local_app_data / "DxProductivity" / "updates")
|
||||
self._thread: QThread | None = None
|
||||
self._worker: _CheckWorker | None = None
|
||||
self._pending_result: UpdateCheckResult | None = None
|
||||
self._stage_thread: QThread | None = None
|
||||
self._stage_worker: _StageWorker | None = None
|
||||
self._pending_stage_result: UpdateStageResult | None = None
|
||||
self._staged_paths: dict[str, Path] = {}
|
||||
|
||||
def load_settings(self) -> dict[str, object]:
|
||||
defaults: dict[str, object] = {
|
||||
"source": "",
|
||||
"channel": "stable",
|
||||
"auto_check": True,
|
||||
"last_check_at": "",
|
||||
}
|
||||
try:
|
||||
data = json.loads(self.settings_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return defaults
|
||||
if not isinstance(data, dict):
|
||||
return defaults
|
||||
for key in defaults:
|
||||
if key in data and isinstance(data[key], type(defaults[key])):
|
||||
defaults[key] = data[key]
|
||||
return defaults
|
||||
|
||||
def save_settings(self, source: str, channel: str, auto_check: bool) -> None:
|
||||
self.settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"source": str(source).strip(),
|
||||
"channel": str(channel).strip().casefold(),
|
||||
"auto_check": bool(auto_check),
|
||||
}
|
||||
temporary = self.settings_path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(self.settings_path)
|
||||
|
||||
def auto_check_due(self, settings: dict[str, object], *, now: datetime | None = None) -> bool:
|
||||
if not bool(settings.get("auto_check")) or not str(settings.get("source", "")).strip():
|
||||
return False
|
||||
raw_timestamp = settings.get("last_check_at")
|
||||
if not isinstance(raw_timestamp, str) or not raw_timestamp.strip():
|
||||
return True
|
||||
try:
|
||||
last_check = datetime.fromisoformat(raw_timestamp)
|
||||
except ValueError:
|
||||
return True
|
||||
if last_check.tzinfo is None:
|
||||
last_check = last_check.replace(tzinfo=timezone.utc)
|
||||
current_time = now or datetime.now(timezone.utc)
|
||||
if current_time.tzinfo is None:
|
||||
current_time = current_time.replace(tzinfo=timezone.utc)
|
||||
return current_time - last_check >= timedelta(hours=24)
|
||||
|
||||
def record_check(self, *, now: datetime | None = None) -> None:
|
||||
settings = self.load_settings()
|
||||
timestamp = now or datetime.now(timezone.utc)
|
||||
if timestamp.tzinfo is None:
|
||||
timestamp = timestamp.replace(tzinfo=timezone.utc)
|
||||
data = {
|
||||
"source": str(settings["source"]).strip(),
|
||||
"channel": str(settings["channel"]).strip().casefold(),
|
||||
"auto_check": bool(settings["auto_check"]),
|
||||
"last_check_at": timestamp.astimezone(timezone.utc).isoformat(),
|
||||
}
|
||||
self.settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self.settings_path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(self.settings_path)
|
||||
|
||||
def check_updates(self, source: str, channel: str) -> None:
|
||||
if self._thread is not None and self._thread.isRunning():
|
||||
self.check_started.emit()
|
||||
return
|
||||
self.check_started.emit()
|
||||
self._thread = QThread(self)
|
||||
self._worker = _CheckWorker(self.service, source, self.current_version, channel)
|
||||
self._worker.moveToThread(self._thread)
|
||||
self._thread.started.connect(self._worker.run)
|
||||
self._worker.finished.connect(self._on_check_result)
|
||||
self._worker.finished.connect(self._thread.quit)
|
||||
self._worker.finished.connect(self._worker.deleteLater)
|
||||
self._thread.finished.connect(self._finish_check)
|
||||
self._thread.finished.connect(self._thread.deleteLater)
|
||||
self._thread.start()
|
||||
|
||||
def request_install(self, manifest: UpdateManifest) -> None:
|
||||
self.install_requested.emit(manifest)
|
||||
|
||||
def stage_update(self, manifest: UpdateManifest) -> None:
|
||||
if self._stage_thread is not None and self._stage_thread.isRunning():
|
||||
return
|
||||
self._stage_thread = QThread(self)
|
||||
self._stage_worker = _StageWorker(self.stager, manifest, self.staging_path)
|
||||
self._stage_worker.moveToThread(self._stage_thread)
|
||||
self._stage_thread.started.connect(self._stage_worker.run)
|
||||
self._stage_worker.finished.connect(self._on_stage_result)
|
||||
self._stage_worker.finished.connect(self._stage_thread.quit)
|
||||
self._stage_worker.finished.connect(self._stage_worker.deleteLater)
|
||||
self._stage_thread.finished.connect(self._finish_stage)
|
||||
self._stage_thread.finished.connect(self._stage_thread.deleteLater)
|
||||
self._stage_thread.start()
|
||||
|
||||
def staged_path(self, manifest: UpdateManifest) -> Path | None:
|
||||
return self._staged_paths.get(str(manifest.version))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for thread in (self._thread, self._stage_thread):
|
||||
if thread is not None and thread.isRunning():
|
||||
thread.quit()
|
||||
thread.wait(5000)
|
||||
|
||||
@Slot()
|
||||
def _on_check_result(self, result: UpdateCheckResult) -> None:
|
||||
self._pending_result = result
|
||||
|
||||
@Slot()
|
||||
def _finish_check(self) -> None:
|
||||
result = self._pending_result
|
||||
self._pending_result = None
|
||||
if self.sender() is not None and self._thread is self.sender():
|
||||
self._thread = None
|
||||
self._worker = None
|
||||
if result is not None:
|
||||
self.check_finished.emit(result)
|
||||
|
||||
@Slot(object)
|
||||
def _on_stage_result(self, result: UpdateStageResult) -> None:
|
||||
self._pending_stage_result = result
|
||||
|
||||
@Slot()
|
||||
def _finish_stage(self) -> None:
|
||||
result = self._pending_stage_result
|
||||
self._pending_stage_result = None
|
||||
if self.sender() is not None and self._stage_thread is self.sender():
|
||||
self._stage_thread = None
|
||||
self._stage_worker = None
|
||||
if result is not None:
|
||||
if result.state == "ready" and result.staged_zip is not None:
|
||||
self._staged_paths[str(result.manifest.version)] = result.staged_zip
|
||||
self.stage_finished.emit(result)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Settings page for controlled online update checks and installation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QSize, Signal
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QFormLayout,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QTextEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from dx_productivity.update.models import UpdateManifest
|
||||
from dx_productivity.update.service import UpdateCheckResult
|
||||
from dx_productivity.ui.theme import Theme, themed_icon
|
||||
|
||||
|
||||
class SettingsPage(QWidget):
|
||||
check_requested = Signal(str, str)
|
||||
download_requested = Signal(object)
|
||||
install_requested = Signal(object)
|
||||
|
||||
def __init__(self, *, current_version: str) -> None:
|
||||
super().__init__()
|
||||
self.current_version = current_version
|
||||
self._manifest: UpdateManifest | None = None
|
||||
self._staged_zip: Path | None = None
|
||||
self._first_confirmation = False
|
||||
self.download_requested_emissions = 0
|
||||
self.install_requested_emissions = 0
|
||||
self._build_ui()
|
||||
|
||||
def show_update(self, manifest: UpdateManifest) -> None:
|
||||
self._manifest = manifest
|
||||
self._staged_zip = None
|
||||
self._first_confirmation = False
|
||||
self.install_button.setText("准备安装")
|
||||
self.version_label.setText(f"当前版本 {self.current_version} · 可更新至 {manifest.version}")
|
||||
self.release_notes_view.setPlainText(manifest.release_notes)
|
||||
if manifest.channel == "stable" and not manifest.signature:
|
||||
self.install_button.setEnabled(False)
|
||||
self.status_label.setText("稳定版缺少签名")
|
||||
else:
|
||||
self.install_button.setEnabled(True)
|
||||
self.status_label.setText("发现新版本")
|
||||
|
||||
def show_result(self, result: UpdateCheckResult) -> None:
|
||||
labels = {
|
||||
"up-to-date": "已是最新",
|
||||
"available": "发现新版本",
|
||||
"incompatible": "版本不兼容",
|
||||
"offline": "离线",
|
||||
"error": "检查失败",
|
||||
}
|
||||
self.status_label.setText(labels.get(result.status, result.status))
|
||||
if result.manifest is not None and result.status == "available":
|
||||
self.show_update(result.manifest)
|
||||
else:
|
||||
self._manifest = None
|
||||
self.install_button.setEnabled(False)
|
||||
self.release_notes_view.clear()
|
||||
|
||||
def show_stage_result(self, result: object) -> None:
|
||||
if getattr(result, "state", "") == "ready" and getattr(result, "staged_zip", None) is not None:
|
||||
self._staged_zip = Path(result.staged_zip)
|
||||
self.install_button.setEnabled(True)
|
||||
self.install_button.setText("确认安装")
|
||||
self.status_label.setText("下载并校验完成,请确认安装")
|
||||
return
|
||||
self._staged_zip = None
|
||||
self.install_button.setEnabled(False)
|
||||
self.status_label.setText(str(getattr(result, "message", "下载失败")))
|
||||
|
||||
def set_checking(self) -> None:
|
||||
self.status_label.setText("检查中")
|
||||
self.install_button.setEnabled(False)
|
||||
|
||||
def refresh_icons(self, theme: Theme) -> None:
|
||||
self.check_button.setIcon(themed_icon("fa6s.arrows-rotate", theme))
|
||||
self.install_button.setIcon(themed_icon("fa6s.download", theme))
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(20, 18, 20, 18)
|
||||
root.setSpacing(14)
|
||||
|
||||
header = QFrame()
|
||||
header.setObjectName("settingsIntro")
|
||||
header_layout = QVBoxLayout(header)
|
||||
header_layout.setContentsMargins(16, 12, 16, 12)
|
||||
title = QLabel("设置")
|
||||
title.setObjectName("pageTitle")
|
||||
header_layout.addWidget(title)
|
||||
subtitle = QLabel("在线更新默认只检查,不会静默安装或覆盖正在运行的程序")
|
||||
subtitle.setObjectName("secondaryLabel")
|
||||
header_layout.addWidget(subtitle)
|
||||
root.addWidget(header)
|
||||
|
||||
form_frame = QFrame()
|
||||
form_frame.setObjectName("settingsPanel")
|
||||
form = QFormLayout(form_frame)
|
||||
form.setContentsMargins(16, 14, 16, 14)
|
||||
form.setHorizontalSpacing(16)
|
||||
form.setVerticalSpacing(12)
|
||||
self.source_input = QLineEdit()
|
||||
self.source_input.setPlaceholderText("https://.../manifest.json 或 file://...")
|
||||
self.channel_combo = QComboBox()
|
||||
self.channel_combo.addItem("稳定版", "stable")
|
||||
self.channel_combo.addItem("开发版", "development")
|
||||
self.auto_check_checkbox = QCheckBox("启动后每天自动检查一次")
|
||||
self.auto_check_checkbox.setChecked(True)
|
||||
form.addRow("更新源", self.source_input)
|
||||
form.addRow("频道", self.channel_combo)
|
||||
form.addRow("检查策略", self.auto_check_checkbox)
|
||||
root.addWidget(form_frame)
|
||||
|
||||
actions = QHBoxLayout()
|
||||
self.check_button = QPushButton("检查更新")
|
||||
self.install_button = QPushButton("准备安装")
|
||||
self.install_button.setObjectName("primaryButton")
|
||||
self.install_button.setEnabled(False)
|
||||
self.check_button.clicked.connect(self._check)
|
||||
self.install_button.clicked.connect(self._install)
|
||||
actions.addWidget(self.check_button)
|
||||
actions.addWidget(self.install_button)
|
||||
actions.addStretch(1)
|
||||
root.addLayout(actions)
|
||||
|
||||
status_row = QHBoxLayout()
|
||||
self.version_label = QLabel(f"当前版本 {self.current_version}")
|
||||
self.version_label.setObjectName("secondaryLabel")
|
||||
self.status_label = QLabel("尚未检查")
|
||||
self.status_label.setObjectName("settingsStatus")
|
||||
status_row.addWidget(self.version_label)
|
||||
status_row.addStretch(1)
|
||||
status_row.addWidget(self.status_label)
|
||||
root.addLayout(status_row)
|
||||
|
||||
notes_title = QLabel("版本说明")
|
||||
notes_title.setObjectName("moduleCardTitle")
|
||||
root.addWidget(notes_title)
|
||||
self.release_notes_view = QTextEdit()
|
||||
self.release_notes_view.setReadOnly(True)
|
||||
self.release_notes_view.setPlaceholderText("检查到新版本后显示版本说明")
|
||||
root.addWidget(self.release_notes_view, 1)
|
||||
self.refresh_icons(Theme.LIGHT)
|
||||
|
||||
def _check(self) -> None:
|
||||
self.set_checking()
|
||||
self.check_requested.emit(self.source_input.text().strip(), self.channel_combo.currentData())
|
||||
|
||||
def _install(self) -> None:
|
||||
if self._manifest is None:
|
||||
return
|
||||
if not self._first_confirmation:
|
||||
answer = QMessageBox.question(
|
||||
self,
|
||||
"确认更新",
|
||||
"将下载并校验新版本,是否继续?",
|
||||
)
|
||||
if answer != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
self._first_confirmation = True
|
||||
self.install_button.setEnabled(False)
|
||||
self.install_button.setText("下载中")
|
||||
self.status_label.setText("正在下载并校验")
|
||||
self.download_requested_emissions += 1
|
||||
self.download_requested.emit(self._manifest)
|
||||
return
|
||||
if self._staged_zip is None:
|
||||
return
|
||||
answer = QMessageBox.question(
|
||||
self,
|
||||
"确认安装",
|
||||
"校验完成后将退出主程序并替换版本目录,是否安装?",
|
||||
)
|
||||
if answer != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
self.install_requested_emissions += 1
|
||||
self.install_requested.emit(self._manifest)
|
||||
@@ -0,0 +1,321 @@
|
||||
"""Accessible light, dark, and high-contrast desktop theme tokens."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
import qtawesome as qta
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
|
||||
class Theme(str, Enum):
|
||||
LIGHT = "light"
|
||||
DARK = "dark"
|
||||
HIGH_CONTRAST = "high-contrast"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ThemeTokens:
|
||||
canvas: str
|
||||
sidebar: str
|
||||
surface: str
|
||||
surface_hover: str
|
||||
border: str
|
||||
text_primary: str
|
||||
text_secondary: str
|
||||
accent: str
|
||||
accent_hover: str
|
||||
accent_text: str
|
||||
success: str
|
||||
warning: str
|
||||
danger: str
|
||||
focus: str
|
||||
|
||||
|
||||
THEMES = {
|
||||
Theme.LIGHT: ThemeTokens(
|
||||
canvas="#F5F5F7",
|
||||
sidebar="#ECEEF1",
|
||||
surface="#FFFFFF",
|
||||
surface_hover="#E5E7EB",
|
||||
border="#C7CBD1",
|
||||
text_primary="#1D1D1F",
|
||||
text_secondary="#5A5D63",
|
||||
accent="#0068D9",
|
||||
accent_hover="#0057B8",
|
||||
accent_text="#FFFFFF",
|
||||
success="#187A36",
|
||||
warning="#8A5A00",
|
||||
danger="#C5222F",
|
||||
focus="#005FCC",
|
||||
),
|
||||
Theme.DARK: ThemeTokens(
|
||||
canvas="#1C1C1E",
|
||||
sidebar="#252527",
|
||||
surface="#2C2C2E",
|
||||
surface_hover="#3A3A3C",
|
||||
border="#515154",
|
||||
text_primary="#F5F5F7",
|
||||
text_secondary="#C7C7CC",
|
||||
accent="#0A84FF",
|
||||
accent_hover="#409CFF",
|
||||
accent_text="#FFFFFF",
|
||||
success="#30D158",
|
||||
warning="#FFD60A",
|
||||
danger="#FF453A",
|
||||
focus="#64D2FF",
|
||||
),
|
||||
Theme.HIGH_CONTRAST: ThemeTokens(
|
||||
canvas="#000000",
|
||||
sidebar="#000000",
|
||||
surface="#000000",
|
||||
surface_hover="#202020",
|
||||
border="#FFFFFF",
|
||||
text_primary="#FFFFFF",
|
||||
text_secondary="#FFFFFF",
|
||||
accent="#00A8FF",
|
||||
accent_hover="#4DC3FF",
|
||||
accent_text="#000000",
|
||||
success="#52FF78",
|
||||
warning="#FFF200",
|
||||
danger="#FF5C5C",
|
||||
focus="#FFF200",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def theme_tokens(theme: Theme) -> ThemeTokens:
|
||||
return THEMES[theme]
|
||||
|
||||
|
||||
def apply_theme(app: QApplication, theme: Theme) -> None:
|
||||
tokens = theme_tokens(theme)
|
||||
app.setStyleSheet(_stylesheet(tokens))
|
||||
app.setProperty("dxTheme", theme.value)
|
||||
|
||||
|
||||
def themed_icon(name: str, theme: Theme, *, color: str | None = None) -> QIcon:
|
||||
tokens = theme_tokens(theme)
|
||||
return qta.icon(name, color=color or tokens.text_secondary)
|
||||
|
||||
|
||||
def contrast_ratio(foreground: str, background: str) -> float:
|
||||
lighter = max(_relative_luminance(foreground), _relative_luminance(background))
|
||||
darker = min(_relative_luminance(foreground), _relative_luminance(background))
|
||||
return (lighter + 0.05) / (darker + 0.05)
|
||||
|
||||
|
||||
def _relative_luminance(color: str) -> float:
|
||||
channels = [int(color[index : index + 2], 16) / 255 for index in (1, 3, 5)]
|
||||
|
||||
def linear(value: float) -> float:
|
||||
return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4
|
||||
|
||||
red, green, blue = (linear(value) for value in channels)
|
||||
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
|
||||
|
||||
|
||||
def _stylesheet(tokens: ThemeTokens) -> str:
|
||||
return f"""
|
||||
* {{
|
||||
font-family: "Microsoft YaHei UI";
|
||||
font-size: 13pt;
|
||||
letter-spacing: 0px;
|
||||
}}
|
||||
QMainWindow, QWidget#appRoot {{
|
||||
background: {tokens.canvas};
|
||||
color: {tokens.text_primary};
|
||||
}}
|
||||
QFrame#titleBar, QFrame#contentHeader {{
|
||||
background: {tokens.surface};
|
||||
border-bottom: 1px solid {tokens.border};
|
||||
}}
|
||||
QFrame#navigationRail {{
|
||||
background: {tokens.sidebar};
|
||||
border-right: 1px solid {tokens.border};
|
||||
}}
|
||||
QFrame#rulesPanel {{
|
||||
border-right: 1px solid {tokens.border};
|
||||
}}
|
||||
QFrame#legacyIntro {{
|
||||
background: {tokens.surface};
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
}}
|
||||
QFrame#moduleCard {{
|
||||
background: {tokens.surface};
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
}}
|
||||
QFrame#moduleCard:hover {{
|
||||
border-color: {tokens.accent};
|
||||
}}
|
||||
QLabel#moduleCardTitle {{
|
||||
font-size: 13pt;
|
||||
font-weight: 600;
|
||||
}}
|
||||
QLabel#compatibilityBadge {{
|
||||
color: {tokens.success};
|
||||
background: {tokens.surface_hover};
|
||||
border: 1px solid {tokens.success};
|
||||
border-radius: 4px;
|
||||
padding: 2px 6px;
|
||||
font-size: 9pt;
|
||||
font-weight: 600;
|
||||
}}
|
||||
QLabel#moduleResource {{
|
||||
color: {tokens.text_secondary};
|
||||
font-size: 10pt;
|
||||
}}
|
||||
QLabel#legacyEmptyState {{
|
||||
color: {tokens.text_secondary};
|
||||
border: 1px dashed {tokens.border};
|
||||
border-radius: 6px;
|
||||
min-height: 120px;
|
||||
}}
|
||||
QFrame#settingsIntro, QFrame#settingsPanel {{
|
||||
background: {tokens.surface};
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
}}
|
||||
QLabel#settingsStatus {{
|
||||
color: {tokens.accent};
|
||||
font-weight: 600;
|
||||
}}
|
||||
QTextEdit {{
|
||||
background: {tokens.surface};
|
||||
color: {tokens.text_primary};
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
padding: 10px;
|
||||
}}
|
||||
QLabel {{
|
||||
color: {tokens.text_primary};
|
||||
}}
|
||||
QLabel#secondaryLabel, QLabel#projectLabel {{
|
||||
color: {tokens.text_secondary};
|
||||
font-size: 10pt;
|
||||
}}
|
||||
QLabel#brandLabel {{
|
||||
font-size: 15pt;
|
||||
font-weight: 600;
|
||||
}}
|
||||
QLabel#pageTitle {{
|
||||
font-size: 16pt;
|
||||
font-weight: 600;
|
||||
}}
|
||||
QListWidget#navigationList {{
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
padding: 8px;
|
||||
}}
|
||||
QListWidget#navigationList::item {{
|
||||
min-height: 36px;
|
||||
padding: 0 10px;
|
||||
border-radius: 6px;
|
||||
color: {tokens.text_secondary};
|
||||
}}
|
||||
QListWidget#navigationList::item:hover {{
|
||||
background: {tokens.surface_hover};
|
||||
color: {tokens.text_primary};
|
||||
}}
|
||||
QListWidget#navigationList::item:selected {{
|
||||
background: {tokens.surface};
|
||||
color: {tokens.accent};
|
||||
font-weight: 600;
|
||||
}}
|
||||
QPushButton, QToolButton, QComboBox, QSpinBox, QDoubleSpinBox,
|
||||
QLineEdit {{
|
||||
min-height: 30px;
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
background: {tokens.surface};
|
||||
color: {tokens.text_primary};
|
||||
padding: 0 10px;
|
||||
}}
|
||||
QPushButton:hover, QToolButton:hover, QComboBox:hover {{
|
||||
background: {tokens.surface_hover};
|
||||
}}
|
||||
QPushButton:focus, QToolButton:focus, QComboBox:focus,
|
||||
QSpinBox:focus, QDoubleSpinBox:focus, QLineEdit:focus,
|
||||
QListWidget:focus, QTableView:focus {{
|
||||
border: 2px solid {tokens.focus};
|
||||
}}
|
||||
QPushButton#primaryButton {{
|
||||
background: {tokens.accent};
|
||||
border-color: {tokens.accent};
|
||||
color: {tokens.accent_text};
|
||||
font-weight: 600;
|
||||
padding: 0 14px;
|
||||
}}
|
||||
QPushButton#primaryButton:hover {{
|
||||
background: {tokens.accent_hover};
|
||||
}}
|
||||
QFrame#segmentedControl {{
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
background: {tokens.surface};
|
||||
}}
|
||||
QPushButton#segmentButton {{
|
||||
min-height: 30px;
|
||||
border: none;
|
||||
border-right: 1px solid {tokens.border};
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
padding: 0 8px;
|
||||
}}
|
||||
QPushButton#segmentButton:checked {{
|
||||
background: {tokens.accent};
|
||||
color: {tokens.accent_text};
|
||||
font-weight: 600;
|
||||
}}
|
||||
QPushButton:disabled, QToolButton:disabled {{
|
||||
color: {tokens.text_secondary};
|
||||
background: {tokens.sidebar};
|
||||
}}
|
||||
QToolButton {{
|
||||
min-width: 30px;
|
||||
max-width: 30px;
|
||||
padding: 0;
|
||||
}}
|
||||
QFrame#statusStrip {{
|
||||
background: {tokens.surface};
|
||||
border-top: 1px solid {tokens.border};
|
||||
}}
|
||||
QTableView {{
|
||||
background: {tokens.surface};
|
||||
alternate-background-color: {tokens.canvas};
|
||||
color: {tokens.text_primary};
|
||||
border: 1px solid {tokens.border};
|
||||
border-radius: 6px;
|
||||
gridline-color: {tokens.border};
|
||||
selection-background-color: {tokens.accent};
|
||||
selection-color: {tokens.accent_text};
|
||||
}}
|
||||
QHeaderView::section {{
|
||||
background: {tokens.sidebar};
|
||||
color: {tokens.text_secondary};
|
||||
border: none;
|
||||
border-bottom: 1px solid {tokens.border};
|
||||
padding: 7px;
|
||||
font-size: 10pt;
|
||||
font-weight: 600;
|
||||
}}
|
||||
QScrollBar:horizontal, QScrollBar:vertical {{
|
||||
background: {tokens.canvas};
|
||||
border: none;
|
||||
}}
|
||||
QScrollBar::handle:horizontal, QScrollBar::handle:vertical {{
|
||||
background: {tokens.border};
|
||||
border-radius: 4px;
|
||||
min-width: 28px;
|
||||
min-height: 28px;
|
||||
}}
|
||||
QScrollBar::add-line, QScrollBar::sub-line {{
|
||||
width: 0;
|
||||
height: 0;
|
||||
}}
|
||||
"""
|
||||
@@ -0,0 +1,4 @@
|
||||
"""Versioned update models and services for the portable release."""
|
||||
|
||||
PRODUCT_ID = "yiyezhqiu-refactored"
|
||||
DISPLAY_NAME = "一叶知秋_重构版"
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Rollbackable side-by-side installer for portable update archives."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
from dx_productivity.update.verification import sha256_file
|
||||
|
||||
|
||||
PARENT_EXIT_TIMEOUT_SECONDS = 60.0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class InstallPlan:
|
||||
current_root: Path
|
||||
staged_zip: Path
|
||||
backup_root: Path
|
||||
restart_command: tuple[str, ...]
|
||||
sha256: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, object]) -> "InstallPlan":
|
||||
sha256 = data.get("sha256")
|
||||
return cls(
|
||||
current_root=Path(str(data["current_root"])),
|
||||
staged_zip=Path(str(data["staged_zip"])),
|
||||
backup_root=Path(str(data["backup_root"])),
|
||||
restart_command=tuple(str(item) for item in data["restart_command"]),
|
||||
sha256=str(sha256) if sha256 else None,
|
||||
)
|
||||
|
||||
def to_mapping(self) -> dict[str, object]:
|
||||
payload: dict[str, object] = {
|
||||
"current_root": str(self.current_root),
|
||||
"staged_zip": str(self.staged_zip),
|
||||
"backup_root": str(self.backup_root),
|
||||
"restart_command": list(self.restart_command),
|
||||
}
|
||||
if self.sha256 is not None:
|
||||
payload["sha256"] = self.sha256
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class InstallResult:
|
||||
state: str
|
||||
message: str
|
||||
backup_path: Path | None = None
|
||||
|
||||
|
||||
class UpdateInstaller:
|
||||
def install(self, plan: InstallPlan) -> InstallResult:
|
||||
current = Path(plan.current_root)
|
||||
staged_zip = Path(plan.staged_zip)
|
||||
backup_root = Path(plan.backup_root)
|
||||
if not current.is_dir():
|
||||
return InstallResult("failed", "current portable root is missing")
|
||||
if not staged_zip.is_file():
|
||||
return InstallResult("failed", "staged ZIP is missing")
|
||||
if plan.sha256 is not None and sha256_file(staged_zip) != plan.sha256:
|
||||
return InstallResult(
|
||||
"failed",
|
||||
"staged ZIP digest no longer matches the manifest (TOCTOU guard)",
|
||||
)
|
||||
with _single_instance_lock(current):
|
||||
return self._install_locked(plan, current, staged_zip, backup_root)
|
||||
|
||||
def _install_locked(
|
||||
self, plan: InstallPlan, current: Path, staged_zip: Path, backup_root: Path
|
||||
) -> InstallResult:
|
||||
backup_root.mkdir(parents=True, exist_ok=True)
|
||||
backup_path = backup_root / self._backup_name(current)
|
||||
staging = current.parent / f".{current.name}.staged-{uuid.uuid4().hex}"
|
||||
old_path = current.parent / f".{current.name}.old-{uuid.uuid4().hex}"
|
||||
exe = current / "DxDesignerTools.exe"
|
||||
if not self._wait_for_parent_exit(exe):
|
||||
return InstallResult(
|
||||
"failed",
|
||||
"the running application did not exit in time; nothing was changed",
|
||||
)
|
||||
try:
|
||||
shutil.copytree(current, backup_path)
|
||||
self._extract_verified_zip(staged_zip, staging)
|
||||
if not (staging / "DxDesignerTools.exe").is_file():
|
||||
raise ValueError("staged package is missing DxDesignerTools.exe")
|
||||
current.replace(old_path)
|
||||
staging.replace(current)
|
||||
probe = subprocess.run(plan.restart_command, timeout=30, check=False)
|
||||
if probe.returncode != 0:
|
||||
raise RuntimeError(f"restart probe failed with code {probe.returncode}")
|
||||
shutil.rmtree(old_path, ignore_errors=True)
|
||||
self._prune_backups(backup_root)
|
||||
self._log(backup_root, f"installed {current}")
|
||||
return InstallResult("installed", "update installed", backup_path)
|
||||
except Exception as error:
|
||||
rollback_error = self._rollback(current, old_path, staging)
|
||||
if rollback_error is not None:
|
||||
error = f"{error}; {rollback_error}"
|
||||
self._log(backup_root, f"rolled-back {current}: {error}")
|
||||
return InstallResult("rolled-back", str(error), backup_path)
|
||||
|
||||
@staticmethod
|
||||
def _rollback(current: Path, old_path: Path, staging: Path) -> str | None:
|
||||
"""Restore the previous directory; report (never swallow) failures."""
|
||||
problems: list[str] = []
|
||||
if current.exists() and old_path.exists():
|
||||
shutil.rmtree(current, ignore_errors=True)
|
||||
if current.exists():
|
||||
problems.append("could not remove the new version directory")
|
||||
if old_path.exists() and not current.exists():
|
||||
try:
|
||||
old_path.replace(current)
|
||||
except OSError as error:
|
||||
problems.append(f"could not restore the old version: {error}")
|
||||
if staging.exists():
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
if staging.exists():
|
||||
problems.append("could not remove the staging directory")
|
||||
if problems:
|
||||
return "; ".join(problems)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _wait_for_parent_exit(exe: Path) -> bool:
|
||||
"""Wait until the running application binary is no longer write-locked."""
|
||||
if not exe.is_file():
|
||||
return True
|
||||
deadline = time.monotonic() + PARENT_EXIT_TIMEOUT_SECONDS
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
handle = os.open(exe, os.O_RDWR)
|
||||
except PermissionError:
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
except OSError:
|
||||
return True
|
||||
else:
|
||||
os.close(handle)
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _backup_name(current: Path) -> str:
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
|
||||
return f"{stamp}-{current.name}-{uuid.uuid4().hex[:8]}"
|
||||
|
||||
@staticmethod
|
||||
def _extract_verified_zip(staged_zip: Path, destination: Path) -> None:
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
root = destination.resolve()
|
||||
with zipfile.ZipFile(staged_zip) as archive:
|
||||
for member in archive.infolist():
|
||||
target = (destination / member.filename).resolve()
|
||||
if not target.is_relative_to(root):
|
||||
raise ValueError("staged ZIP contains path traversal")
|
||||
archive.extractall(destination)
|
||||
|
||||
@staticmethod
|
||||
def _prune_backups(backup_root: Path) -> None:
|
||||
backups = sorted(
|
||||
(path for path in backup_root.iterdir() if path.is_dir()),
|
||||
key=lambda path: path.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
for path in backups[2:]:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
@staticmethod
|
||||
def _log(backup_root: Path, message: str) -> None:
|
||||
log_path = backup_root.parent / "install.log"
|
||||
with log_path.open("a", encoding="utf-8") as stream:
|
||||
stream.write(f"{datetime.now(timezone.utc).isoformat()} {message}\n")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _single_instance_lock(current_root: Path):
|
||||
"""Best-effort named mutex so two updaters cannot race each other."""
|
||||
if os.name != "win32":
|
||||
yield
|
||||
return
|
||||
import ctypes
|
||||
|
||||
marker = abs(hash(str(current_root).casefold()))
|
||||
name = f"Local\\DxProductivityUpdate-{marker:08x}"
|
||||
handle = ctypes.windll.kernel32.CreateMutexW(None, False, name)
|
||||
already_running = (
|
||||
ctypes.windll.kernel32.GetLastError() == 183
|
||||
) # ERROR_ALREADY_EXISTS
|
||||
try:
|
||||
if already_running:
|
||||
raise RuntimeError("another update is already in progress")
|
||||
yield
|
||||
finally:
|
||||
if handle:
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Embedded release verification key.
|
||||
|
||||
The Ed25519 public key below is the release-signing identity. The matching
|
||||
private key is kept OFF this machine's repository (see
|
||||
``packaging/sign_manifest.py`` for the signing workflow). Rotating the key
|
||||
requires shipping a new release that embeds the new public key.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
|
||||
|
||||
RELEASE_PUBLIC_KEY_HEX = (
|
||||
"49c8b4fa8cc827e38321de8e3b0518c2a9f5340eb88f14f5ce7bd770603ec17e"
|
||||
)
|
||||
|
||||
|
||||
def release_public_key() -> bytes:
|
||||
return binascii.unhexlify(RELEASE_PUBLIC_KEY_HEX)
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Strict SemVer and signed release-manifest models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from functools import total_ordering
|
||||
|
||||
from dx_productivity.update import PRODUCT_ID
|
||||
|
||||
|
||||
_VERSION = re.compile(
|
||||
r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
|
||||
r"(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"
|
||||
)
|
||||
_DIGEST = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||
|
||||
|
||||
@total_ordering
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SemVer:
|
||||
major: int
|
||||
minor: int
|
||||
patch: int
|
||||
prerelease: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: str | "SemVer") -> "SemVer":
|
||||
if isinstance(value, cls):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("version must be a string")
|
||||
match = _VERSION.fullmatch(value.strip())
|
||||
if match is None:
|
||||
raise ValueError(f"invalid version: {value!r}")
|
||||
prerelease = tuple((match.group(4) or "").split(".")) if match.group(4) else ()
|
||||
return cls(int(match.group(1)), int(match.group(2)), int(match.group(3)), prerelease)
|
||||
|
||||
def __str__(self) -> str:
|
||||
suffix = "-" + ".".join(self.prerelease) if self.prerelease else ""
|
||||
return f"{self.major}.{self.minor}.{self.patch}{suffix}"
|
||||
|
||||
def _compare_key(self) -> tuple[object, ...]:
|
||||
if not self.prerelease:
|
||||
return (self.major, self.minor, self.patch, (1,))
|
||||
identifiers: list[tuple[int, object]] = []
|
||||
for identifier in self.prerelease:
|
||||
if identifier.isdigit():
|
||||
identifiers.append((0, int(identifier)))
|
||||
else:
|
||||
identifiers.append((1, identifier))
|
||||
return (self.major, self.minor, self.patch, (0, tuple(identifiers)))
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if not isinstance(other, SemVer):
|
||||
return NotImplemented
|
||||
return (self.major, self.minor, self.patch, self.prerelease) == (
|
||||
other.major,
|
||||
other.minor,
|
||||
other.patch,
|
||||
other.prerelease,
|
||||
)
|
||||
|
||||
def __lt__(self, other: object) -> bool:
|
||||
if not isinstance(other, SemVer):
|
||||
return NotImplemented
|
||||
return self._compare_key() < other._compare_key()
|
||||
|
||||
def is_newer_than(self, other: str | "SemVer") -> bool:
|
||||
return self > self.parse(other)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UpdateManifest:
|
||||
product: str
|
||||
version: SemVer
|
||||
channel: str
|
||||
min_supported_version: SemVer
|
||||
package_url: str
|
||||
sha256: str
|
||||
release_notes: str
|
||||
published_at: str
|
||||
signature: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: Mapping[str, object]) -> "UpdateManifest":
|
||||
required = (
|
||||
"product",
|
||||
"version",
|
||||
"channel",
|
||||
"min_supported_version",
|
||||
"package_url",
|
||||
"sha256",
|
||||
"release_notes",
|
||||
"published_at",
|
||||
)
|
||||
missing = [key for key in required if key not in data]
|
||||
if missing:
|
||||
raise ValueError("missing manifest fields: " + ", ".join(missing))
|
||||
product = str(data["product"]).strip().casefold()
|
||||
if product != PRODUCT_ID:
|
||||
raise ValueError(f"manifest product mismatch: {product!r}")
|
||||
channel = str(data["channel"]).strip().casefold()
|
||||
if channel not in {"stable", "development"}:
|
||||
raise ValueError(f"invalid channel: {channel!r}")
|
||||
package_url = str(data["package_url"]).strip()
|
||||
if not package_url:
|
||||
raise ValueError("package_url must not be empty")
|
||||
require_allowed_url(package_url)
|
||||
sha256 = str(data["sha256"]).strip().lower()
|
||||
if _DIGEST.fullmatch(sha256) is None:
|
||||
raise ValueError("sha256 must be 64 hexadecimal characters")
|
||||
signature = data.get("signature")
|
||||
if signature is not None and not str(signature).strip():
|
||||
signature = None
|
||||
return cls(
|
||||
product=product,
|
||||
version=SemVer.parse(str(data["version"])),
|
||||
channel=channel,
|
||||
min_supported_version=SemVer.parse(str(data["min_supported_version"])),
|
||||
package_url=package_url,
|
||||
sha256=sha256,
|
||||
release_notes=str(data["release_notes"]),
|
||||
published_at=str(data["published_at"]),
|
||||
signature=str(signature) if signature is not None else None,
|
||||
)
|
||||
|
||||
def is_compatible_with(self, current: str | SemVer) -> bool:
|
||||
return self.product == PRODUCT_ID and SemVer.parse(current) >= self.min_supported_version
|
||||
|
||||
|
||||
ALLOWED_PACKAGE_SCHEMES = frozenset({"https", "file"})
|
||||
|
||||
|
||||
def require_allowed_url(url: str) -> None:
|
||||
"""Reject plaintext HTTP and arbitrary schemes for update downloads."""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
scheme = urlparse(url).scheme.casefold()
|
||||
if scheme not in ALLOWED_PACKAGE_SCHEMES:
|
||||
raise ValueError(
|
||||
f"package_url scheme {scheme or 'none'!r} is not allowed; "
|
||||
"use https or a file share"
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Manifest fetching and non-mutating update checks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from dx_productivity.update.models import (
|
||||
SemVer,
|
||||
UpdateManifest,
|
||||
require_allowed_url,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UpdateCheckResult:
|
||||
status: str
|
||||
current: SemVer
|
||||
manifest: UpdateManifest | None
|
||||
message: str
|
||||
|
||||
|
||||
class UpdateService:
|
||||
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||
|
||||
def fetch_manifest(self, source: str, timeout: float = 10.0) -> UpdateManifest:
|
||||
require_allowed_url(str(source))
|
||||
request = Request(str(source), headers={"User-Agent": "YiyezhqiuUpdater/1"})
|
||||
with urlopen(request, timeout=timeout) as response:
|
||||
payload = response.read(self.MAX_MANIFEST_BYTES + 1)
|
||||
if len(payload) > self.MAX_MANIFEST_BYTES:
|
||||
raise ValueError("manifest exceeds the size limit")
|
||||
data = json.loads(payload.decode("utf-8"))
|
||||
if not isinstance(data, Mapping):
|
||||
raise ValueError("manifest JSON must be an object")
|
||||
return UpdateManifest.from_mapping(data)
|
||||
|
||||
def check(
|
||||
self, source: str, current: str | SemVer, channel: str = "stable"
|
||||
) -> UpdateCheckResult:
|
||||
try:
|
||||
current_version = SemVer.parse(current)
|
||||
except ValueError as error:
|
||||
return UpdateCheckResult("error", SemVer(0, 0, 0), None, str(error))
|
||||
try:
|
||||
manifest = self.fetch_manifest(source)
|
||||
except Exception as error: # network and malformed manifests are UI states
|
||||
return UpdateCheckResult("error", current_version, None, str(error))
|
||||
requested_channel = str(channel).strip().casefold()
|
||||
if manifest.channel != requested_channel:
|
||||
return UpdateCheckResult(
|
||||
"incompatible",
|
||||
current_version,
|
||||
manifest,
|
||||
f"manifest channel {manifest.channel!r} does not match {requested_channel!r}",
|
||||
)
|
||||
if not manifest.is_compatible_with(current_version):
|
||||
return UpdateCheckResult(
|
||||
"incompatible",
|
||||
current_version,
|
||||
manifest,
|
||||
"current version is below the manifest minimum supported version",
|
||||
)
|
||||
if manifest.version.is_newer_than(current_version):
|
||||
return UpdateCheckResult("available", current_version, manifest, "new version available")
|
||||
return UpdateCheckResult("up-to-date", current_version, manifest, "already up to date")
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Download, verify, and stage update archives without installing them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import (
|
||||
HTTPRedirectHandler,
|
||||
Request,
|
||||
build_opener,
|
||||
)
|
||||
import zipfile
|
||||
|
||||
from dx_productivity.update import keys
|
||||
from dx_productivity.update.models import UpdateManifest, require_allowed_url
|
||||
from dx_productivity.update.verification import sha256_file, verify_ed25519
|
||||
|
||||
|
||||
MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB safety cap
|
||||
|
||||
|
||||
class UpdateVerificationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class _SafeRedirectHandler(HTTPRedirectHandler):
|
||||
"""Block redirects that leave the allowed schemes (https -> http etc.)."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
if urlparse(newurl).scheme.casefold() not in {"https", "file"}:
|
||||
raise HTTPError(
|
||||
req.full_url,
|
||||
code,
|
||||
"redirect to a disallowed scheme was blocked",
|
||||
headers,
|
||||
fp,
|
||||
)
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
_OPENER = build_opener(_SafeRedirectHandler)
|
||||
|
||||
|
||||
class UpdateStager:
|
||||
def __init__(self, *, public_key: bytes | None = None) -> None:
|
||||
self.public_key = (
|
||||
public_key if public_key is not None else keys.release_public_key()
|
||||
)
|
||||
|
||||
def download_and_verify(self, manifest: UpdateManifest, destination: Path) -> Path:
|
||||
destination = Path(destination)
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
require_allowed_url(manifest.package_url)
|
||||
final_path = destination / f"{manifest.version}.zip"
|
||||
if final_path.exists():
|
||||
# Reuse a previously staged archive when it still verifies; a
|
||||
# corrupted leftover is replaced by a fresh download.
|
||||
try:
|
||||
self._verify_archive(final_path, manifest)
|
||||
return final_path
|
||||
except UpdateVerificationError:
|
||||
final_path.unlink(missing_ok=True)
|
||||
part_path = destination / f"{manifest.version}.zip.part"
|
||||
try:
|
||||
request = Request(
|
||||
manifest.package_url, headers={"User-Agent": "YiyezhqiuUpdater/1"}
|
||||
)
|
||||
with _OPENER.open(request, timeout=30.0) as response, part_path.open(
|
||||
"wb"
|
||||
) as output:
|
||||
total = 0
|
||||
while True:
|
||||
block = response.read(1024 * 1024)
|
||||
if not block:
|
||||
break
|
||||
total += len(block)
|
||||
if total > MAX_DOWNLOAD_BYTES:
|
||||
raise UpdateVerificationError(
|
||||
"download exceeded the size limit"
|
||||
)
|
||||
output.write(block)
|
||||
self._verify_archive(part_path, manifest)
|
||||
part_path.replace(final_path)
|
||||
return final_path
|
||||
except UpdateVerificationError:
|
||||
if part_path.exists():
|
||||
part_path.unlink()
|
||||
raise
|
||||
except Exception as error:
|
||||
if part_path.exists():
|
||||
part_path.unlink()
|
||||
raise UpdateVerificationError(str(error)) from error
|
||||
|
||||
def _verify_archive(self, path: Path, manifest: UpdateManifest) -> None:
|
||||
if sha256_file(path) != manifest.sha256:
|
||||
raise UpdateVerificationError("sha256 digest mismatch")
|
||||
if not zipfile.is_zipfile(path):
|
||||
raise UpdateVerificationError("package is not a ZIP archive")
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
for member in archive.infolist():
|
||||
member_path = (path.parent / "_extract" / member.filename).resolve()
|
||||
if not member_path.is_relative_to(
|
||||
(path.parent / "_extract").resolve()
|
||||
):
|
||||
raise UpdateVerificationError("ZIP path traversal detected")
|
||||
if manifest.signature is None:
|
||||
if manifest.channel == "stable":
|
||||
raise UpdateVerificationError(
|
||||
"signature required for stable channel"
|
||||
)
|
||||
elif self.public_key is None:
|
||||
raise UpdateVerificationError("public key is required")
|
||||
else:
|
||||
try:
|
||||
signature = base64.b64decode(manifest.signature, validate=True)
|
||||
except Exception as error:
|
||||
raise UpdateVerificationError(
|
||||
"invalid signature encoding"
|
||||
) from error
|
||||
if not verify_ed25519(self.public_key, path.read_bytes(), signature):
|
||||
raise UpdateVerificationError(
|
||||
"ed25519 signature verification failed"
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Cryptographic verification primitives for portable update packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with open(path, "rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def verify_ed25519(public_key: bytes, payload: bytes, signature: bytes) -> bool:
|
||||
try:
|
||||
Ed25519PublicKey.from_public_bytes(public_key).verify(signature, payload)
|
||||
except (InvalidSignature, ValueError):
|
||||
return False
|
||||
return True
|
||||
Reference in new issue
Block a user