"""Offline KiCad import and generated board-viewer asset pipeline.""" from __future__ import annotations import json import os import platform import shutil import subprocess import tempfile import uuid import xml.etree.ElementTree as ET from collections.abc import Callable, Mapping from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path from typing import Any, Protocol from jsonschema import Draft202012Validator from .assets import sha256_file, validate_generated_assets from .data import build_board_data from .ipcd356 import IpCd356AlignmentError, validate_ipcd356_alignment from .pcb import parse_kicad_pcb from .photo import PhotoOverlayError, prepare_photo_overlay from .regression import BoardRegressionError, validate_product_regression ROOT = Path(__file__).resolve().parents[3] DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json" ANNOTATION_SCHEMA = ROOT / "schemas" / "board_viewer_annotations.schema.json" GENERATOR_VERSION = "1.2.0" GENERATOR_SOURCE_PATHS = { "generator_pipeline": Path(__file__).resolve(), "generator_data": ROOT / "tools" / "board-viewer" / "board_viewer" / "data.py", "generator_annotations": ROOT / "tools" / "board-viewer" / "board_viewer" / "annotations.py", "generator_eligibility": ROOT / "tools" / "board-viewer" / "board_viewer" / "eligibility.py", "generator_pcb": ROOT / "tools" / "board-viewer" / "board_viewer" / "pcb.py", "generator_sexpr": ROOT / "tools" / "board-viewer" / "board_viewer" / "sexpr.py", "generator_ipcd356": ROOT / "tools" / "board-viewer" / "board_viewer" / "ipcd356.py", "generator_photo": ROOT / "tools" / "board-viewer" / "board_viewer" / "photo.py", "generator_regression": ROOT / "tools" / "board-viewer" / "board_viewer" / "regression.py", "schema_data": DATA_SCHEMA, "schema_annotations": ANNOTATION_SCHEMA, } class GenerationError(RuntimeError): """Raised when a generated bundle cannot be completed and validated.""" class CommandResult(Protocol): returncode: int stdout: str stderr: str Runner = Callable[[list[str], Path], CommandResult] @dataclass class GenerationConfig: brd_path: Path inventory_path: Path annotations_path: Path output_dir: Path kicad_cli: Path board_name: str required_kicad_version: str = "10.0.4" expected_counts: Mapping[str, int] | None = None expected_front_only: bool = True product_regression: bool = False photo_root: Path = ROOT temp_parent: Path | None = None def _default_runner(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]: return subprocess.run( command, cwd=cwd, check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", ) def _run_checked(runner: Runner, command: list[str], cwd: Path) -> CommandResult: result = runner(command, cwd) if result.returncode != 0: detail = (result.stderr or result.stdout or "command failed").strip() raise GenerationError(detail) return result def _load_json(path: Path) -> dict[str, Any]: try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise GenerationError(f"cannot read JSON {path}: {exc}") from exc if not isinstance(payload, dict): raise GenerationError(f"JSON root must be an object: {path}") return payload def _validate_schema(payload: object, schema_path: Path, label: str) -> None: schema = _load_json(schema_path) errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda item: list(item.path)) if errors: locations = [".".join(str(part) for part in error.path) or "" for error in errors[:5]] raise GenerationError(f"{label} schema validation failed at: {', '.join(locations)}") def _ensure_outside_repository(path: Path) -> Path: resolved = path.resolve() try: resolved.relative_to(ROOT.resolve()) except ValueError: return resolved raise GenerationError("temporary directory must be outside repository") def _verify_inputs(config: GenerationConfig) -> Path: for path, label in ( (config.brd_path, "BRD source"), (config.inventory_path, "pin inventory"), (config.annotations_path, "annotations"), (config.kicad_cli, "KiCad CLI"), ): if not Path(path).is_file(): raise GenerationError(f"missing {label}: {path}") temp_parent = config.temp_parent or Path(tempfile.gettempdir()) temp_parent = _ensure_outside_repository(Path(temp_parent)) temp_parent.mkdir(parents=True, exist_ok=True) return temp_parent def _verify_kicad_version(config: GenerationConfig, runner: Runner, cwd: Path) -> str: result = _run_checked(runner, [str(config.kicad_cli), "--version"], cwd) version = result.stdout.strip().splitlines()[0] if result.stdout.strip() else "unknown" if version != config.required_kicad_version: raise GenerationError( f"board viewer generation requires KiCad {config.required_kicad_version}, found {version}" ) return version def _write_json(path: Path, payload: object) -> None: path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") def _normalize_svg(path: Path, title: str) -> tuple[float, float]: try: tree = ET.parse(path) except (OSError, ET.ParseError) as exc: raise GenerationError(f"invalid SVG {path.name}: {exc}") from exc root = tree.getroot() if root.tag.rsplit("}", 1)[-1] != "svg": raise GenerationError(f"invalid SVG root: {path.name}") title_element = next((item for item in root if item.tag.rsplit("}", 1)[-1] == "title"), None) if title_element is not None: title_element.text = title view_box = root.get("viewBox", "").replace(",", " ").split() if len(view_box) != 4: raise GenerationError(f"SVG has no usable viewBox: {path.name}") try: width, height = float(view_box[2]), float(view_box[3]) except ValueError as exc: raise GenerationError(f"SVG has invalid viewBox: {path.name}") from exc ET.register_namespace("", "http://www.w3.org/2000/svg") ET.register_namespace("xlink", "http://www.w3.org/1999/xlink") tree.write(path, encoding="utf-8", xml_declaration=True) return width, height def _validate_counts(payload: Mapping[str, object], config: GenerationConfig) -> None: counts = payload["counts"] if not isinstance(counts, Mapping): raise GenerationError("generated board counts are missing") if config.expected_counts: mismatches = [ f"{name}={counts.get(name)} expected {expected}" for name, expected in config.expected_counts.items() if counts.get(name) != expected ] if mismatches: raise GenerationError("board regression mismatch: " + ", ".join(mismatches)) sides = counts.get("sides", {}) if config.expected_front_only and isinstance(sides, Mapping) and sides.get("back") != 0: raise GenerationError(f"board regression mismatch: target back-side count is {sides.get('back')}") def _import_board(config: GenerationConfig, runner: Runner, work: Path) -> tuple[Path, dict[str, Any]]: imported = work / "board.kicad_pcb" report_path = work / "import-report.json" command = [ str(config.kicad_cli), "pcb", "import", "--format", "auto", "--output", str(imported), "--report-format", "json", "--report-file", str(report_path), str(config.brd_path.resolve()), ] _run_checked(runner, command, work) if not imported.is_file() or not report_path.is_file(): raise GenerationError("KiCad import did not create the board and report") report = _load_json(report_path) if report.get("errors"): raise GenerationError(f"KiCad import report contains errors: {report['errors']}") return imported, report # Front layers keep board coordinates (top-down from component side). FRONT_SVG_LAYERS = { "board-mask-edge.svg": "F.Mask,Edge.Cuts", "board-silkscreen.svg": "F.SilkS,Edge.Cuts", "board-copper.svg": "F.Cu,Edge.Cuts", } # Back layers export with KiCad --mirror (flip about the vertical/Y axis) so the # image matches a physical board flipped left-right with the top edge kept up. # Hotspot X must use width - x when the viewer shows these assets. BACK_SVG_LAYERS = { "board-mask-edge-back.svg": "B.Mask,Edge.Cuts", "board-silkscreen-back.svg": "B.SilkS,Edge.Cuts", "board-copper-back.svg": "B.Cu,Edge.Cuts", } SVG_LAYERS = {**FRONT_SVG_LAYERS, **BACK_SVG_LAYERS} BACK_MIRROR_AXIS = "y" def _export_svgs( config: GenerationConfig, runner: Runner, imported: Path, assets_dir: Path, board_data: Mapping[str, object], ) -> None: board_meta = board_data["board"] if not isinstance(board_meta, Mapping) or not isinstance(board_meta.get("view_box"), Mapping): raise GenerationError("generated board view box is missing") expected_width = float(board_meta["view_box"]["width"]) expected_height = float(board_meta["view_box"]["height"]) for filename, layers in FRONT_SVG_LAYERS.items(): _export_one_svg( config, runner, imported, assets_dir, filename, layers, expected_width=expected_width, expected_height=expected_height, mirror=False, ) for filename, layers in BACK_SVG_LAYERS.items(): _export_one_svg( config, runner, imported, assets_dir, filename, layers, expected_width=expected_width, expected_height=expected_height, mirror=True, ) def _export_one_svg( config: GenerationConfig, runner: Runner, imported: Path, assets_dir: Path, filename: str, layers: str, *, expected_width: float, expected_height: float, mirror: bool, ) -> None: output = assets_dir / filename command = [ str(config.kicad_cli), "pcb", "export", "svg", "--mode-single", "--output", str(output), "--layers", layers, "--page-size-mode", "2", "--fit-page-to-board", "--exclude-drawing-sheet", ] if mirror: command.append("--mirror") command.append(str(imported)) _run_checked(runner, command, assets_dir) if not output.is_file(): raise GenerationError(f"KiCad SVG export did not create {filename}") width, height = _normalize_svg(output, f"FCB board viewer {filename}") if abs(width - expected_width) > 0.1 or abs(height - expected_height) > 0.1: raise GenerationError( f"SVG viewBox mismatch for {filename}: {width}x{height}, expected {expected_width}x{expected_height}" ) def _export_and_validate_ipcd356( config: GenerationConfig, runner: Runner, imported: Path, work: Path, board_data: Mapping[str, object], ) -> dict[str, object]: output = work / "board.d356" command = [ str(config.kicad_cli), "pcb", "export", "ipcd356", "--output", str(output), str(imported), ] _run_checked(runner, command, work) if not output.is_file(): raise GenerationError("KiCad IPC-D-356 export did not create board.d356") try: return validate_ipcd356_alignment(board_data, output) except IpCd356AlignmentError as exc: raise GenerationError(f"IPC-D-356 cross-check failed: {exc}") from exc def _asset_metadata(path: Path) -> dict[str, object]: return {"sha256": sha256_file(path), "bytes": path.stat().st_size} def manifest_source_path(path: Path | str, repository_root: Path | str = ROOT) -> str: resolved = Path(path).resolve() repository = Path(repository_root).resolve() try: return resolved.relative_to(repository).as_posix() except ValueError: return str(resolved) def _publish_directory(source: Path, target: Path) -> None: target.parent.mkdir(parents=True, exist_ok=True) suffix = uuid.uuid4().hex staging = target.parent / f".{target.name}.stage-{suffix}" backup = target.parent / f".{target.name}.backup-{suffix}" shutil.copytree(source, staging) validate_generated_assets(staging) moved_old = False try: if target.exists(): os.replace(target, backup) moved_old = True os.replace(staging, target) except Exception: if moved_old and backup.exists() and not target.exists(): os.replace(backup, target) raise finally: if staging.exists(): shutil.rmtree(staging) if backup.exists(): shutil.rmtree(backup) def generate_assets(config: GenerationConfig, *, runner: Runner = _default_runner) -> dict[str, object]: temp_parent = _verify_inputs(config) inventory = _load_json(config.inventory_path) annotations = _load_json(config.annotations_path) _validate_schema(annotations, ANNOTATION_SCHEMA, "annotations") with tempfile.TemporaryDirectory(prefix="cpld-board-viewer-", dir=temp_parent) as temporary: work = Path(temporary) kicad_version = _verify_kicad_version(config, runner, work) imported, import_report = _import_board(config, runner, work) parsed = parse_kicad_pcb(imported) board_data = build_board_data( parsed, inventory, annotations, board_name=config.board_name, ) assets_dir = work / "generated" assets_dir.mkdir() try: prepared_photo = prepare_photo_overlay( annotations.get("photo_overlay"), repository_root=config.photo_root, assets_dir=assets_dir, board_bounds=parsed.bounds, ) except PhotoOverlayError as exc: raise GenerationError(f"photo overlay validation failed: {exc}") from exc board_data["photo_overlay"] = prepared_photo.data if prepared_photo else None _validate_counts(board_data, config) if config.product_regression: try: validate_product_regression(board_data) except BoardRegressionError as exc: raise GenerationError(f"product board regression failed: {exc}") from exc _validate_schema(board_data, DATA_SCHEMA, "board data") ipcd356_verification = _export_and_validate_ipcd356( config, runner, imported, work, board_data, ) _write_json(assets_dir / "board-data.json", board_data) _write_json(assets_dir / "import-report.json", import_report) _export_svgs(config, runner, imported, assets_dir, board_data) asset_names = ["board-data.json", *SVG_LAYERS, "import-report.json"] if prepared_photo: asset_names.append(prepared_photo.asset_path.name) counts = board_data["counts"] sources = { "brd": {"path": manifest_source_path(config.brd_path), "sha256": sha256_file(config.brd_path)}, "inventory": { "path": manifest_source_path(config.inventory_path), "sha256": sha256_file(config.inventory_path), }, "annotations": { "path": manifest_source_path(config.annotations_path), "sha256": sha256_file(config.annotations_path), }, **{ name: {"path": manifest_source_path(path), "sha256": sha256_file(path)} for name, path in GENERATOR_SOURCE_PATHS.items() }, } if prepared_photo: sources["photo"] = { "path": manifest_source_path(prepared_photo.source_path), "sha256": sha256_file(prepared_photo.source_path), } build_info = { "schema": "board-viewer-build-info-v1", "generated_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"), "generator_version": GENERATOR_VERSION, "toolchain": {"python": platform.python_version(), "kicad": kicad_version}, "sources": sources, "assets": {name: _asset_metadata(assets_dir / name) for name in asset_names}, "verification": { "ipcd356": ipcd356_verification, "side_views": { "front_layers": list(FRONT_SVG_LAYERS), "back_layers": list(BACK_SVG_LAYERS), "back_mirror_axis": BACK_MIRROR_AXIS, "back_svg_export_mirrored": True, "convention": ( "Back SVGs use KiCad --mirror (flip about vertical/Y axis). " "Matches physical board flipped left-right with top edge kept up; " "viewer hotspot X = board_width - view_position.x." ), }, }, "counts": { "footprints": counts["footprints"], "touchpoints": counts["touchpoints"], "pads": counts["pads"], "resistors": counts["resistors"], "resistor_pads": counts["resistor_pads"], }, } _write_json(assets_dir / "build-info.json", build_info) validate_generated_assets(assets_dir) try: _publish_directory(assets_dir, config.output_dir) except OSError as exc: raise GenerationError(f"cannot publish generated assets: {exc}") from exc return {"status": "pass", "output_dir": str(config.output_dir), "build_info": build_info}